Skip to main content

rff/
transcode.rs

1//! Transcoding — the engine side of `ffmpeg`.
2//!
3//! The pipeline is the classic FFmpeg shape:
4//!
5//! ```text
6//!   demuxer ─▶ decoder ─▶ [filters] ─▶ encoder ─▶ muxer
7//!   (input)    (raw frames pass through the middle)      (output)
8//! ```
9//!
10//! [`TranscodeSpec`] is the declarative description of a job — inputs, an
11//! output, and the codecs to use. [`run`] resolves that spec against an
12//! [`Engine`] (finding the demuxer, decoders, encoders, and muxer) and then
13//! drives the loop to completion.
14//!
15//! Each input stream is either **transcoded** (decode → re-encode) when an
16//! output codec is requested for its media type, or **stream-copied**
17//! (remuxed packet-for-packet) when none is — the same `-c:v copy` distinction
18//! FFmpeg draws. Video runs through the `-vf` filter graph (scale/crop); audio
19//! is automatically resampled to a rate the target encoder accepts (FFmpeg's
20//! implicit `aresample`).
21
22use std::path::PathBuf;
23
24use rff_codec::{CodecParams, Decoder, Encoder};
25use rff_core::{
26    AudioFrame, CodecId, ColorRange, Dictionary, Error, Frame, MediaType, Packet, PixelFormat,
27    Result, SampleFormat, VideoFrame,
28};
29use rff_filter::{FilterChain, FilterComplex};
30
31use rff_format::{Chapter, Muxer, Stream, TrackReference};
32use rff_resample::Resampler;
33
34use crate::Engine;
35
36/// `RFF_PHASES=1`: wall time per phase of the transcode loop, on stderr at the
37/// end of [`run`] -- the outside-the-codec view (demux, decode, the conform
38/// chain, encode, mux) that a codec's own stage profiler cannot see. A gap
39/// between a codec's core throughput and the CLI's is plumbing, and this is
40/// what locates it (codec-memory-copies step 0). Off by default: one cached
41/// flag test per call, and `Instant` is never touched unless it is set.
42mod phases {
43    use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
44    use std::sync::OnceLock;
45
46    pub static OPEN: AtomicU64 = AtomicU64::new(0);
47    pub static DEMUX: AtomicU64 = AtomicU64::new(0);
48    pub static DECODE: AtomicU64 = AtomicU64::new(0);
49    pub static CONFORM: AtomicU64 = AtomicU64::new(0);
50    pub static ENCODE: AtomicU64 = AtomicU64::new(0);
51    pub static MUX: AtomicU64 = AtomicU64::new(0);
52
53    pub fn on() -> bool {
54        static ON: OnceLock<bool> = OnceLock::new();
55        *ON.get_or_init(|| std::env::var_os("RFF_PHASES").is_some())
56    }
57
58    /// Run `f`, charging its wall time to `acc` when phases are on.
59    pub fn time<T>(acc: &AtomicU64, f: impl FnOnce() -> T) -> T {
60        if !on() {
61            return f();
62        }
63        let t = std::time::Instant::now();
64        let r = f();
65        acc.fetch_add(t.elapsed().as_nanos() as u64, Relaxed);
66        r
67    }
68
69    pub fn report(total: std::time::Duration) {
70        let total_ns = total.as_nanos().max(1) as f64;
71        eprintln!("--- rff phases (total {:.1} ms) ---", total_ns / 1e6);
72        let mut sum = 0u64;
73        for (name, acc) in [
74            ("open", &OPEN),
75            ("demux", &DEMUX),
76            ("decode", &DECODE),
77            ("conform", &CONFORM),
78            ("encode", &ENCODE),
79            ("mux", &MUX),
80        ] {
81            let ns = acc.swap(0, Relaxed);
82            sum += ns;
83            eprintln!(
84                "  {name:<8} {:>9.1} ms  {:>5.1}%",
85                ns as f64 / 1e6,
86                100.0 * ns as f64 / total_ns
87            );
88        }
89        let rest = total_ns - sum as f64;
90        eprintln!(
91            "  {:<8} {:>9.1} ms  {:>5.1}%",
92            "other",
93            rest / 1e6,
94            100.0 * rest / total_ns
95        );
96    }
97}
98
99/// Codecs whose decoded output is inherently full-range (they decode to RGB, or
100/// are defined on 0-255 samples). JPEG is the canonical case: the standard has
101/// no limited-range mode, which is why FFmpeg calls its pixel formats `yuvj*`.
102fn is_full_range_codec(codec: CodecId) -> bool {
103    matches!(
104        codec,
105        CodecId::Jpeg | CodecId::Png | CodecId::Gif | CodecId::Webp | CodecId::Exr
106    )
107}
108
109/// Codecs whose decoders hand out packed RGB(A) frames.
110fn decodes_to_rgb(codec: CodecId) -> bool {
111    matches!(
112        codec,
113        CodecId::Png | CodecId::Gif | CodecId::Webp | CodecId::Jxl | CodecId::Exr
114    )
115}
116
117/// What range this stream's decoded frames are actually in.
118///
119/// An `Unspecified` stream is not "unknown, do nothing" — every consumer has to
120/// pick something, so pick it here, once, explicitly:
121/// full-range for codecs that are defined that way, limited-range otherwise
122/// (the video convention, and what an untagged y4m means).
123///
124/// Before the codec default, an untagged H.264 stream's own SPS is asked: its
125/// VUI carries `video_full_range_flag`, which is how a full-range stream in a
126/// container without colour metadata (FLV, a Matroska file without `Colour`)
127/// still round-trips.
128fn effective_color_range(stream: &Stream) -> ColorRange {
129    match stream.color_range {
130        ColorRange::Unspecified => match extradata_color_range(stream) {
131            Some(range) => range,
132            None if is_full_range_codec(stream.codec_id) => ColorRange::Full,
133            None => ColorRange::Limited,
134        },
135        explicit => explicit,
136    }
137}
138
139/// The range signalled by the codec configuration in a stream's extradata
140/// (the SPS of an H.264 `avcC` or Annex-B header), if it signals one.
141fn extradata_color_range(stream: &Stream) -> Option<ColorRange> {
142    let x = &stream.extradata;
143    let full = match stream.codec_id {
144        CodecId::H264 => {
145            let annexb = rff_format::avc::parse_avcc(x).map(|c| c.headers_annexb);
146            let headers = annexb.as_deref().unwrap_or(x);
147            rff_format::avc::sps_full_range(rff_format::avc::find_sps_annexb(headers)?)?
148        }
149        _ => return None,
150    };
151    Some(if full {
152        ColorRange::Full
153    } else {
154        ColorRange::Limited
155    })
156}
157
158/// One input file for a job.
159#[derive(Debug, Clone)]
160pub struct InputSpec {
161    pub path: PathBuf,
162    /// Force a container format instead of guessing from the extension
163    /// (`ffmpeg -f <fmt> -i ...`).
164    pub format: Option<String>,
165}
166
167/// Per-stream codec selection for the output.
168#[derive(Debug, Clone)]
169pub struct StreamCodec {
170    pub codec: CodecId,
171    /// Codec options (`-b:v 2M`, `-crf 23`, ...).
172    pub options: Dictionary,
173    /// Output sample format pinned by the codec NAME (`-c:a pcm_s16le`) or by
174    /// `-sample_fmt`. `None` = take whatever the decoder emits. Without this,
175    /// raw-PCM output silently ignored the format half of its own codec name.
176    pub sample_format: Option<SampleFormat>,
177}
178
179/// Which input stream(s) a `-map` entry selects.
180#[derive(Debug, Clone)]
181pub enum MapSelector {
182    /// All streams of the input (`-map 0`).
183    All,
184    /// All streams of a media kind (`-map 0:v` / `0:a`).
185    Kind(MediaType),
186    /// One stream by index within the input (`-map 0:2`).
187    Index(usize),
188}
189
190/// One `-map` entry: pick stream(s) from input `input`.
191#[derive(Debug, Clone)]
192pub struct MapSpec {
193    pub input: usize,
194    pub selector: MapSelector,
195}
196
197/// The output file for a job.
198#[derive(Debug, Clone, Default)]
199pub struct OutputSpec {
200    pub path: PathBuf,
201    /// Force a container format instead of guessing from the extension
202    /// (`ffmpeg -f <fmt> ...`).
203    pub format: Option<String>,
204    /// Video codec for the output, if a video stream is produced.
205    pub video_codec: Option<StreamCodec>,
206    /// Audio codec for the output, if an audio stream is produced.
207    pub audio_codec: Option<StreamCodec>,
208    /// Subtitle codec (`-c:s subrip|webvtt`). Text-subtitle packets share one
209    /// contract (plain text + ms timing), so this relabels the stream for the
210    /// muxer rather than re-encoding anything.
211    pub subtitle_codec: Option<CodecId>,
212    /// Video filter graph (`-vf`), e.g. `scale=320:240,crop=...`. Applied to
213    /// decoded video frames before re-encoding (transcode streams only).
214    pub video_filters: Option<String>,
215    /// Multi-input filter graph (`-filter_complex`). Currently models `overlay`:
216    /// the last input is composited over input #0's video.
217    pub filter_complex: Option<String>,
218    /// Explicit stream selection (`-map`). Empty = default (all video + audio,
219    /// in input/stream order).
220    pub maps: Vec<MapSpec>,
221    /// Media kinds dropped from the output whatever selected them (`-vn`,
222    /// `-an`, `-sn`, `-dn`).
223    pub disabled: Vec<MediaType>,
224    /// Overwrite the output if it exists (`-y`); otherwise fail (`-n`).
225    pub overwrite: bool,
226    /// Stop after this many VIDEO frames (`-frames:v N`). `None` = whole input.
227    ///
228    /// This is a measurement-critical option: without it a harness that thinks
229    /// it is encoding a 50-frame prefix silently encodes the whole clip, and any
230    /// rate-vs-quality pairing computed against a prefix is then wrong.
231    pub max_video_frames: Option<u64>,
232    /// Output trim window start, in seconds (`-ss`). Decoded frames (or copied
233    /// packets) before this point are dropped; timestamps are shifted so the
234    /// output starts at zero.
235    pub trim_start: Option<f64>,
236    /// Output trim window end, in seconds (`-to`, or `-ss` + `-t`). Exclusive.
237    pub trim_end: Option<f64>,
238    /// Constant output frame rate (`-r`), as `(num, den)` — e.g. `(30000, 1001)`.
239    /// Frames are duplicated/dropped to hit it (FFmpeg's `fps` filter).
240    pub frame_rate: Option<(u32, u32)>,
241    /// Target audio sample rate (`-ar`). The encoder's accepted-rate list still
242    /// wins if it cannot take this exact rate (nearest accepted is used).
243    pub audio_rate: Option<u32>,
244    /// Target audio channel count (`-ac`): 1↔2 downmix/upmix.
245    pub audio_channels: Option<u16>,
246    /// Audio filter chain (`-af` / `-filter:a`), e.g. `volume=-6dB,atrim=...`.
247    pub audio_filters: Option<String>,
248    /// Output metadata (`-metadata title=...`), handed to muxers that carry it.
249    pub metadata: Dictionary,
250    /// Muxer options (`-hls_time 6` → `{"hls_time": "6"}`), for formats that
251    /// take them (HLS/DASH segmenting).
252    pub format_options: Dictionary,
253    /// Pixel format handed to the video encoder (`-pix_fmt`). `None` = the
254    /// encoder's best accepted format for the source (FFmpeg's automatic
255    /// format negotiation). A format the encoder does not accept falls back to
256    /// that automatic choice with a warning, as FFmpeg does.
257    pub pixel_format: Option<PixelFormat>,
258}
259
260/// A complete, declarative transcoding job.
261#[derive(Debug, Clone, Default)]
262pub struct TranscodeSpec {
263    pub inputs: Vec<InputSpec>,
264    pub outputs: Vec<OutputSpec>,
265}
266
267/// A successful run's summary (frames/packets moved, etc.). Fields will grow as
268/// the pipeline does.
269#[derive(Debug, Clone, Default)]
270pub struct TranscodeReport {
271    pub packets_written: u64,
272    pub frames_decoded: u64,
273    /// Non-fatal notices raised while encoding (an incompatible `-pix_fmt`
274    /// that was replaced, an alpha channel the encoder cannot carry, ...).
275    pub warnings: Vec<String>,
276}
277
278/// Output trim window (`-ss` / `-t` / `-to`), in seconds.
279#[derive(Clone, Copy)]
280struct Trim {
281    start: f64,
282    end: Option<f64>,
283}
284
285impl Trim {
286    fn from_spec(o: &OutputSpec) -> Option<Trim> {
287        if o.trim_start.is_none() && o.trim_end.is_none() {
288            return None;
289        }
290        Some(Trim {
291            start: o.trim_start.unwrap_or(0.0).max(0.0),
292            end: o.trim_end,
293        })
294    }
295
296    fn keeps(&self, t: f64) -> bool {
297        t >= self.start - 1e-9 && self.end.is_none_or(|e| t < e - 1e-9)
298    }
299}
300
301/// CFR conversion state (`-r`): input frames are snapped onto a fixed
302/// `num/den` fps grid, duplicating the previous frame across gaps and dropping
303/// frames that land on an already-filled slot. Emitted frames carry their slot
304/// index as pts (time base `den/num`).
305struct FpsConv {
306    num: u32,
307    den: u32,
308    next_slot: i64,
309    last: Option<VideoFrame>,
310}
311
312impl FpsConv {
313    fn new(num: u32, den: u32) -> FpsConv {
314        FpsConv {
315            num: num.max(1),
316            den: den.max(1),
317            next_slot: 0,
318            last: None,
319        }
320    }
321
322    fn slot_time(&self, slot: i64) -> f64 {
323        slot as f64 * self.den as f64 / self.num as f64
324    }
325
326    /// Feed one input frame at time `t` (seconds); returns the frames due
327    /// strictly before `t`, each stamped with its slot pts.
328    fn push(&mut self, frame: VideoFrame, t: f64) -> Vec<VideoFrame> {
329        let mut out = Vec::new();
330        while let Some(last) = &self.last {
331            if self.slot_time(self.next_slot) < t - 1e-9 {
332                let mut f = last.clone();
333                f.pts = Some(self.next_slot);
334                out.push(f);
335                self.next_slot += 1;
336            } else {
337                break;
338            }
339        }
340        self.last = Some(frame);
341        out
342    }
343
344    /// End of stream: emit the held frame in its slot.
345    fn finish(&mut self) -> Option<VideoFrame> {
346        self.last.take().map(|mut f| {
347            f.pts = Some(self.next_slot);
348            self.next_slot += 1;
349            f
350        })
351    }
352}
353
354/// What to do with one input stream on its way to the output.
355enum StreamOp {
356    /// Not selected (or a media type we can't route): drop its packets.
357    Skip,
358    /// Remux packets unchanged into the output.
359    Copy(CopyOp),
360    /// Decode, filter, re-encode.
361    Transcode(Box<TranscodeOp>),
362}
363
364/// Stream-copy: forward packets, applying the trim window at packet level.
365/// Video cuts on the first keyframe inside the window (a copy can't split a
366/// GOP); timestamps shift so the output starts at zero.
367struct CopyOp {
368    out_index: usize,
369    is_video: bool,
370    /// Trim window in stream ticks (`None` = no trimming).
371    start_ticks: i64,
372    end_ticks: Option<i64>,
373    trimming: bool,
374    /// Video: set once the first in-window keyframe has passed.
375    started: bool,
376}
377
378impl CopyOp {
379    /// Apply trim/shift; `None` = drop the packet.
380    fn process(&mut self, mut packet: Packet) -> Option<Packet> {
381        if self.trimming {
382            let ts = packet.pts.or(packet.dts).unwrap_or(0);
383            if ts < self.start_ticks {
384                return None;
385            }
386            if let Some(end) = self.end_ticks {
387                if ts >= end {
388                    return None;
389                }
390            }
391            if self.is_video && !self.started {
392                if !packet.flags.keyframe {
393                    return None; // wait for a clean random-access point
394                }
395                self.started = true;
396            }
397            packet.pts = packet.pts.map(|p| p - self.start_ticks);
398            packet.dts = packet.dts.map(|d| d - self.start_ticks);
399        }
400        packet.stream_index = self.out_index;
401        Some(packet)
402    }
403}
404
405/// Decode → trim → fps → filters/overlay → audio conform → encode → mux.
406struct TranscodeOp {
407    decoder: Box<dyn Decoder>,
408    encoder: Box<dyn Encoder>,
409    filters: FilterChain,
410    /// `-filter_complex` overlay: a pre-decoded frame composited onto each
411    /// of this stream's frames at `(x, y)` (after `filters`). Video only.
412    overlay: Option<(VideoFrame, u32, u32)>,
413    /// The input stream's time base (frame pts are in these ticks).
414    in_time_base: rff_core::Rational,
415    is_video: bool,
416    /// Output trim window; pts are shifted by `shift_ticks` after it.
417    trim: Option<Trim>,
418    shift_ticks: i64,
419    /// Fallback clock for trimming audio whose frames carry no pts.
420    audio_clock_samples: u64,
421    /// `-r`: CFR duplicate/drop stage.
422    fps: Option<FpsConv>,
423    /// `-af`: the audio filter chain (volume/atrim/...).
424    audio_chain: rff_filter::AudioFilterChain,
425    /// `-ac`: mix to this many channels before everything else (0 = keep).
426    target_channels: u16,
427    /// Sample rate the encoder needs (0 = no audio resampling required).
428    target_rate: u32,
429    /// Sample format the output pins (`-c:a pcm_s16le`), if any.
430    target_sample_format: Option<SampleFormat>,
431    /// Lazily built once the first audio frame reveals the input rate.
432    resampler: Option<Resampler>,
433    /// Pixel-format negotiation + conversion in front of the encoder.
434    pixels: PixelConform,
435    /// Full → limited conversion for an encoder that cannot signal full
436    /// range (applied after `pixels`).
437    range_fix: Option<FilterChain>,
438    /// Range of the frames reaching the encoder, for that conversion.
439    source_range: ColorRange,
440    /// Warnings raised mid-stream, handed to the report as they appear.
441    warnings: Vec<String>,
442    out_index: usize,
443    /// `-frames:v` limit for this output, and how many we have sent.
444    max_video_frames: Option<u64>,
445    video_frames_sent: u64,
446    /// pts of video frames handed to the encoder, FIFO. Video encoders that
447    /// don't timestamp their packets (VP9, H.264) get these stamped on in
448    /// [`TranscodeOp::drain`] — without it every Matroska block lands at t=0.
449    pending_pts: std::collections::VecDeque<Option<i64>>,
450}
451
452/// Composite the `-filter_complex` overlay onto a video frame, if one is set.
453/// Audio frames and the no-overlay case pass through untouched.
454fn apply_overlay(overlay: &Option<(VideoFrame, u32, u32)>, frame: Frame) -> Result<Frame> {
455    match (overlay, frame) {
456        (Some((over, x, y)), Frame::Video(v)) => {
457            Ok(Frame::Video(rff_filter::overlay(v, over, *x, *y)?))
458        }
459        (_, frame) => Ok(frame),
460    }
461}
462
463/// Apply a video filter chain to a frame. Filters are video-only; audio passes
464/// through untouched, and an empty chain is a no-op.
465fn apply_filters(filters: &mut FilterChain, frame: Frame) -> Result<Frame> {
466    if filters.is_empty() {
467        return Ok(frame);
468    }
469    match frame {
470        Frame::Video(v) => Ok(Frame::Video(filters.apply(v)?)),
471        other => Ok(other),
472    }
473}
474
475/// Pick the accepted rate closest to `target`.
476fn nearest_rate(rates: &[u32], target: u32) -> u32 {
477    rates
478        .iter()
479        .copied()
480        .min_by_key(|r| (*r as i64 - target as i64).abs())
481        .unwrap_or(target)
482}
483
484/// Read interleaved `s16`/`f32` plane 0 of an audio frame into `f32` samples.
485fn audio_to_f32(af: &AudioFrame) -> Result<Vec<f32>> {
486    match af.format {
487        SampleFormat::F32 => Ok(af.planes[0]
488            .chunks_exact(4)
489            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
490            .collect()),
491        SampleFormat::S16 => Ok(af.planes[0]
492            .chunks_exact(2)
493            .map(|b| i16::from_le_bytes([b[0], b[1]]) as f32 / 32768.0)
494            .collect()),
495        other => Err(Error::unsupported(format!(
496            "resample: sample format `{}` (need interleaved s16/f32)",
497            other.name()
498        ))),
499    }
500}
501
502/// `f32` samples as little-endian bytes, in one sized pass. The
503/// `iter().flat_map(to_le_bytes).collect()` this replaces is the pattern LLVM
504/// handles worst -- an iterator of tiny arrays flattened into a growing `Vec`.
505fn f32_le_bytes(samples: &[f32]) -> Vec<u8> {
506    let mut bytes = vec![0u8; samples.len() * 4];
507    for (d, s) in bytes.chunks_exact_mut(4).zip(samples) {
508        d.copy_from_slice(&s.to_le_bytes());
509    }
510    bytes
511}
512
513/// The usual f32 -> s16 rule: round to nearest, then clamp. Truncation would
514/// bias every sample toward zero.
515fn f32_to_s16(s: f32) -> i16 {
516    (s * 32768.0).round().clamp(-32768.0, 32767.0) as i16
517}
518
519/// Wrap interleaved `f32` samples as an `f32` [`AudioFrame`].
520fn f32_frame(samples: Vec<f32>, rate: u32, channels: u16, pts: Option<i64>) -> Frame {
521    let bytes = f32_le_bytes(&samples);
522    Frame::Audio(AudioFrame {
523        sample_rate: rate,
524        channels,
525        format: SampleFormat::F32,
526        samples: samples.len() / channels.max(1) as usize,
527        planes: vec![bytes],
528        pts,
529    })
530}
531
532/// Convert an audio frame to `target` sample format, if one is pinned and the
533/// frame is not already in it. The audio analogue of `conform_video`: raw PCM
534/// output declares its format in the container header, so the frames handed to
535/// the muxer must actually BE that format, not merely be labelled it.
536fn conform_sample_format(target: Option<SampleFormat>, frame: Frame) -> Result<Frame> {
537    let Some(target) = target else {
538        return Ok(frame);
539    };
540    let Frame::Audio(af) = frame else {
541        return Ok(frame);
542    };
543    if af.format == target {
544        return Ok(Frame::Audio(af));
545    }
546    // Bytes to bytes in ONE pass. This used to decode the whole plane into a
547    // `Vec<f32>` and then re-encode it through `flat_map(..).collect()` -- an
548    // extra full-frame copy (a WAV's worth, when the frame is a whole file) and
549    // the iterator shape LLVM vectorises worst. The arithmetic per sample is
550    // the same expression, so the output is byte-identical.
551    let src = &af.planes[0];
552    let plane = match (af.format, target) {
553        (SampleFormat::F32, SampleFormat::S16) => {
554            let mut out = vec![0u8; src.len() / 4 * 2];
555            for (d, b) in out.chunks_exact_mut(2).zip(src.chunks_exact(4)) {
556                let s = f32::from_le_bytes([b[0], b[1], b[2], b[3]]);
557                d.copy_from_slice(&f32_to_s16(s).to_le_bytes());
558            }
559            out
560        }
561        (SampleFormat::S16, SampleFormat::F32) => {
562            let mut out = vec![0u8; src.len() / 2 * 4];
563            for (d, b) in out.chunks_exact_mut(4).zip(src.chunks_exact(2)) {
564                let s = i16::from_le_bytes([b[0], b[1]]) as f32 / 32768.0;
565                d.copy_from_slice(&s.to_le_bytes());
566            }
567            out
568        }
569        _ => {
570            // Not a supported pair: report the source format first, as before.
571            audio_to_f32(&af)?;
572            return Err(Error::unsupported(format!(
573                "sample format conversion to `{}` (only interleaved s16/f32)",
574                target.name()
575            )));
576        }
577    };
578    let planes = vec![plane];
579    Ok(Frame::Audio(AudioFrame {
580        sample_rate: af.sample_rate,
581        channels: af.channels,
582        format: target,
583        samples: af.samples,
584        planes,
585        pts: af.pts,
586    }))
587}
588
589/// Resample an audio frame to `target_rate` if needed (the resampler is built
590/// lazily from the first frame's rate/channels). `target_rate == 0` is a no-op.
591fn conform_audio(
592    resampler: &mut Option<Resampler>,
593    target_rate: u32,
594    frame: Frame,
595) -> Result<Frame> {
596    if target_rate == 0 {
597        return Ok(frame);
598    }
599    let Frame::Audio(af) = frame else {
600        return Ok(frame);
601    };
602    if af.sample_rate == target_rate {
603        return Ok(Frame::Audio(af));
604    }
605    let rs =
606        resampler.get_or_insert_with(|| Resampler::new(af.sample_rate, target_rate, af.channels));
607    let out = rs.process(&audio_to_f32(&af)?);
608    let pts = af
609        .pts
610        .map(|p| p * target_rate as i64 / af.sample_rate.max(1) as i64);
611    Ok(f32_frame(out, target_rate, af.channels, pts))
612}
613
614/// Pick the pixel format to hand an encoder for a `src` frame — FFmpeg's
615/// automatic format negotiation (`avcodec_find_best_pix_fmt_of_list` plus the
616/// `-pix_fmt` override).
617///
618/// * `requested` (`-pix_fmt`) wins when the encoder accepts it. When it does
619///   not, the automatic choice is used instead and a warning says so, worded
620///   as FFmpeg words it ("Incompatible pixel format ...").
621/// * A source the encoder already accepts passes through untouched.
622/// * Otherwise: the encoder's most-preferred accepted format that the
623///   pipeline can convert `src` into, keeping high bit depth when the
624///   reference (the request, else the source) has it and the encoder takes it,
625///   and staying at 8 bits otherwise.
626///
627/// Returns the chosen format plus any warnings. `accepted == None` means the
628/// encoder takes anything.
629fn negotiate_pixel_format(
630    src: PixelFormat,
631    accepted: Option<&[PixelFormat]>,
632    requested: Option<PixelFormat>,
633    codec: CodecId,
634) -> Result<(PixelFormat, Vec<String>)> {
635    let accepted = accepted.filter(|a| !a.is_empty());
636    let accepts = |f: PixelFormat| accepted.is_none_or(|a| a.contains(&f));
637    let mut warnings = Vec::new();
638    let chosen = match requested {
639        Some(req) if accepts(req) => req,
640        Some(req) => {
641            let best = best_pixel_format(src, req, accepted.unwrap_or_default())?;
642            warnings.push(format!(
643                "Incompatible pixel format '{}' for codec '{}', auto-selecting format '{}'",
644                req.name(),
645                codec.name(),
646                best.name()
647            ));
648            best
649        }
650        None if accepts(src) => src,
651        None => best_pixel_format(src, src, accepted.unwrap_or_default())?,
652    };
653    if chosen != src && !rff_filter::can_convert(src, chosen) {
654        return Err(Error::unsupported(format!(
655            "no conversion from `{}` to `{}`",
656            src.name(),
657            chosen.name()
658        )));
659    }
660    if src.has_alpha() && !chosen.has_alpha() {
661        warnings.push(format!(
662            "codec '{}' has no alpha channel in `{}`: the alpha of the `{}` input is dropped",
663            codec.name(),
664            chosen.name(),
665            src.name()
666        ));
667    }
668    Ok((chosen, warnings))
669}
670
671/// The encoder's best accepted format for a `src` frame: candidates are the
672/// accepted formats `src` converts into, in the encoder's preference order;
673/// a high-bit-depth `reference` takes the first deep candidate, an 8-bit one
674/// the first 8-bit candidate, and failing that the first candidate of any
675/// depth.
676fn best_pixel_format(
677    src: PixelFormat,
678    reference: PixelFormat,
679    accepted: &[PixelFormat],
680) -> Result<PixelFormat> {
681    let candidates: Vec<PixelFormat> = accepted
682        .iter()
683        .copied()
684        .filter(|&f| rff_filter::can_convert(src, f))
685        .collect();
686    let deep = reference.bit_depth() > 8;
687    candidates
688        .iter()
689        .copied()
690        .find(|f| (f.bit_depth() > 8) == deep)
691        .or(candidates.first().copied())
692        .ok_or_else(|| {
693            let names: Vec<&str> = accepted.iter().map(|f| f.name()).collect();
694            Error::unsupported(format!(
695                "no conversion from `{}` to any format this encoder accepts ({})",
696                src.name(),
697                names.join(", ")
698            ))
699        })
700}
701
702/// Converts video frames into the pixel format negotiated with the encoder,
703/// if they aren't already in it. The converting chain is built lazily from
704/// the first frame that needs it, mirroring the audio resampler above.
705///
706/// This is what lets a decoder emit its cheapest native layout: the JPEG decoder
707/// hands out planar Y'CbCr, and a PNG encoder downstream still gets the RGB it
708/// requires because this inserts the conversion. Equally, a PNG's RGB reaches
709/// an AVIF / H.264 / VP9 encoder as the planar Y'CbCr it needs.
710struct PixelConform {
711    /// Pixel formats the encoder accepts (`None` = anything).
712    accepted: Option<Vec<PixelFormat>>,
713    /// `-pix_fmt`, if given.
714    requested: Option<PixelFormat>,
715    /// The output codec, for messages.
716    codec: CodecId,
717    /// An RGB → Y'CbCr conversion produces limited range (FFmpeg's default,
718    /// and what a video bitstream that carries no range flag is read as),
719    /// rather than following the source's full range. True for the
720    /// compressed video codecs; the full-range image codecs and raw video
721    /// keep the source range.
722    rgb_to_limited: bool,
723    /// The range committed for the output stream (what the muxer labels and
724    /// the encoder signals). An RGB → Y'CbCr conversion produces it, so a
725    /// source only discovered to be RGB at the first frame (a progressive
726    /// JPEG) still matches the label. `None`: decide by `rgb_to_limited`.
727    out_range: Option<ColorRange>,
728    /// Source format the converter below was built for, the target it
729    /// converts to, and the converter (`None` when they are equal).
730    state: Option<(PixelFormat, PixelFormat, Option<FilterChain>)>,
731}
732
733impl PixelConform {
734    fn new(
735        accepted: Option<Vec<PixelFormat>>,
736        requested: Option<PixelFormat>,
737        codec: CodecId,
738    ) -> PixelConform {
739        PixelConform {
740            accepted,
741            requested,
742            codec,
743            rgb_to_limited: !is_full_range_codec(codec) && codec != CodecId::RawVideo,
744            out_range: None,
745            state: None,
746        }
747    }
748
749    fn negotiate(&self, src: PixelFormat) -> Result<(PixelFormat, Vec<String>)> {
750        negotiate_pixel_format(src, self.accepted.as_deref(), self.requested, self.codec)
751    }
752
753    fn conform(
754        &mut self,
755        source_range: ColorRange,
756        frame: Frame,
757        warnings: &mut Vec<String>,
758    ) -> Result<Frame> {
759        if self.accepted.is_none() && self.requested.is_none() {
760            return Ok(frame);
761        }
762        let Frame::Video(vf) = frame else {
763            return Ok(frame);
764        };
765        let fresh = !matches!(&self.state, Some((src, _, _)) if *src == vf.format);
766        if fresh {
767            let (target, mut notes) = self.negotiate(vf.format)?;
768            warnings.append(&mut notes);
769            let converter = if target == vf.format {
770                None
771            } else {
772                // Pin the range: `spec.limited` describes the Y'CbCr side
773                // either way, and guessing it wrong is a silent several-dB
774                // error.
775                let limited = if vf.format.is_rgb() && !target.is_rgb() {
776                    match self.out_range {
777                        Some(range) => range != ColorRange::Full,
778                        None => self.rgb_to_limited || source_range == ColorRange::Limited,
779                    }
780                } else {
781                    source_range == ColorRange::Limited
782                };
783                Some(FilterChain::parse(&format!(
784                    "format={}:bt601:{}",
785                    target.name(),
786                    if limited { "limited" } else { "full" }
787                ))?)
788            };
789            self.state = Some((vf.format, target, converter));
790        }
791        match &mut self.state {
792            Some((_, _, Some(chain))) => Ok(Frame::Video(chain.apply(vf)?)),
793            _ => Ok(Frame::Video(vf)),
794        }
795    }
796}
797
798/// Mix an audio frame to `target` channels (0 = keep). Stereo↔mono only: a
799/// downmix averages pairs, an upmix duplicates the channel.
800fn conform_channels(target: u16, frame: Frame) -> Result<Frame> {
801    if target == 0 {
802        return Ok(frame);
803    }
804    let Frame::Audio(af) = frame else {
805        return Ok(frame);
806    };
807    if af.channels == target {
808        return Ok(Frame::Audio(af));
809    }
810    let samples = audio_to_f32(&af)?;
811    let mixed: Vec<f32> = match (af.channels, target) {
812        (2, 1) => samples
813            .chunks_exact(2)
814            .map(|p| 0.5 * (p[0] + p[1]))
815            .collect(),
816        (1, 2) => samples.iter().flat_map(|s| [*s, *s]).collect(),
817        (from, to) => {
818            return Err(Error::unsupported(format!(
819                "-ac: only 1<->2 channel mixing supported (input {from} ch, requested {to})"
820            )))
821        }
822    };
823    Ok(f32_frame(mixed, af.sample_rate, target, af.pts))
824}
825
826impl TranscodeOp {
827    /// A frame's start time in seconds (input timeline). Audio without pts
828    /// falls back to a running sample clock; video without pts cannot be
829    /// placed and errors — only called when trim/fps actually need the time.
830    fn frame_time(&self, frame: &Frame) -> Result<f64> {
831        let tb = self.in_time_base;
832        let tick = if tb.num > 0 && tb.den > 0 {
833            tb.num as f64 / tb.den as f64
834        } else {
835            0.001
836        };
837        match frame.pts() {
838            Some(p) => Ok(p as f64 * tick),
839            None => match frame {
840                Frame::Audio(af) => {
841                    Ok(self.audio_clock_samples as f64 / af.sample_rate.max(1) as f64)
842                }
843                Frame::Video(_) => Err(Error::unsupported(
844                    "-ss/-t/-to/-r need timestamps and this video stream has none",
845                )),
846            },
847        }
848    }
849
850    /// Decoded-frame entry point: trim window, timestamp shift, CFR stage,
851    /// then the per-frame pipeline in [`TranscodeOp::emit`].
852    fn handle_frame(
853        &mut self,
854        frame: Frame,
855        muxer: &mut dyn Muxer,
856        report: &mut TranscodeReport,
857    ) -> Result<()> {
858        report.frames_decoded += 1;
859        let needs_time = self.trim.is_some() || (self.is_video && self.fps.is_some());
860        let t = if needs_time {
861            Some(self.frame_time(&frame)?)
862        } else {
863            None
864        };
865        // The sample clock tracks ALL input audio, kept or dropped.
866        if let Frame::Audio(af) = &frame {
867            self.audio_clock_samples += af.samples as u64;
868        }
869        let mut frame = frame;
870        if let (Some(trim), Some(t)) = (self.trim, t) {
871            match frame {
872                // Audio frames can be arbitrarily long (a WAV decodes as one
873                // frame), so the window slices samples instead of keep/drop.
874                Frame::Audio(af) => {
875                    match rff_filter::trim_audio_frame(af, Some(t), Some(trim.start), trim.end)? {
876                        Some(af) => frame = Frame::Audio(af),
877                        None => return Ok(()),
878                    }
879                }
880                Frame::Video(_) => {
881                    if !trim.keeps(t) {
882                        return Ok(());
883                    }
884                }
885            }
886        }
887        // Shift timestamps so the output timeline starts at zero.
888        if self.shift_ticks != 0 {
889            match &mut frame {
890                Frame::Video(v) => v.pts = v.pts.map(|p| p - self.shift_ticks),
891                Frame::Audio(a) => a.pts = a.pts.map(|p| p - self.shift_ticks),
892            }
893        }
894        match frame {
895            Frame::Video(v) if self.fps.is_some() => {
896                let t_out = t.expect("fps requires time") - self.trim.map_or(0.0, |w| w.start);
897                let mut fps = self.fps.take().expect("checked");
898                let due = fps.push(v, t_out);
899                self.fps = Some(fps);
900                for f in due {
901                    self.emit(Frame::Video(f), muxer, report)?;
902                }
903                Ok(())
904            }
905            other => self.emit(other, muxer, report),
906        }
907    }
908
909    /// Post-fps pipeline: `-frames:v` gate, filters, overlay, audio conforms,
910    /// encode, drain.
911    fn emit(
912        &mut self,
913        frame: Frame,
914        muxer: &mut dyn Muxer,
915        report: &mut TranscodeReport,
916    ) -> Result<()> {
917        if let Some(limit) = self.max_video_frames {
918            if matches!(frame, Frame::Video(_)) {
919                if self.video_frames_sent >= limit {
920                    return Ok(());
921                }
922                self.video_frames_sent += 1;
923            }
924        }
925        let conformed = phases::time(&phases::CONFORM, || self.conform(frame));
926        report.warnings.append(&mut self.warnings);
927        let Some(frame) = conformed? else {
928            return Ok(()); // atrim consumed the whole frame
929        };
930        if self.is_video {
931            self.pending_pts.push_back(frame.pts());
932        }
933        phases::time(&phases::ENCODE, || self.encoder.send_frame(&frame))?;
934        self.drain(muxer, report)
935    }
936
937    /// The per-frame conform chain between decode and encode: filters, overlay,
938    /// channel/rate/sample-format/pixel conforms. `None` = atrim dropped it.
939    fn conform(&mut self, frame: Frame) -> Result<Option<Frame>> {
940        let frame = apply_filters(&mut self.filters, frame)?;
941        let frame = apply_overlay(&self.overlay, frame)?;
942        let frame = conform_channels(self.target_channels, frame)?;
943        let frame = match frame {
944            Frame::Audio(af) if !self.audio_chain.is_empty() => {
945                let tb = self.in_time_base;
946                let t = af
947                    .pts
948                    .map(|p| p as f64 * tb.num as f64 / tb.den.max(1) as f64);
949                match self.audio_chain.apply(af, t)? {
950                    Some(af) => Frame::Audio(af),
951                    None => return Ok(None),
952                }
953            }
954            other => other,
955        };
956        let frame = conform_audio(&mut self.resampler, self.target_rate, frame)?;
957        let frame = conform_sample_format(self.target_sample_format, frame)?;
958        let frame = self
959            .pixels
960            .conform(self.source_range, frame, &mut self.warnings)?;
961        let frame = match (&mut self.range_fix, frame) {
962            (Some(chain), Frame::Video(vf)) => Frame::Video(chain.apply(vf)?),
963            (_, frame) => frame,
964        };
965        Ok(Some(frame))
966    }
967
968    /// Pull every ready packet out of the encoder and mux it. Video encoders
969    /// that don't timestamp their packets (VP9, H.264 emit `pts: None`) get the
970    /// corresponding source frame's pts stamped on, FIFO — without this every
971    /// Matroska block would land at t=0.
972    fn drain(&mut self, muxer: &mut dyn Muxer, report: &mut TranscodeReport) -> Result<()> {
973        loop {
974            match phases::time(&phases::ENCODE, || self.encoder.receive_packet()) {
975                Ok(mut packet) => {
976                    if self.is_video {
977                        let queued = self.pending_pts.pop_front().flatten();
978                        if packet.pts.is_none() {
979                            packet.pts = queued;
980                        }
981                    }
982                    packet.stream_index = self.out_index;
983                    phases::time(&phases::MUX, || muxer.write_packet(&packet))?;
984                    report.packets_written += 1;
985                }
986                Err(Error::Again) | Err(Error::Eof) => break,
987                Err(e) => return Err(e),
988            }
989        }
990        Ok(())
991    }
992
993    /// End of input: flush the decoder, the CFR stage's held frame, the
994    /// resampler's FIR tail, then the encoder.
995    fn finish(&mut self, muxer: &mut dyn Muxer, report: &mut TranscodeReport) -> Result<()> {
996        self.decoder.flush();
997        loop {
998            match phases::time(&phases::DECODE, || self.decoder.receive_frame()) {
999                Ok(frame) => self.handle_frame(frame, muxer, report)?,
1000                Err(Error::Again) | Err(Error::Eof) => break,
1001                Err(e) => return Err(e),
1002            }
1003        }
1004        if let Some(mut fps) = self.fps.take() {
1005            let held = fps.finish();
1006            self.fps = Some(fps);
1007            if let Some(f) = held {
1008                self.emit(Frame::Video(f), muxer, report)?;
1009            }
1010        }
1011        if let Some(rs) = &mut self.resampler {
1012            let tail = rs.finish();
1013            if !tail.is_empty() {
1014                let frame = f32_frame(tail, rs.out_rate(), rs.channels(), None);
1015                let frame = conform_sample_format(self.target_sample_format, frame)?;
1016                self.encoder.send_frame(&frame)?;
1017                self.drain(muxer, report)?;
1018            }
1019        }
1020        phases::time(&phases::ENCODE, || self.encoder.flush());
1021        self.drain(muxer, report)
1022    }
1023}
1024
1025/// Resolve and run a transcode job against `engine`.
1026///
1027/// Resolution (formats, decoders, encoders) happens up front so failures are
1028/// reported before any output file is touched; then the demux→decode→encode→mux
1029/// loop runs to completion.
1030pub fn run(engine: &Engine, spec: &TranscodeSpec) -> Result<TranscodeReport> {
1031    if spec.inputs.is_empty() {
1032        return Err(Error::Option("no input files specified".into()));
1033    }
1034    if spec.outputs.is_empty() {
1035        return Err(Error::Option("no output file specified".into()));
1036    }
1037    if spec.outputs.len() > 1 {
1038        return Err(Error::unsupported("multiple outputs are not supported yet"));
1039    }
1040    let output = &spec.outputs[0];
1041
1042    // -filter_complex overlay: the last input is composited over input #0's
1043    // video. Resolve it up front so stream selection can exclude that input.
1044    let overlay_xy = output
1045        .filter_complex
1046        .as_deref()
1047        .map(FilterComplex::parse)
1048        .transpose()?
1049        .and_then(|fc| fc.overlay);
1050    let overlay_input = match overlay_xy {
1051        Some(_) if spec.inputs.len() >= 2 => Some(spec.inputs.len() - 1),
1052        Some(_) => {
1053            return Err(Error::Option(
1054                "filter_complex overlay needs a second input (the overlay image/video)".into(),
1055            ))
1056        }
1057        None => None,
1058    };
1059
1060    // --- open every input demuxer and read its streams ---
1061    // (`open` is a phase of its own: demuxers read only their headers here and
1062    // stream packets after; MP4 from a pipe, which must buffer to reach a
1063    // trailing `moov`, is the one that still does all of its I/O at open.)
1064    let t_start = phases::on().then(std::time::Instant::now);
1065    // Timecode tracks are streams only when data streams are asked for by
1066    // kind (`-map 0:d`): otherwise stream numbers, and what `-map 0` selects,
1067    // stay as they are and the timecode travels as `Stream::timecode`.
1068    let timecode_streams = output
1069        .maps
1070        .iter()
1071        .any(|m| matches!(m.selector, MapSelector::Kind(MediaType::Data)));
1072    let mut demuxers: Vec<Box<dyn rff_format::Demuxer>> = Vec::new();
1073    let mut input_streams: Vec<Vec<Stream>> = Vec::new();
1074    for input in &spec.inputs {
1075        let (demuxer, streams) = phases::time(&phases::OPEN, || -> Result<_> {
1076            let (in_format, source) = open_input(engine, input)?;
1077            let mut demuxer = source.open_demuxer(engine, &in_format)?;
1078            if timecode_streams {
1079                demuxer.set_timecode_streams(true);
1080            }
1081            let streams = demuxer.read_header()?;
1082            Ok((demuxer, streams))
1083        })?;
1084        input_streams.push(streams);
1085        demuxers.push(demuxer);
1086    }
1087
1088    // --- select which (input, stream) pairs go to the output, in order ---
1089    let mut selection = select_streams(&input_streams, output)?;
1090    // An MP4 chapter track is a data stream no muxer takes; its chapters are
1091    // carried as chapters, so `-map 0` and `-map 0:d` pass over it.
1092    selection.retain(|&(inp, i)| {
1093        input_streams[inp][i].media_type != MediaType::Data
1094            || !is_chapter_track(&*demuxers[inp], input_streams[inp].len(), i)
1095            || output
1096                .maps
1097                .iter()
1098                .any(|m| m.input == inp && matches!(m.selector, MapSelector::Index(n) if n == i))
1099    });
1100    // The overlay input is consumed by the filter, not muxed as its own stream.
1101    if let Some(oin) = overlay_input {
1102        selection.retain(|(inp, _)| *inp != oin);
1103    }
1104    if selection.is_empty() {
1105        return Err(Error::unsupported("no streams selected for the output"));
1106    }
1107    // A still-image output holds one picture. Without `-map`, keep one video
1108    // stream — the first one marked default (a JPEG MPF file's primary image,
1109    // not its gain map or thumbnails), else the first — as FFmpeg picks a
1110    // single best video stream. `-map 0:N` picks any other.
1111    if output.maps.is_empty() {
1112        let still = resolve_output_format(engine, output)
1113            .ok()
1114            .and_then(|name| engine.formats.by_name(&name))
1115            .is_some_and(|f| f.mux_caps.still_image);
1116        if still {
1117            let is_video =
1118                |&(inp, i): &(usize, usize)| input_streams[inp][i].media_type == MediaType::Video;
1119            let keep = selection
1120                .iter()
1121                .copied()
1122                .filter(is_video)
1123                .find(|&(inp, i)| input_streams[inp][i].disposition.default == Some(true))
1124                .or_else(|| selection.iter().copied().find(is_video));
1125            if let Some(keep) = keep {
1126                selection.retain(|s| !is_video(s) || *s == keep);
1127            }
1128        }
1129    }
1130
1131    // Single-codec containers can't stream-copy a foreign codec, so an unset
1132    // `-c:v` must mean TRANSCODE to the container's one codec, not copy (which
1133    // the muxer would reject). y4m additionally can't carry anything compressed.
1134    // Mirrors ffmpeg picking the muxer's default codec (`out.webp` → webp).
1135    // When the source already IS that codec, `None` stays: stream-copy wins.
1136    let mut output_owned;
1137    let output = if output.video_codec.is_none() {
1138        let format_name = resolve_output_format(engine, output).ok();
1139        // y4m keeps its unconditional default: it can't carry anything
1140        // compressed, so even rawvideo input goes through the decode path.
1141        let required = match format_name.as_deref() {
1142            Some("yuv4mpegpipe") => Some((CodecId::RawVideo, true)),
1143            Some("webp") => Some((CodecId::Webp, false)),
1144            Some("png") => Some((CodecId::Png, false)),
1145            Some("jpeg") | Some("jpeg_mpf") => Some((CodecId::Jpeg, false)),
1146            Some("gif") => Some((CodecId::Gif, false)),
1147            Some("avif") => Some((CodecId::Avif, false)),
1148            Some("jpegxl") => Some((CodecId::Jxl, false)),
1149            Some("exr_pipe") => Some((CodecId::Exr, false)),
1150            _ => None,
1151        };
1152        let apply = match required {
1153            Some((_, true)) => true,
1154            // Image containers: only when the source codec differs — a matching
1155            // source keeps `None` and takes the stream-copy fast path.
1156            Some((codec, false)) => !selection.iter().any(|&(inp, local)| {
1157                let s = &input_streams[inp][local];
1158                s.media_type == MediaType::Video && s.codec_id == codec
1159            }),
1160            None => false,
1161        };
1162        if apply {
1163            output_owned = output.clone();
1164            output_owned.video_codec = Some(StreamCodec {
1165                codec: required.expect("apply implies required").0,
1166                options: Dictionary::default(),
1167                sample_format: None, // video: no audio sample format to pin
1168            });
1169            &output_owned
1170        } else {
1171            output
1172        }
1173    } else {
1174        output
1175    };
1176
1177    // Per-input op tables (Skip for unselected streams) + ordered output streams.
1178    let mut per_input_ops: Vec<Vec<StreamOp>> = input_streams
1179        .iter()
1180        .map(|s| (0..s.len()).map(|_| StreamOp::Skip).collect())
1181        .collect();
1182    let mut out_streams: Vec<Stream> = Vec::new();
1183    for (out_index, &(inp, local)) in selection.iter().enumerate() {
1184        let (op, os) = build_op(engine, &input_streams[inp][local], output, out_index)?;
1185        per_input_ops[inp][local] = op;
1186        out_streams.push(os);
1187    }
1188
1189    // --- filter_complex overlay: pre-decode the overlay frame and hand it to
1190    // input #0's video transcode op (which composites it onto every frame) ---
1191    if let (Some((x, y)), Some(oin)) = (overlay_xy, overlay_input) {
1192        let over = decode_overlay_frame(engine, &mut *demuxers[oin], &input_streams[oin])?;
1193        let vidx = input_streams[0]
1194            .iter()
1195            .position(|s| s.media_type == MediaType::Video)
1196            .ok_or_else(|| Error::Option("filter_complex overlay: input #0 has no video".into()))?;
1197        match &mut per_input_ops[0][vidx] {
1198            StreamOp::Transcode(op) => op.overlay = Some((over, x, y)),
1199            _ => {
1200                return Err(Error::unsupported(
1201                    "filter_complex overlay needs input #0's video re-encoded — pass -c:v",
1202                ))
1203            }
1204        }
1205    }
1206
1207    // --- pick the muxer from the registry. Path-based formats (HLS/DASH: a
1208    // playlist plus many segment files) are built with the output path; every
1209    // other format writes one byte sink through rff-io (file, pipe, udp).
1210    let out_format = resolve_output_format(engine, output)?;
1211    let muxer_path_factory = engine
1212        .formats
1213        .by_name(&out_format)
1214        .filter(|fmt| fmt.can_mux())
1215        .ok_or_else(|| Error::MuxerNotFound(out_format.clone()))?
1216        .muxer_path;
1217
1218    // --- refuse to clobber an existing file unless -y was given (pipes and
1219    // sockets have nothing to clobber) ---
1220    let out_path_str = output.path.to_str().unwrap_or_default();
1221    let is_sink_stream = rff_io::is_pipe(out_path_str)
1222        || rff_io::is_udp(out_path_str)
1223        || rff_io::is_rtmp(out_path_str);
1224    if !is_sink_stream && !output.overwrite && output.path.exists() {
1225        return Err(Error::Option(format!(
1226            "{} already exists (pass -y to overwrite)",
1227            output.path.display()
1228        )));
1229    }
1230    let mut muxer: Box<dyn Muxer> = match muxer_path_factory {
1231        Some(factory) => factory(&output.path, &output.format_options)?,
1232        // A local file is seekable: muxers that can stream and patch their
1233        // header afterwards take that path (#28); pipes and network sinks
1234        // keep the plain one.
1235        None => match rff_io::create_seekable(out_path_str)? {
1236            Some(file) => engine
1237                .formats
1238                .open_muxer_seekable(&out_format, Box::new(file))?,
1239            None => engine
1240                .formats
1241                .open_muxer(&out_format, rff_io::create(out_path_str)?)?,
1242        },
1243    };
1244    if !output.metadata.is_empty() {
1245        muxer.set_metadata(&output.metadata);
1246    }
1247    // Format options (`-movflags +faststart`) reach byte-sink muxers too; a
1248    // path muxer already took them in its factory.
1249    if muxer_path_factory.is_none() {
1250        for (key, value) in output.format_options.iter() {
1251            muxer.set_option(key, value);
1252        }
1253    }
1254    // Per-stream metadata rides along from the input stream (FFmpeg's default
1255    // `-map_metadata`): a JPEG MPF remux keeps each image's MP Type.
1256    for (out_index, &(inp, local)) in selection.iter().enumerate() {
1257        if let Some(md) = demuxers[inp].stream_metadata(local) {
1258            muxer.set_stream_metadata(out_index, md);
1259        }
1260    }
1261    // What a stream refers to (its timecode track) follows it, as far as the
1262    // targets are in the output too.
1263    for (out_index, &(inp, local)) in selection.iter().enumerate() {
1264        let refs: Vec<TrackReference> = demuxers[inp]
1265            .track_references(local)
1266            .iter()
1267            .filter_map(|r| {
1268                let to: Vec<usize> = r
1269                    .streams
1270                    .iter()
1271                    .filter_map(|&t| selection.iter().position(|&s| s == (inp, t)))
1272                    .collect();
1273                (!to.is_empty()).then(|| TrackReference::new(r.kind, to))
1274            })
1275            .collect();
1276        if !refs.is_empty() {
1277            muxer.set_track_references(out_index, &refs);
1278        }
1279    }
1280    let chapters = output_chapters(&demuxers, output)?;
1281    if !chapters.is_empty() {
1282        muxer.set_chapters(&chapters);
1283    }
1284    muxer.write_header(&out_streams)?;
1285
1286    let mut report = TranscodeReport::default();
1287
1288    // Streams every op skips (unmapped, -vn/-an, the overlay input once its
1289    // frame is decoded) are never needed: let each demuxer drop them at the
1290    // source instead of reading and converting packets only to discard them.
1291    for (demuxer, ops) in demuxers.iter_mut().zip(&per_input_ops) {
1292        let discard: Vec<bool> = ops.iter().map(|op| matches!(op, StreamOp::Skip)).collect();
1293        if discard.contains(&true) {
1294            demuxer.set_discard(&discard);
1295        }
1296    }
1297
1298    // --- drive each input through its plan into the shared muxer ---
1299    for (demuxer, ops) in demuxers.iter_mut().zip(per_input_ops.iter_mut()) {
1300        loop {
1301            match phases::time(&phases::DEMUX, || demuxer.read_packet()) {
1302                Ok(packet) => process_packet(packet, ops, &mut *muxer, &mut report)?,
1303                Err(Error::Eof) => break,
1304                Err(e) => return Err(e),
1305            }
1306        }
1307        flush_streams(ops, &mut *muxer, &mut report)?;
1308    }
1309    phases::time(&phases::MUX, || muxer.write_trailer())?;
1310    if let Some(t) = t_start {
1311        phases::report(t.elapsed());
1312    }
1313
1314    Ok(report)
1315}
1316
1317/// The chapters of the output: those of the first input that has any, as
1318/// FFmpeg takes them by default, or of the input `map_chapters` names in the
1319/// format options (`-map_chapters N`; a negative number takes none), cut to
1320/// the trim window.
1321fn output_chapters(
1322    demuxers: &[Box<dyn rff_format::Demuxer>],
1323    output: &OutputSpec,
1324) -> Result<Vec<Chapter>> {
1325    let chapters = match output.format_options.get("map_chapters") {
1326        Some(v) => {
1327            let n: i64 = v
1328                .trim()
1329                .parse()
1330                .map_err(|_| Error::Option(format!("-map_chapters: not an input number: {v}")))?;
1331            match usize::try_from(n) {
1332                Ok(n) => demuxers
1333                    .get(n)
1334                    .ok_or_else(|| Error::Option(format!("-map_chapters: no input #{n}")))?
1335                    .chapters(),
1336                Err(_) => &[],
1337            }
1338        }
1339        None => demuxers
1340            .iter()
1341            .map(|d| d.chapters())
1342            .find(|c| !c.is_empty())
1343            .unwrap_or(&[]),
1344    };
1345    Ok(match Trim::from_spec(output) {
1346        Some(t) => rff_format::chapter::trim(chapters, t.start, t.end),
1347        None => chapters.to_vec(),
1348    })
1349}
1350
1351/// Whether another of the `n` streams refers to `stream` as its chapters.
1352fn is_chapter_track(demuxer: &dyn rff_format::Demuxer, n: usize, stream: usize) -> bool {
1353    (0..n).any(|i| {
1354        demuxer
1355            .track_references(i)
1356            .iter()
1357            .any(|r| &r.kind == b"chap" && r.streams.contains(&stream))
1358    })
1359}
1360
1361/// Resolve which `(input_index, stream_index)` pairs go to the output, in
1362/// output order. With no `-map`, defaults to every video + audio stream across
1363/// all inputs (input order, then stream order). Kinds in
1364/// [`OutputSpec::disabled`] are then dropped, mapped or not.
1365fn select_streams(inputs: &[Vec<Stream>], output: &OutputSpec) -> Result<Vec<(usize, usize)>> {
1366    let mut selection = mapped_streams(inputs, output)?;
1367    selection.retain(|&(ii, i)| !output.disabled.contains(&inputs[ii][i].media_type));
1368    Ok(selection)
1369}
1370
1371fn mapped_streams(inputs: &[Vec<Stream>], output: &OutputSpec) -> Result<Vec<(usize, usize)>> {
1372    let mut selection = Vec::new();
1373    if output.maps.is_empty() {
1374        for (ii, streams) in inputs.iter().enumerate() {
1375            for (i, s) in streams.iter().enumerate() {
1376                if matches!(
1377                    s.media_type,
1378                    MediaType::Video | MediaType::Audio | MediaType::Subtitle
1379                ) {
1380                    selection.push((ii, i));
1381                }
1382            }
1383        }
1384    } else {
1385        for map in &output.maps {
1386            let streams = inputs
1387                .get(map.input)
1388                .ok_or_else(|| Error::Option(format!("-map: no input #{}", map.input)))?;
1389            for (i, s) in streams.iter().enumerate() {
1390                let hit = match &map.selector {
1391                    MapSelector::All => true,
1392                    MapSelector::Kind(k) => s.media_type == *k,
1393                    MapSelector::Index(idx) => i == *idx,
1394                };
1395                if hit {
1396                    selection.push((map.input, i));
1397                }
1398            }
1399        }
1400    }
1401    Ok(selection)
1402}
1403
1404/// Build the [`StreamOp`] (transcode or copy) and matching output [`Stream`] for
1405/// one selected input stream at output position `out_index`.
1406fn build_op(
1407    engine: &Engine,
1408    stream: &Stream,
1409    output: &OutputSpec,
1410    out_index: usize,
1411) -> Result<(StreamOp, Stream)> {
1412    let requested = match stream.media_type {
1413        MediaType::Video => output.video_codec.as_ref(),
1414        MediaType::Audio => output.audio_codec.as_ref(),
1415        _ => None,
1416    };
1417    match requested {
1418        // Transcode: decode the input codec, re-encode to the requested one.
1419        Some(target) => {
1420            let mut decoder = engine.codecs.find_decoder(stream.codec_id)?;
1421            decoder.configure(&codec_params(stream))?;
1422            let mut encoder = engine.codecs.find_encoder(target.codec)?;
1423            encoder.configure(&target.options)?; // rate control: -crf / -preset / -b
1424                                                 // Video filter graph (`-vf`); applies to video streams only.
1425            let mut filters = if stream.media_type == MediaType::Video {
1426                FilterChain::parse(output.video_filters.as_deref().unwrap_or(""))?
1427            } else {
1428                FilterChain::default()
1429            };
1430            // Colour range has to be reconciled before any filter runs. JPEG (and
1431            // the other image codecs) are defined on full-range samples, so
1432            // handing them limited-range video encodes the wrong signal — it
1433            // measured 28.35 dB where it should have been 36.15 dB, a deficit
1434            // that looked exactly like poor encoder quality. Convert once, up
1435            // front, then tell the rest of the chain what it is now looking at.
1436            let mut source_range = ColorRange::Unspecified;
1437            if stream.media_type == MediaType::Video {
1438                source_range = effective_color_range(stream);
1439                if is_full_range_codec(target.codec) && source_range == ColorRange::Limited {
1440                    filters.prepend_range_conversion(true);
1441                    source_range = ColorRange::Full;
1442                }
1443                filters.set_source_color_range(source_range);
1444            }
1445            let (out_w, out_h) = filters.output_dims(stream.width, stream.height);
1446            let is_video = stream.media_type == MediaType::Video;
1447            let is_audio = stream.media_type == MediaType::Audio;
1448
1449            // Audio filter chain (`-af`); audio streams only.
1450            let audio_chain = if is_audio {
1451                rff_filter::AudioFilterChain::parse(output.audio_filters.as_deref().unwrap_or(""))?
1452            } else {
1453                rff_filter::AudioFilterChain::default()
1454            };
1455
1456            // `-ac`: validate up front — only mono/stereo mixing exists.
1457            let target_channels = match output.audio_channels {
1458                Some(c) if is_audio => {
1459                    if !(1..=2).contains(&c) {
1460                        return Err(Error::unsupported(format!(
1461                            "-ac {c}: only 1 or 2 channels supported"
1462                        )));
1463                    }
1464                    c
1465                }
1466                _ => 0,
1467            };
1468
1469            // Output sample rate: `-ar` / `aresample=` wins, else the input
1470            // rate; either way the encoder's accepted-rate list has the last
1471            // word (nearest accepted).
1472            let mut target_rate = 0;
1473            let mut out_rate = stream.sample_rate;
1474            if is_audio && stream.sample_rate > 0 {
1475                let desired = output
1476                    .audio_rate
1477                    .or(audio_chain.resample_target())
1478                    .unwrap_or(stream.sample_rate);
1479                let desired = match encoder.accepted_sample_rates() {
1480                    Some(rates) if !rates.contains(&desired) => nearest_rate(&rates, desired),
1481                    _ => desired,
1482                };
1483                if desired != stream.sample_rate {
1484                    target_rate = desired;
1485                }
1486                out_rate = desired;
1487            }
1488
1489            // Trim window and the tick shift that re-zeroes the output timeline.
1490            let trim = Trim::from_spec(output);
1491            let tb = stream.time_base;
1492            let shift_ticks = trim
1493                .map(|t| (t.start * tb.den as f64 / tb.num.max(1) as f64).round() as i64)
1494                .unwrap_or(0);
1495
1496            // `-r`: CFR stage; the output stream ticks in 1/fps units.
1497            let fps = match output.frame_rate {
1498                Some((num, den)) if is_video => Some(FpsConv::new(num, den)),
1499                _ => None,
1500            };
1501
1502            let mut accepted_formats = encoder.accepted_pixel_formats();
1503            let requested_format = if is_video { output.pixel_format } else { None };
1504
1505            let mut os = Stream::new(out_index, target.codec);
1506            os.media_type = stream.media_type;
1507            os.time_base = stream.time_base;
1508            os.width = out_w;
1509            os.height = out_h;
1510            os.pixel_format = stream.pixel_format;
1511            // Raw output declares its pixel format in the container header,
1512            // which the muxer writes before a single frame has been seen. So the
1513            // format cannot be discovered later — pin it now and force frames to
1514            // match, or the header ends up describing data it does not have.
1515            // (A 4:4:4 JPEG decoded straight to planes under a `C420mpeg2`
1516            // header is silent corruption, not a mislabel.)
1517            if target.codec == CodecId::RawVideo && stream.media_type == MediaType::Video {
1518                let pinned = requested_format
1519                    .or(os.pixel_format)
1520                    .unwrap_or(PixelFormat::Yuv420p);
1521                os.pixel_format = Some(pinned);
1522                accepted_formats = Some(vec![pinned]);
1523            }
1524            // Colour range: a `format=` filter that converts to Y'CbCr decides
1525            // it; otherwise it rides through from the input. Decoders whose
1526            // native output is RGB (JPEG, PNG, GIF, WebP) are full-range by
1527            // definition, so an untagged input from one of those is Full, not
1528            // "unknown" — leaving it unspecified makes the muxer label the
1529            // samples limited-range and every reader then rescales them.
1530            // A colour conversion in the chain decides the output range;
1531            // otherwise it is whatever we reconciled the source to above.
1532            os.color_range = filters.output_color_range().unwrap_or(source_range);
1533            let mut pixels = PixelConform::new(accepted_formats, requested_format, target.codec);
1534            // The automatic conversion is the colour conversion when nothing in
1535            // the chain already is one: label the stream with the range it
1536            // will produce (limited for an RGB source into a Y'CbCr video
1537            // codec), and commit the pixel format the encoder will really see.
1538            // Image demuxers rarely declare a pixel format, but their decoders
1539            // are known to emit packed RGB(A): that is enough to know an RGB
1540            // → Y'CbCr conversion is coming.
1541            let src_format = stream
1542                .pixel_format
1543                .or_else(|| decodes_to_rgb(stream.codec_id).then_some(PixelFormat::Rgb24));
1544            if is_video && filters.output_color_range().is_none() {
1545                if let Some(src) = src_format {
1546                    if let Ok((fmt, _)) = pixels.negotiate(src) {
1547                        if pixels.rgb_to_limited && src.is_rgb() && !fmt.is_rgb() {
1548                            os.color_range = ColorRange::Limited;
1549                        }
1550                        if stream.pixel_format.is_some() && target.codec != CodecId::RawVideo {
1551                            os.pixel_format = Some(fmt);
1552                        }
1553                    }
1554                }
1555            }
1556            // Colour range at the encoder (#213), FFmpeg's way: the encoder
1557            // signals the range of its frames in the bitstream (AV1 / VP9
1558            // `color_range`, H.264 `video_full_range_flag`), or, when it
1559            // cannot signal full range, the frames are converted to limited.
1560            // Either way the samples, the bitstream and the container label
1561            // agree; before, full-range Y'CbCr went out under the bitstream's
1562            // default limited label (28 dB through dav1d instead of 40).
1563            let mut range_fix = None;
1564            if is_video {
1565                let range = match os.color_range {
1566                    ColorRange::Full => ColorRange::Full,
1567                    _ => ColorRange::Limited,
1568                };
1569                if !encoder.set_color_range(range) && range == ColorRange::Full {
1570                    range_fix = Some(FilterChain::parse("setrange=limited")?);
1571                    os.color_range = ColorRange::Limited;
1572                    encoder.set_color_range(ColorRange::Limited);
1573                }
1574                pixels.out_range = Some(os.color_range);
1575            }
1576            os.sample_rate = out_rate;
1577            os.channels = if target_channels > 0 {
1578                target_channels
1579            } else {
1580                stream.channels
1581            };
1582            // A CFR conversion re-times the stream: pts become slot indices.
1583            if let Some((num, den)) = output.frame_rate {
1584                if is_video {
1585                    os.time_base = rff_core::Rational::new(den as i32, num as i32);
1586                }
1587            }
1588            // A format pinned by the output codec NAME (`-c:a pcm_s16le`) wins:
1589            // it is an explicit request, and the muxer writes it into the
1590            // container header before any frame is seen. Otherwise compressed
1591            // decoders (AAC/Opus/Vorbis/FLAC/MP3) emit f32, so default to that
1592            // when the input doesn't declare a format.
1593            let target_sample_format = target.sample_format;
1594            os.sample_format = target_sample_format
1595                .or(stream.sample_format)
1596                .or(Some(SampleFormat::F32));
1597            // The muxer writes os.sample_format into the container header
1598            // BEFORE any frame is seen, so every frame must be conformed to
1599            // that committed format — decoders may legitimately emit either
1600            // layout (the FLAC decoder emits native s16 for 16-bit streams).
1601            let target_sample_format = target_sample_format.or(os.sample_format);
1602            // Audio encoders timestamp packets in per-channel samples, so the
1603            // output stream's time base is 1/sample_rate.
1604            if stream.media_type == MediaType::Audio && out_rate > 0 {
1605                os.time_base = rff_core::Rational::new(1, out_rate as i32);
1606            }
1607            Ok((
1608                StreamOp::Transcode(Box::new(TranscodeOp {
1609                    decoder,
1610                    encoder,
1611                    filters,
1612                    overlay: None,
1613                    in_time_base: stream.time_base,
1614                    is_video,
1615                    trim,
1616                    shift_ticks,
1617                    audio_clock_samples: 0,
1618                    fps,
1619                    audio_chain,
1620                    target_channels,
1621                    target_rate,
1622                    target_sample_format,
1623                    resampler: None,
1624                    pixels,
1625                    range_fix,
1626                    source_range,
1627                    warnings: Vec::new(),
1628                    out_index,
1629                    max_video_frames: output.max_video_frames,
1630                    video_frames_sent: 0,
1631                    pending_pts: std::collections::VecDeque::new(),
1632                })),
1633                os,
1634            ))
1635        }
1636        // Stream copy: carry the same codec/packets through unchanged (the trim
1637        // window still applies, cutting video on keyframes).
1638        None => {
1639            let mut os = stream.clone();
1640            os.index = out_index;
1641            // `-c:s`: text subtitles share one packet contract, so choosing a
1642            // subtitle codec relabels the stream (SubRip ↔ WebVTT) in place.
1643            if stream.media_type == MediaType::Subtitle {
1644                if let Some(target) = output.subtitle_codec {
1645                    if target.media_type() != MediaType::Subtitle {
1646                        return Err(Error::unsupported(format!(
1647                            "-c:s: `{}` is not a subtitle codec",
1648                            target.name()
1649                        )));
1650                    }
1651                    os.codec_id = target;
1652                }
1653            }
1654            let trim = Trim::from_spec(output);
1655            let tb = stream.time_base;
1656            let to_ticks = |s: f64| (s * tb.den as f64 / tb.num.max(1) as f64).round() as i64;
1657            Ok((
1658                StreamOp::Copy(CopyOp {
1659                    out_index,
1660                    is_video: stream.media_type == MediaType::Video,
1661                    start_ticks: trim.map(|t| to_ticks(t.start)).unwrap_or(0),
1662                    end_ticks: trim.and_then(|t| t.end).map(to_ticks),
1663                    trimming: trim.is_some(),
1664                    started: false,
1665                }),
1666                os,
1667            ))
1668        }
1669    }
1670}
1671
1672/// Decode the first video frame of the overlay input and convert it to 4:2:0,
1673/// ready to composite onto the base's YUV frames.
1674fn decode_overlay_frame(
1675    engine: &Engine,
1676    demuxer: &mut dyn rff_format::Demuxer,
1677    streams: &[Stream],
1678) -> Result<VideoFrame> {
1679    let vidx = streams
1680        .iter()
1681        .position(|s| s.media_type == MediaType::Video)
1682        .ok_or_else(|| {
1683            Error::Option("filter_complex overlay: overlay input has no video".into())
1684        })?;
1685    let mut decoder = engine.codecs.find_decoder(streams[vidx].codec_id)?;
1686    decoder.configure(&codec_params(&streams[vidx]))?;
1687    let mut to_yuv = FilterChain::parse("format=yuv420p")?;
1688    let mut got_eof = false;
1689    loop {
1690        let frame = match demuxer.read_packet() {
1691            Ok(pkt) if pkt.stream_index != vidx => continue,
1692            Ok(pkt) => {
1693                decoder.send_packet(&pkt)?;
1694                decoder.receive_frame()
1695            }
1696            Err(Error::Eof) if !got_eof => {
1697                got_eof = true;
1698                decoder.flush();
1699                decoder.receive_frame()
1700            }
1701            Err(e) => return Err(e),
1702        };
1703        match frame {
1704            Ok(Frame::Video(v)) => return to_yuv.apply(v),
1705            Ok(_) => continue,
1706            Err(Error::Again) if !got_eof => continue,
1707            Err(Error::Again) | Err(Error::Eof) => {
1708                return Err(Error::Option(
1709                    "filter_complex overlay: no decodable frame in the overlay input".into(),
1710                ))
1711            }
1712            Err(e) => return Err(e),
1713        }
1714    }
1715}
1716
1717/// Build the decoder configuration from a demuxed input stream.
1718fn codec_params(s: &Stream) -> CodecParams {
1719    CodecParams {
1720        codec_id: s.codec_id,
1721        width: s.width,
1722        height: s.height,
1723        pixel_format: s.pixel_format,
1724        sample_rate: s.sample_rate,
1725        channels: s.channels,
1726        sample_format: s.sample_format,
1727        extradata: s.extradata.clone(),
1728    }
1729}
1730
1731/// Route one demuxed packet through its stream's plan.
1732fn process_packet(
1733    packet: Packet,
1734    ops: &mut [StreamOp],
1735    muxer: &mut dyn Muxer,
1736    report: &mut TranscodeReport,
1737) -> Result<()> {
1738    let Some(op) = ops.get_mut(packet.stream_index) else {
1739        return Ok(()); // packet for a stream we didn't plan — drop it
1740    };
1741    match op {
1742        StreamOp::Skip => Ok(()),
1743        StreamOp::Copy(copy) => {
1744            if let Some(packet) = copy.process(packet) {
1745                muxer.write_packet(&packet)?;
1746                report.packets_written += 1;
1747            }
1748            Ok(())
1749        }
1750        StreamOp::Transcode(op) => {
1751            phases::time(&phases::DECODE, || op.decoder.send_packet(&packet))?;
1752            loop {
1753                match phases::time(&phases::DECODE, || op.decoder.receive_frame()) {
1754                    Ok(frame) => op.handle_frame(frame, muxer, report)?,
1755                    Err(Error::Again) | Err(Error::Eof) => break,
1756                    Err(e) => return Err(e),
1757                }
1758            }
1759            Ok(())
1760        }
1761    }
1762}
1763
1764/// At end of input, flush each transcoded stream's decoder, filter state, and
1765/// encoder, writing out anything still buffered.
1766fn flush_streams(
1767    ops: &mut [StreamOp],
1768    muxer: &mut dyn Muxer,
1769    report: &mut TranscodeReport,
1770) -> Result<()> {
1771    for op in ops.iter_mut() {
1772        if let StreamOp::Transcode(op) = op {
1773            op.finish(muxer, report)?;
1774        }
1775    }
1776    Ok(())
1777}
1778
1779/// Open an input and decide its container format — local file (seekable) or
1780/// `http://` URL. Delegates to the shared [`crate::probe`] opener so ffmpeg and
1781/// ffprobe resolve inputs identically.
1782fn open_input(engine: &Engine, input: &InputSpec) -> Result<(String, crate::probe::Source)> {
1783    let path = input
1784        .path
1785        .to_str()
1786        .ok_or_else(|| Error::Option("input path is not valid UTF-8".into()))?;
1787    crate::probe::open_source(engine, path, input.format.as_deref())
1788}
1789
1790/// Decide which container to mux an output as: explicit `-f`, else by
1791/// extension. An `rtmp://` target implies FLV — that is the payload RTMP
1792/// carries (matching FFmpeg's default for rtmp outputs).
1793fn resolve_output_format(engine: &Engine, output: &OutputSpec) -> Result<String> {
1794    if let Some(forced) = &output.format {
1795        return Ok(forced.clone());
1796    }
1797    if output.path.to_str().is_some_and(rff_io::is_rtmp) {
1798        return Ok("flv".to_string());
1799    }
1800    let ext = output
1801        .path
1802        .extension()
1803        .and_then(|e| e.to_str())
1804        .unwrap_or_default();
1805    engine
1806        .formats
1807        .by_extension(ext)
1808        .map(|f| f.name.to_string())
1809        .ok_or_else(|| {
1810            Error::MuxerNotFound(format!(
1811                "{} (no format for this extension — pass -f)",
1812                output.path.display()
1813            ))
1814        })
1815}
1816
1817#[cfg(test)]
1818mod sample_format_tests {
1819    use super::*;
1820
1821    fn f32_af(samples: &[f32]) -> Frame {
1822        f32_frame(samples.to_vec(), 44_100, 1, Some(0))
1823    }
1824
1825    /// `-c:a pcm_s16le` used to be silently ignored on decode: the codec NAME
1826    /// carries the format but `CodecId` does not, so raw output kept whatever
1827    /// the decoder emitted (f32), writing double the bytes under an s16 request.
1828    #[test]
1829    fn pinned_format_converts_f32_to_s16() {
1830        let src = [0.0f32, 0.5, -0.5, 1.0, -1.0];
1831        let out = conform_sample_format(Some(SampleFormat::S16), f32_af(&src)).unwrap();
1832        let Frame::Audio(af) = out else {
1833            unreachable!()
1834        };
1835        assert_eq!(af.format, SampleFormat::S16);
1836        assert_eq!(af.planes[0].len(), src.len() * 2, "s16 is 2 bytes/sample");
1837        let got: Vec<i16> = af.planes[0]
1838            .chunks_exact(2)
1839            .map(|b| i16::from_le_bytes([b[0], b[1]]))
1840            .collect();
1841        // Round-to-nearest, and full scale must CLAMP rather than wrap: 1.0 maps
1842        // to 32767, not to -32768 via overflow.
1843        assert_eq!(got, vec![0, 16384, -16384, 32767, -32768]);
1844    }
1845
1846    /// No pin, or a frame already in the target format, must pass through
1847    /// untouched — the conversion is not allowed to cost anything when idle.
1848    #[test]
1849    fn unpinned_or_matching_format_is_a_passthrough() {
1850        let src = [0.25f32, -0.25];
1851        let Frame::Audio(a) = conform_sample_format(None, f32_af(&src)).unwrap() else {
1852            unreachable!()
1853        };
1854        assert_eq!(a.format, SampleFormat::F32);
1855        let Frame::Audio(b) = conform_sample_format(Some(SampleFormat::F32), f32_af(&src)).unwrap()
1856        else {
1857            unreachable!()
1858        };
1859        assert_eq!(b.format, SampleFormat::F32);
1860        assert_eq!(b.planes[0], a.planes[0]);
1861    }
1862
1863    /// The codec name is the only place the format lives for raw PCM.
1864    #[test]
1865    fn codec_name_pins_the_sample_format() {
1866        assert_eq!(
1867            CodecId::sample_format_from_name("pcm_s16le"),
1868            Some(SampleFormat::S16)
1869        );
1870        assert_eq!(
1871            CodecId::sample_format_from_name("pcm_f32le"),
1872            Some(SampleFormat::F32)
1873        );
1874        // Bare `pcm` pins nothing, and compressed codecs never do.
1875        assert_eq!(CodecId::sample_format_from_name("pcm"), None);
1876        assert_eq!(CodecId::sample_format_from_name("mp3"), None);
1877    }
1878}
1879
1880#[cfg(test)]
1881mod pixel_format_negotiation_tests {
1882    use super::*;
1883    use PixelFormat::*;
1884
1885    const AVIF: &[PixelFormat] = &[Yuv420p, Yuv444p, Yuv422p, Yuv420p10, Yuv444p10, Yuv422p10];
1886
1887    fn pick(
1888        src: PixelFormat,
1889        accepted: Option<&[PixelFormat]>,
1890        requested: Option<PixelFormat>,
1891    ) -> (PixelFormat, Vec<String>) {
1892        negotiate_pixel_format(src, accepted, requested, CodecId::Avif).unwrap()
1893    }
1894
1895    #[test]
1896    fn rgb_into_a_yuv_encoder_takes_its_first_8_bit_format() {
1897        assert_eq!(pick(Rgb24, Some(AVIF), None), (Yuv420p, vec![]));
1898        assert_eq!(pick(Rgb24, Some(&[Yuv420p]), None), (Yuv420p, vec![]));
1899    }
1900
1901    #[test]
1902    fn accepted_sources_pass_through() {
1903        for f in AVIF {
1904            assert_eq!(pick(*f, Some(AVIF), None), (*f, vec![]));
1905        }
1906        assert_eq!(pick(Rgba, None, None), (Rgba, vec![]));
1907    }
1908
1909    #[test]
1910    fn high_bit_depth_is_kept_when_the_encoder_takes_it() {
1911        assert_eq!(pick(Yuv420p12, Some(AVIF), None).0, Yuv420p10);
1912        assert_eq!(pick(Yuv422p12, Some(AVIF), None).0, Yuv422p10);
1913        // ... and narrowed when it does not.
1914        assert_eq!(pick(Yuv420p10, Some(&[Yuv420p]), None).0, Yuv420p);
1915    }
1916
1917    #[test]
1918    fn pix_fmt_wins_when_accepted() {
1919        assert_eq!(pick(Rgb24, Some(AVIF), Some(Yuv444p)), (Yuv444p, vec![]));
1920        assert_eq!(
1921            pick(Rgb24, Some(AVIF), Some(Yuv420p10)),
1922            (Yuv420p10, vec![])
1923        );
1924        // An encoder that takes anything takes the request too.
1925        assert_eq!(pick(Rgb24, None, Some(Yuv422p)), (Yuv422p, vec![]));
1926        // Even when the source is already acceptable as it is.
1927        assert_eq!(pick(Yuv420p, Some(AVIF), Some(Yuv420p10)).0, Yuv420p10);
1928    }
1929
1930    #[test]
1931    fn unaccepted_pix_fmt_falls_back_with_ffmpegs_warning() {
1932        let (fmt, warnings) = pick(Rgb24, Some(AVIF), Some(Rgb24));
1933        assert_eq!(fmt, Yuv420p);
1934        assert_eq!(
1935            warnings,
1936            vec!["Incompatible pixel format 'rgb24' for codec 'avif', auto-selecting format 'yuv420p'"]
1937        );
1938        // A deep request falls back to a deep format.
1939        let (fmt, warnings) = pick(Rgb24, Some(AVIF), Some(Yuv420p12));
1940        assert_eq!(fmt, Yuv420p10);
1941        assert_eq!(warnings.len(), 1);
1942    }
1943
1944    #[test]
1945    fn dropped_alpha_is_reported() {
1946        let (fmt, warnings) = pick(Rgba, Some(AVIF), None);
1947        assert_eq!(fmt, Yuv420p);
1948        assert_eq!(warnings.len(), 1);
1949        assert!(warnings[0].contains("alpha"), "{warnings:?}");
1950        // Kept alpha is not.
1951        assert_eq!(pick(Rgba, Some(&[Rgb24, Rgba]), None), (Rgba, vec![]));
1952    }
1953
1954    /// The image encoders' choices are what they were before negotiation
1955    /// grew depth awareness: first convertible accepted format.
1956    #[test]
1957    fn existing_image_encoder_choices_are_unchanged() {
1958        let jpeg = &[Yuv420p, Yuv422p, Yuv444p, Rgb24, Rgba];
1959        for src in [Yuv420p10, Yuv422p10, Yuv444p10, Yuv420p12, Yuv444p12] {
1960            assert_eq!(pick(src, Some(jpeg), None).0, Yuv420p, "{}", src.name());
1961        }
1962        let png = &[Rgb24, Rgba];
1963        for src in [Yuv420p, Yuv422p, Yuv444p, Yuv420p10, Yuv444p12] {
1964            assert_eq!(pick(src, Some(png), None).0, Rgb24, "{}", src.name());
1965        }
1966    }
1967
1968    #[test]
1969    fn impossible_conversions_are_errors() {
1970        // 8-bit 4:2:0 cannot be upsampled to 4:4:4 by the pipeline.
1971        assert!(negotiate_pixel_format(Yuv420p, Some(&[Yuv444p]), None, CodecId::Avif).is_err());
1972        assert!(negotiate_pixel_format(Yuv420p, Some(AVIF), Some(Yuv444p), CodecId::Avif).is_err());
1973    }
1974
1975    /// The converter an RGB source gets in front of a Y'CbCr video encoder is
1976    /// BT.601 limited range (FFmpeg's default); in front of raw video it keeps
1977    /// following the source, as before.
1978    #[test]
1979    fn rgb_to_yuv_range_depends_on_the_codec() {
1980        let rgb = VideoFrame {
1981            width: 2,
1982            height: 2,
1983            format: Rgb24,
1984            planes: vec![vec![0u8; 12]],
1985            strides: vec![6],
1986            pts: None,
1987        };
1988        let luma_of_black = |codec| {
1989            let mut pc = PixelConform::new(Some(vec![Yuv420p]), None, codec);
1990            let mut w = Vec::new();
1991            match pc
1992                .conform(ColorRange::Full, Frame::Video(rgb.clone()), &mut w)
1993                .unwrap()
1994            {
1995                Frame::Video(v) => v.planes[0][0],
1996                Frame::Audio(_) => unreachable!(),
1997            }
1998        };
1999        assert_eq!(luma_of_black(CodecId::Avif), 16);
2000        assert_eq!(luma_of_black(CodecId::H264), 16);
2001        assert_eq!(luma_of_black(CodecId::RawVideo), 0);
2002    }
2003
2004    /// Once the output range is committed, an RGB frame converts to it — a
2005    /// source only found to be RGB at the first frame (a progressive JPEG,
2006    /// committed Full like every JPEG) must not be converted to limited under
2007    /// a full-range label (#213).
2008    #[test]
2009    fn rgb_to_yuv_follows_the_committed_range() {
2010        let rgb = VideoFrame {
2011            width: 2,
2012            height: 2,
2013            format: Rgb24,
2014            planes: vec![vec![0u8; 12]],
2015            strides: vec![6],
2016            pts: None,
2017        };
2018        for (range, black) in [(ColorRange::Full, 0), (ColorRange::Limited, 16)] {
2019            let mut pc = PixelConform::new(Some(vec![Yuv420p]), None, CodecId::Avif);
2020            pc.out_range = Some(range);
2021            let mut w = Vec::new();
2022            match pc
2023                .conform(ColorRange::Full, Frame::Video(rgb.clone()), &mut w)
2024                .unwrap()
2025            {
2026                Frame::Video(v) => assert_eq!(v.planes[0][0], black, "{range:?}"),
2027                Frame::Audio(_) => unreachable!(),
2028            }
2029        }
2030    }
2031}