Skip to content
Snippets Groups Projects
video_thumbnail_generator.rb 901 B
Newer Older
Matheus Agio Nerone's avatar
Matheus Agio Nerone committed
require 'streamio-ffmpeg'

module Thumbnail
  module Strategies
    class VideoThumbnailGenerator < ::Thumbnail::GeneratableStrategy

      def generate(media)
        movie = build_ffmpeg_movie media.path
        hash = SecureRandom.hex(10)
        output = "/tmp/#{hash}.jpg"

        if movie.valid? and !movie.video_codec.nil?
          frame = (movie.duration * 25/100).floor
          movie.screenshot(output,
                           {seek_time: frame, resolution: size},
                           preserve_aspect_ratio: :width)
          File.open output
        else
          raise "ERROR: Video's thumbnail was not generated. (NULL_CODEC)"
        end
      end

      def can_generate?(media)
        super { 'video' }
Matheus Agio Nerone's avatar
Matheus Agio Nerone committed
      end
      private

      def size
        '530x300'
      end

      def build_ffmpeg_movie(path)
        ::FFMPEG::Movie.new(path)
      end

    end
  end
end