dbarison
9/30/2015 - 12:12 PM

gistfile1.txt

class VideoCompresser < Paperclip::Processor

  # def initialize(file, options = {}, attachment = nil)
  #     super
  #     @file     = file
  #     @whiny    = options[:whiny].nil? ? true : options[:whiny]
  #     @basename = File.basename(@file.path, File.extname(@file.path))
  #     @format   = options[:format]
  #     @geometry = options[:geometry].nil? ? nil : Paperclip::Geometry.parse(options[:geometry])
  #   end

  # con ffmpeg
  # cmd = "-y -i '#{File.expand_path(@file.path)}' -acodec libfaac -ab 44100 -vcodec libx264 -b 256k -s 480x320 '#{File.expand_path(dst.path)}'"
  # con ffmpeg2theora
  # cmd = "-a 3 -v 9  -x 480 -y 320 '#{File.expand_path(@file.path)}' -o '#{File.expand_path(dst.path)}'"


  def make
    #@geometry = options[:geometry].nil? ? nil : Paperclip::Geometry.parse(options[:geometry])
    #begin
      case @options[:format]
      when :png
        exec_command('ffmpegbin', 'convert') do |input, output|
          ["-itsoffset -1 -i '#{input}' -y -vcodec mjpeg -vframes 1 -an -f rawvideo '#{output}'",
           "-resize '#{@options[:geometry]}' '#{output}' '#{output}'"]
        end
      when :mp4
        exec_command do |input, output|
          ["-y -i '#{input}' -c:v libx264 -strict experimental -b:v 1024k -f mp4 -b:a 128k -s #{@options[:geometry]} '#{output}'"]
        end
      when :ogg
        exec_command do |input, output|
          ["-y -i '#{input}' -c:v libtheora -c:a libvorbis -b:v 1024k -f ogg -b:a 128k -s #{@options[:geometry]} '#{output}'"]
        end
      when :webm
        exec_command do |input, output|
          ["-y -i '#{input}' -c:v libvpx -b:v 1024k -b:a 128k -f webm -s #{@options[:geometry]} '#{output}'"]
        end
      when :flv
        exec_command do |input, output|
          ["-y -i '#{input}' -f flv -ab 44100 -s '#{@options[:geometry]}' '#{output}'"]
        end
      else # unknown format, do nothing
        return @file
      end
    # rescue Paperclip::PaperclipError
    #   raise Paperclip::PaperclipError, "There was an error processing the file #{@file}" if @whiny
    # end
  end

  private

  def exec_command(*args)
    basename = File.basename(@file.path, File.extname(@file.path))
    dst = Tempfile.new(basename)
    dst.binmode
    cmds = yield(File.expand_path(@file.path), File.expand_path(dst.path))
    cmds.each_with_index do |cmd, i|
      cmd.gsub!(/\s+/, ' ')
      prog = args[i]
      prog ||= 'ffmpegbin'
      success = Paperclip.run(prog, cmd, :swallow_stderr => false)
    end
    return dst
  end

end