Skip to content

Instantly share code, notes, and snippets.

@mbajur
Created March 5, 2014 18:43
Show Gist options
  • Save mbajur/eea25199f67ac89ac348 to your computer and use it in GitHub Desktop.
Save mbajur/eea25199f67ac89ac348 to your computer and use it in GitHub Desktop.
class ExtractKeyframesWorker
include Sidekiq::Worker
def perform(video_id, grinder_id)
video = Video.find(video_id)
download_as = video.tmp_file.path
# Destroy all present keyframes
video.keyframes.destroy_all
# Convert duration to integer
duration = video.file_meta['duration'].to_i
# Load video file
movie = FFMPEG::Movie.new(download_as)
# Determine how many keyframes should be extracted
# based on movie duration.
if duration > 60
frames_to_extract = 9
elsif 60 > duration && duration > 30
frames_to_extract = 6
else
frames_to_extract = 3
end
# Extract the keyframes and save them to db
for i in 1..(frames_to_extract)
seek_time = (duration / frames_to_extract) * i
image = movie.screenshot(
Rails.root.join('tmp', seek_time.to_s + '.jpg'),
seek_time: seek_time
)
Rails.logger.debug "Taking screenshot from #{seek_time}s"
Keyframe.create(video_id: video.id, file: File.open(image.path))
# Destroy image
File.delete(image.path)
end
# Destroy downloaded video
# File.delete(Rails.root.join('tmp', download_as))
logger.info "Keyframes extracted!"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment