transcoder.rb 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # frozen_string_literal: true
  2. module Paperclip
  3. # This transcoder is only to be used for the MediaAttachment model
  4. # to check when uploaded videos are actually gifv's
  5. class Transcoder < Paperclip::Processor
  6. # This is the H.264 "High" value taken from https://www.dr-lex.be/info-stuff/videocalc.html
  7. BITS_PER_PIXEL = 0.11
  8. def initialize(file, options = {}, attachment = nil)
  9. super
  10. @current_format = File.extname(@file.path)
  11. @basename = File.basename(@file.path, @current_format)
  12. @format = options[:format]
  13. @time = options[:time] || 3
  14. @passthrough_options = options[:passthrough_options]
  15. @convert_options = options[:convert_options].dup
  16. @vfr_threshold = options[:vfr_frame_rate_threshold]
  17. end
  18. def make
  19. metadata = VideoMetadataExtractor.new(@file.path)
  20. raise Paperclip::Error, "Error while transcoding #{@file.path}: unsupported file" unless metadata.valid?
  21. update_attachment_type(metadata)
  22. update_options_from_metadata(metadata)
  23. destination = Tempfile.new([@basename, @format ? ".#{@format}" : ''])
  24. destination.binmode
  25. @output_options = @convert_options[:output]&.dup || {}
  26. @input_options = @convert_options[:input]&.dup || {}
  27. case @format.to_s
  28. when /jpg$/, /jpeg$/, /png$/, /gif$/
  29. @input_options['ss'] = @time
  30. @output_options['f'] = 'image2'
  31. @output_options['vframes'] = 1
  32. when 'mp4'
  33. unless eligible_to_passthrough?(metadata)
  34. size_limit_in_bits = MediaAttachment::VIDEO_LIMIT * 8
  35. desired_bitrate = (metadata.width * metadata.height * 30 * BITS_PER_PIXEL).floor
  36. duration = [metadata.duration, 1].max
  37. maximum_bitrate = (size_limit_in_bits / duration).floor - 192_000 # Leave some space for the audio stream
  38. bitrate = [desired_bitrate, maximum_bitrate].min
  39. @output_options['b:v'] = bitrate
  40. @output_options['maxrate'] = bitrate + 192_000
  41. @output_options['bufsize'] = bitrate * 5
  42. if high_vfr?(metadata)
  43. @output_options['vsync'] = 'vfr'
  44. @output_options['r'] = @vfr_threshold
  45. end
  46. end
  47. end
  48. command_arguments, interpolations = prepare_command(destination)
  49. begin
  50. command = Terrapin::CommandLine.new('ffmpeg', command_arguments.join(' '), logger: Paperclip.logger)
  51. command.run(interpolations)
  52. rescue Terrapin::ExitStatusError => e
  53. raise Paperclip::Error, "Error while transcoding #{@basename}: #{e}"
  54. rescue Terrapin::CommandNotFoundError
  55. raise Paperclip::Errors::CommandNotFoundError, 'Could not run the `ffmpeg` command. Please install ffmpeg.'
  56. end
  57. destination
  58. end
  59. private
  60. def prepare_command(destination)
  61. command_arguments = ['-nostdin']
  62. interpolations = {}
  63. interpolation_keys = 0
  64. @input_options.each_pair do |key, value|
  65. interpolation_key = interpolation_keys
  66. command_arguments << "-#{key} :#{interpolation_key}"
  67. interpolations[interpolation_key] = value
  68. interpolation_keys += 1
  69. end
  70. command_arguments << '-i :source'
  71. interpolations[:source] = @file.path
  72. @output_options.each_pair do |key, value|
  73. interpolation_key = interpolation_keys
  74. command_arguments << "-#{key} :#{interpolation_key}"
  75. interpolations[interpolation_key] = value
  76. interpolation_keys += 1
  77. end
  78. command_arguments << '-y :destination'
  79. interpolations[:destination] = destination.path
  80. [command_arguments, interpolations]
  81. end
  82. def update_options_from_metadata(metadata)
  83. return unless eligible_to_passthrough?(metadata)
  84. @format = @passthrough_options[:options][:format] || @format
  85. @time = @passthrough_options[:options][:time] || @time
  86. @convert_options = @passthrough_options[:options][:convert_options].dup
  87. end
  88. def high_vfr?(metadata)
  89. @vfr_threshold && metadata.r_frame_rate && metadata.r_frame_rate > @vfr_threshold
  90. end
  91. def eligible_to_passthrough?(metadata)
  92. @passthrough_options && @passthrough_options[:video_codecs].include?(metadata.video_codec) && @passthrough_options[:audio_codecs].include?(metadata.audio_codec) && @passthrough_options[:colorspaces].include?(metadata.colorspace)
  93. end
  94. def update_attachment_type(metadata)
  95. @attachment.instance.type = MediaAttachment.types[:gifv] unless metadata.audio_codec
  96. end
  97. end
  98. end