|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'fileutils' |
| 4 | +require 'tmpdir' |
| 5 | + |
| 6 | +require_relative 'media' |
| 7 | + |
| 8 | +module FFMPEG |
| 9 | + # The Remuxer class is responsible for remuxing multimedia files via stream copy. |
| 10 | + # It attempts a direct stream copy first, and if that fails (e.g. due to corrupted |
| 11 | + # timestamps), it falls back to extracting raw Annex B streams and re-muxing them |
| 12 | + # with a corrected frame rate. |
| 13 | + # |
| 14 | + # @example |
| 15 | + # remuxer = FFMPEG::Remuxer.new |
| 16 | + # status = remuxer.process('input.mp4', 'output.mp4') |
| 17 | + # status.success? # => true |
| 18 | + class Remuxer |
| 19 | + ANNEXB_CODEC_NAMES = %w[h264 hevc].freeze |
| 20 | + |
| 21 | + # @param name [String, nil] An optional name for the remuxer. |
| 22 | + # @param metadata [Hash, nil] Optional metadata to associate with the remuxer. |
| 23 | + # @param checks [Array<Symbol, Proc>] Checks to run on the output to determine success. |
| 24 | + # @param timeout [Integer, nil] Timeout in seconds for each ffmpeg command. |
| 25 | + def initialize(name: nil, metadata: nil, checks: %i[exist?], timeout: nil) |
| 26 | + @name = name |
| 27 | + @metadata = metadata |
| 28 | + @checks = checks |
| 29 | + @timeout = timeout |
| 30 | + end |
| 31 | + |
| 32 | + class << self |
| 33 | + # Returns true if the media has a video codec that supports lossless |
| 34 | + # Annex B bitstream extraction (H.264 or H.265). |
| 35 | + # |
| 36 | + # @param media [FFMPEG::Media] |
| 37 | + # @return [Boolean] |
| 38 | + def annexb?(media) |
| 39 | + media.video? && ANNEXB_CODEC_NAMES.include?(media.video_codec_name) |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + # Remuxes the media file to the given output path via stream copy. |
| 44 | + # If the initial stream copy fails and the video codec supports Annex B |
| 45 | + # extraction, it falls back to extracting raw streams and re-muxing with |
| 46 | + # a corrected frame rate. |
| 47 | + # |
| 48 | + # @param media [String, Pathname, URI, FFMPEG::Media] The media file to remux. |
| 49 | + # @param output_path [String, Pathname] The output path for the remuxed file. |
| 50 | + # @yield [report] Reports from the ffmpeg command (see FFMPEG::Reporters). |
| 51 | + # @return [FFMPEG::Transcoder::Status] |
| 52 | + def process(media, output_path, &) |
| 53 | + media = Media.new(media, load: false) unless media.is_a?(Media) |
| 54 | + |
| 55 | + status = ffmpeg_copy(media, output_path, &) |
| 56 | + return status if status.success? |
| 57 | + return status unless self.class.annexb?(media) |
| 58 | + |
| 59 | + Dir.mktmpdir do |tmpdir| |
| 60 | + annexb_extname = media.video_codec_name == 'hevc' ? '.h265' : '.h264' |
| 61 | + annexb_path = File.join(tmpdir, "remux#{annexb_extname}") |
| 62 | + annexb_filter = annexb_filter(media) |
| 63 | + annexb_status = ffmpeg_copy(media, '-map', '0:v:0', *annexb_filter, annexb_path, &) |
| 64 | + return annexb_status unless annexb_status.success? |
| 65 | + |
| 66 | + mka_path = File.join(tmpdir, 'remux.mka') |
| 67 | + mka_status = ffmpeg_copy(media, '-vn', mka_path, &) |
| 68 | + return mka_status unless mka_status.success? |
| 69 | + |
| 70 | + video = annexb_status.media.first |
| 71 | + audio = mka_status.media.first |
| 72 | + frame_rate = detect_frame_rate(video, audio) |
| 73 | + |
| 74 | + status = ffmpeg_copy( |
| 75 | + [video, audio, media], |
| 76 | + '-map', '0:v', |
| 77 | + '-map', '1:a', |
| 78 | + '-map_metadata', '2', |
| 79 | + output_path, |
| 80 | + inargs: %W[-r #{frame_rate}], |
| 81 | + & |
| 82 | + ) |
| 83 | + return status unless status.success? |
| 84 | + return status unless FFMPEG.exiftool_binary |
| 85 | + |
| 86 | + FFMPEG.exiftool_capture3( |
| 87 | + '-overwrite_original', |
| 88 | + "-rotation=#{media.rotation}", |
| 89 | + output_path |
| 90 | + ).tap do |_, stderr, exiftool_status| |
| 91 | + next if exiftool_status.success? |
| 92 | + |
| 93 | + status.warn!("ExifTool exited with non-zero status: #{exiftool_status.exitstatus}\n#{stderr.strip}") |
| 94 | + end |
| 95 | + |
| 96 | + status |
| 97 | + end |
| 98 | + end |
| 99 | + |
| 100 | + # Remuxes the media file to the given output path via stream copy, |
| 101 | + # raising an error if the remux fails. |
| 102 | + # |
| 103 | + # @param media [String, Pathname, URI, FFMPEG::Media] The media file to remux. |
| 104 | + # @param output_path [String, Pathname] The output path for the remuxed file. |
| 105 | + # @yield [report] Reports from the ffmpeg command (see FFMPEG::Reporters). |
| 106 | + # @return [FFMPEG::Transcoder::Status] |
| 107 | + def process!(media, output_path, &) |
| 108 | + process(media, output_path, &).assert! |
| 109 | + end |
| 110 | + |
| 111 | + protected |
| 112 | + |
| 113 | + def ffmpeg_copy(media, *args, inargs: [], &) |
| 114 | + media = [media] unless media.is_a?(Array) |
| 115 | + |
| 116 | + FFMPEG.ffmpeg_execute( |
| 117 | + *inargs.map(&:to_s), |
| 118 | + *media.map { ['-i', _1.path.to_s] }.flatten, |
| 119 | + '-c', |
| 120 | + 'copy', |
| 121 | + *args.map(&:to_s), |
| 122 | + timeout: @timeout, |
| 123 | + status: Transcoder::Status.new([args.last], checks: @checks), |
| 124 | + & |
| 125 | + ) |
| 126 | + end |
| 127 | + |
| 128 | + def annexb_filter(media) |
| 129 | + ['-bsf:v', "#{media.video_codec_name}_mp4toannexb"] |
| 130 | + end |
| 131 | + |
| 132 | + def detect_frame_rate(video, audio) |
| 133 | + stdout, = FFMPEG.ffprobe_capture3( |
| 134 | + '-v', 'quiet', |
| 135 | + '-count_packets', |
| 136 | + '-select_streams', 'v:0', |
| 137 | + '-show_entries', 'stream=nb_read_packets', |
| 138 | + '-of', 'csv=p=0', |
| 139 | + video.path |
| 140 | + ) |
| 141 | + frame_count = stdout.strip.to_i |
| 142 | + |
| 143 | + stdout, = FFMPEG.ffprobe_capture3( |
| 144 | + '-v', 'quiet', |
| 145 | + '-show_entries', 'format=duration', |
| 146 | + '-of', 'csv=p=0', |
| 147 | + audio.path |
| 148 | + ) |
| 149 | + duration = stdout.strip.to_f |
| 150 | + |
| 151 | + (frame_count.to_f / duration).round |
| 152 | + end |
| 153 | + end |
| 154 | +end |
0 commit comments