Skip to main content

alpha2_native/
passthrough.rs

1//! Copying a source's compressed video packets into an export unchanged.
2//!
3//! The engine decides the project side (one untouched clip covering the range,
4//! [`alpha2_engine::passthrough_plan`]); this decides whether the packets under that range decode
5//! on their own into exactly the rendered frames, and performs the copy.
6//!
7//! The test is on timestamps, not flags. The copy is one contiguous run in decode order starting at
8//! an IDR access unit (a keyframe flag alone does not promise independence), and its presentation
9//! times must be exactly the export's frame times, one packet each. A B picture whose reference
10//! lies outside the range puts an out-of-range presentation time in the run and is refused, as are
11//! off-grid frames, variable rates and duplicates.
12//!
13//! Several runs join into one output ([`PacketCopy::join`]) when one MP4 sample description fits
14//! them all and decode times keep increasing across each join.
15
16use alpha2_host_core::remote::SourceLocation;
17
18use alpha2_ffmpeg_bridge::DemuxInput;
19use alpha2_media::{
20    CancelToken, ChromaLocation, ColorMetadata, EncodeError, StreamKind, YuvEncoding,
21};
22use alpha2_time::MediaTime;
23use rsmpeg::avutil::{AVRational, av_rescale_q};
24use rsmpeg::ffi;
25
26use crate::NativeVideoCodec;
27use crate::capabilities::FfmpegCodec;
28use crate::convert::{encode_adapter_error, encode_adapter_error_at, tick_base};
29use crate::mux::{AudioStream, Muxer, VideoStream};
30
31/// The stream an export copies from and what it must match.
32#[derive(Clone, Debug)]
33pub struct PacketCopyRequest<'a> {
34    /// The source.
35    pub source: &'a SourceLocation,
36    /// Each output frame's source time, in order: what rendering would show.
37    pub frame_times: &'a [MediaTime],
38    /// The output size, which the stream must already have.
39    pub width: u32,
40    /// The output height, which the stream must already have.
41    pub height: u32,
42    /// The codec the export asked for, which the stream must already be.
43    pub codec: NativeVideoCodec,
44    /// The file format the export writes, which must offer the copied streams' codecs.
45    pub container: alpha2_media::Container,
46    /// The color the output is tagged with; a copy keeps the source's tags, so they must match.
47    pub color: ColorMetadata,
48    /// Where this run's first frame lands in the output: zero for a single copy, a
49    /// segment's start in a join.
50    pub output_start: MediaTime,
51    /// The source's own untouched audio, copied where that can be exact (the whole file). Otherwise
52    /// the plan says why ([`PacketCopyPlan::audio_copy_refusal`]) and the caller encodes the mix;
53    /// the video copy stands either way.
54    pub audio: Option<PacketCopyAudio>,
55}
56
57/// What a copied audio stream must match.
58#[derive(Copy, Clone, Debug, Eq, PartialEq)]
59pub struct PacketCopyAudio {
60    /// The project's sample rate.
61    pub sample_rate: u32,
62    /// The export's channel count.
63    pub channels: u32,
64}
65
66/// A copy that can be made, and what it copies.
67#[derive(Clone, Debug)]
68pub struct PacketCopyPlan {
69    source: SourceLocation,
70    video_stream: usize,
71    audio_stream: Option<usize>,
72    /// Why audio the request offered to copy is not copied.
73    audio_refusal: Option<String>,
74    /// The copied run, as positions in the video stream's decode order.
75    first_packet: u64,
76    last_packet: u64,
77    /// The first packet's timestamps in the video time base, by which a
78    /// seeking writer recognizes it.
79    first_timestamps: (i64, i64),
80    /// The first output frame's presentation time in the video time base; it lands at `offset`.
81    origin: i64,
82    /// `output_start`, in the video stream's time base.
83    offset: i64,
84    video_time_base: AVRational,
85    /// What an MP4 sample description records; joined runs must agree on all of it.
86    contract: StreamContract,
87    /// The run's first and last decode times in the output, in ticks.
88    decode_span: (i64, i64),
89}
90
91/// The part of a video stream a single MP4 sample description fixes.
92#[derive(Clone, Debug, Eq, PartialEq)]
93struct StreamContract {
94    codec_id: ffi::AVCodecID,
95    width: i32,
96    height: i32,
97    format: i32,
98    extradata: Vec<u8>,
99    time_base: (i32, i32),
100}
101
102/// One or more copy runs written back to back into one output.
103#[derive(Clone, Debug)]
104pub struct PacketCopy {
105    segments: Vec<PacketCopyPlan>,
106}
107
108impl PacketCopy {
109    /// Joins runs, in output order, into one copy.
110    ///
111    /// Every run starts at an IDR, so a decoder restarts at each join. The join also requires one
112    /// sample description for all runs (codec, size, pixel format, parameter sets, time base) and
113    /// decode times that keep increasing, which fails when runs reorder pictures differently.
114    ///
115    /// # Errors
116    /// Names the join that breaks either, or a run copying audio in a join (copied audio only
117    /// travels with one whole file).
118    pub fn join(segments: Vec<PacketCopyPlan>) -> Result<Self, String> {
119        let first = segments
120            .first()
121            .ok_or_else(|| "a copy needs at least one run".to_owned())?;
122        if segments.len() > 1 && segments.iter().any(PacketCopyPlan::copies_audio) {
123            return Err("copied audio travels only with one whole file".to_owned());
124        }
125        for (index, pair) in segments.windows(2).enumerate() {
126            if pair[1].contract != first.contract {
127                return Err(format!(
128                    "the source of run {} is not encoded like the first run's (codec, size, pixel format, parameter sets, or time base differ), and one MP4 sample description must fit both",
129                    index + 2
130                ));
131            }
132            if pair[1].decode_span.0 <= pair[0].decode_span.1 {
133                return Err(format!(
134                    "at the join into run {}, decode times go back: the runs reorder pictures differently",
135                    index + 2
136                ));
137            }
138        }
139        Ok(Self { segments })
140    }
141
142    /// Video packets the copy writes: one per output frame.
143    #[must_use]
144    pub fn video_packets(&self) -> u64 {
145        self.segments
146            .iter()
147            .map(PacketCopyPlan::video_packets)
148            .sum()
149    }
150
151    /// Runs joined.
152    #[must_use]
153    pub fn segments(&self) -> usize {
154        self.segments.len()
155    }
156
157    /// Whether the source's audio is copied too.
158    #[must_use]
159    pub fn copies_audio(&self) -> bool {
160        matches!(&self.segments[..], [only] if only.copies_audio())
161    }
162
163    /// Why the source's audio, offered for copying, is not copied.
164    #[must_use]
165    pub fn audio_copy_refusal(&self) -> Option<&str> {
166        self.segments
167            .first()
168            .and_then(PacketCopyPlan::audio_copy_refusal)
169    }
170}
171
172impl PacketCopyPlan {
173    /// Video packets the copy writes: one per output frame.
174    #[must_use]
175    pub const fn video_packets(&self) -> u64 {
176        self.last_packet - self.first_packet + 1
177    }
178
179    /// Whether the source's audio is copied too.
180    #[must_use]
181    pub const fn copies_audio(&self) -> bool {
182        self.audio_stream.is_some()
183    }
184
185    /// Why the source's audio, offered for copying, is not copied.
186    #[must_use]
187    pub fn audio_copy_refusal(&self) -> Option<&str> {
188        self.audio_refusal.as_deref()
189    }
190}
191
192/// The export's mixed audio, block by block, for a copy that encodes it.
193pub trait AudioBlockFeed {
194    /// The next block, continuing from the previous one at output sample
195    /// zero; `None` once complete.
196    ///
197    /// # Errors
198    /// Says why the mix could not be produced.
199    fn next_block(&mut self) -> Result<Option<alpha2_media::AudioBlock>, String>;
200}
201
202/// The audio a packet copy writes beside its video.
203pub enum CopyAudio<'a> {
204    /// No audio.
205    None,
206    /// The plan's copied audio packets; see [`PacketCopyPlan::copies_audio`].
207    Source,
208    /// The export's mix, encoded.
209    Encode {
210        /// The encoder's settings.
211        config: crate::AudioStreamConfig,
212        /// Where the mix comes from.
213        feed: &'a mut dyn AudioBlockFeed,
214    },
215}
216
217/// What a copy wrote.
218#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
219pub struct PacketCopyReport {
220    /// Video packets written.
221    pub video_packets: u64,
222    /// Audio packets copied.
223    pub audio_packets: u64,
224    /// Audio sample frames encoded from the mix.
225    pub encoded_audio_frames: u64,
226    /// Payload bytes written, both streams.
227    pub bytes: u64,
228    /// How the finished file was published.
229    pub publish: Option<crate::PublishReport>,
230}
231
232#[derive(Clone)]
233struct ScannedPacket {
234    pts: i64,
235    dts: i64,
236    idr: bool,
237    /// The stream's sample description changes here (`AV_PKT_DATA_NEW_EXTRADATA`).
238    new_description: bool,
239}
240
241/// Decides whether `request` can be served by copying packets.
242///
243/// Hosts planning several runs use one [`PacketCopyPlanner`], which reads each source once.
244///
245/// # Errors
246/// Names the container, codec, size, color or frame timing a copy would not reproduce, or a run
247/// that does not start at an IDR picture.
248pub fn plan_packet_copy(request: &PacketCopyRequest<'_>) -> Result<PacketCopyPlan, String> {
249    PacketCopyPlanner::new(CancelToken::default()).plan(request)
250}
251
252/// Plans the runs of one export, reading each source once and stopping on cancel.
253pub struct PacketCopyPlanner {
254    cancel: CancelToken,
255    sources: std::collections::HashMap<SourceLocation, SourceFacts>,
256}
257
258/// What a plan learns of one source file, each part read on first use.
259#[derive(Default)]
260struct SourceFacts {
261    probe: Option<Result<crate::ProbeResult, String>>,
262    video: Option<Result<VideoParameters, String>>,
263    scan: Option<Result<std::rc::Rc<Scan>, String>>,
264}
265
266/// The selected video stream's codec parameters a copy depends on.
267#[derive(Clone)]
268struct VideoParameters {
269    codec_id: ffi::AVCodecID,
270    format: i32,
271    field_order: ffi::AVFieldOrder,
272    sample_aspect_ratio: AVRational,
273    extradata: Vec<u8>,
274    time_base: AVRational,
275    width: i32,
276    height: i32,
277    tags: (
278        ffi::AVColorPrimaries,
279        ffi::AVColorTransferCharacteristic,
280        ffi::AVColorSpace,
281        ffi::AVColorRange,
282    ),
283}
284
285impl PacketCopyPlanner {
286    /// A planner that gives up as soon as `cancel` is set.
287    #[must_use]
288    pub fn new(cancel: CancelToken) -> Self {
289        Self {
290            cancel,
291            sources: std::collections::HashMap::new(),
292        }
293    }
294
295    /// [`plan_packet_copy`], from what this planner has read of the source.
296    ///
297    /// # Errors
298    /// As [`plan_packet_copy`], and a cancel.
299    pub fn plan(&mut self, request: &PacketCopyRequest<'_>) -> Result<PacketCopyPlan, String> {
300        if request.frame_times.is_empty() {
301            return Err("the range has no frames".to_owned());
302        }
303        let probed = self.probe(request.source)?;
304        let (video_index, audio_stream) = check_metadata(&probed, request)?;
305        let parameters = self.video(request.source, video_index)?;
306        let (length_size, contract) = stream_framing(request, &parameters)?;
307        let time_base = parameters.time_base;
308        let expected = request
309            .frame_times
310            .iter()
311            .map(|time| av_rescale_q(time.ticks(), tick_base(), time_base))
312            .collect::<Vec<_>>();
313        // Exact frame identity: each expected pts must convert back to the frame time itself, or
314        // the grid does not land on the stream's time base.
315        if expected
316            .iter()
317            .zip(request.frame_times)
318            .any(|(pts, time)| av_rescale_q(*pts, time_base, tick_base()) != time.ticks())
319        {
320            return Err(
321                "the export's frame times do not land on the source's time base".to_owned(),
322            );
323        }
324        let scanned = self.scan(
325            request.source,
326            video_index,
327            probed.selected_audio,
328            request.codec,
329            length_size,
330        )?;
331        plan_run(
332            request,
333            &scanned,
334            &expected,
335            video_index,
336            audio_stream,
337            contract,
338        )
339    }
340
341    fn facts(&mut self, source: &SourceLocation) -> &mut SourceFacts {
342        self.sources.entry(source.clone()).or_default()
343    }
344
345    fn probe(&mut self, source: &SourceLocation) -> Result<crate::ProbeResult, String> {
346        self.facts(source)
347            .probe
348            .get_or_insert_with(|| {
349                crate::probe(source).map_err(|error| format!("probe failed: {error}"))
350            })
351            .clone()
352    }
353
354    fn video(&mut self, source: &SourceLocation, index: usize) -> Result<VideoParameters, String> {
355        self.facts(source)
356            .video
357            .get_or_insert_with(|| video_parameters(source, index))
358            .clone()
359    }
360
361    fn scan(
362        &mut self,
363        source: &SourceLocation,
364        index: usize,
365        audio: Option<usize>,
366        codec: NativeVideoCodec,
367        length_size: usize,
368    ) -> Result<std::rc::Rc<Scan>, String> {
369        let cancel = self.cancel.clone();
370        self.facts(source)
371            .scan
372            .get_or_insert_with(|| {
373                scan(source, index, codec, length_size, audio, &cancel).map(std::rc::Rc::new)
374            })
375            .clone()
376    }
377}
378
379fn plan_run(
380    request: &PacketCopyRequest<'_>,
381    scanned: &Scan,
382    expected: &[i64],
383    video_index: usize,
384    audio_stream: Option<Result<usize, String>>,
385    contract: StreamContract,
386) -> Result<PacketCopyPlan, String> {
387    let time_base = AVRational {
388        num: contract.time_base.0,
389        den: contract.time_base.1,
390    };
391    let packets = &scanned.video;
392    let first = packets
393        .iter()
394        .position(|packet| packet.pts == expected[0])
395        .ok_or_else(|| "no source frame is at the range's first frame time".to_owned())?;
396    let last = first + expected.len() - 1;
397    let run = packets
398        .get(first..=last)
399        .ok_or_else(|| "the source ends before the range does".to_owned())?;
400    if !run[0].idr {
401        return Err(
402            "the range does not start at an IDR picture, so its first frames may refer to earlier ones"
403                .to_owned(),
404        );
405    }
406    // Parameter sets come from the first sample description; a run under another would
407    // decode with the wrong ones.
408    if packets[1..=last]
409        .iter()
410        .any(|packet| packet.new_description)
411    {
412        return Err(
413            "the source changes its sample description (its parameter sets) before or inside the range, and a copy carries only the first"
414                .to_owned(),
415        );
416    }
417    let mut presented = run.iter().map(|packet| packet.pts).collect::<Vec<_>>();
418    presented.sort_unstable();
419    if presented != expected {
420        return Err(
421            "the packets under the range are not exactly its frames: the source is off the export's frame grid, or a picture in it depends on one outside it"
422                .to_owned(),
423        );
424    }
425    // Except over the whole file, boundary audio packets straddle the range, and
426    // cutting them is not a copy.
427    let (audio_stream, audio_refusal) = match audio_stream {
428        Some(Ok(_)) if first != 0 || last + 1 != packets.len() => (
429            None,
430            Some("audio is copied only with the whole of its video".to_owned()),
431        ),
432        Some(Ok(index)) => match check_audio_span(scanned.audio, expected[0], time_base, request) {
433            Ok(()) => (Some(index), None),
434            Err(reason) => (None, Some(reason)),
435        },
436        Some(Err(reason)) => (None, Some(reason)),
437        None => (None, None),
438    };
439    let offset = av_rescale_q(request.output_start.ticks(), tick_base(), time_base);
440    let output_decode = |dts: i64| av_rescale_q(dts - expected[0] + offset, time_base, tick_base());
441    let decode_span = (
442        output_decode(run.iter().map(|packet| packet.dts).min().unwrap_or(0)),
443        output_decode(run.iter().map(|packet| packet.dts).max().unwrap_or(0)),
444    );
445    Ok(PacketCopyPlan {
446        source: request.source.to_owned(),
447        video_stream: video_index,
448        audio_stream,
449        audio_refusal,
450        first_packet: u64::try_from(first).unwrap_or(u64::MAX),
451        last_packet: u64::try_from(last).unwrap_or(u64::MAX),
452        first_timestamps: (run[0].pts, run[0].dts),
453        origin: expected[0],
454        offset,
455        video_time_base: time_base,
456        contract,
457        decode_span,
458    })
459}
460
461/// Checks the container and stream metadata a copy keeps: video, and audio when copied.
462fn check_metadata(
463    probed: &crate::ProbeResult,
464    request: &PacketCopyRequest<'_>,
465) -> Result<(usize, Option<Result<usize, String>>), String> {
466    if !probed
467        .format
468        .split(',')
469        .any(|name| matches!(name, "mov" | "mp4"))
470    {
471        return Err(format!(
472            "the source is {}, and only MP4/MOV sources are copied",
473            probed.format
474        ));
475    }
476    if !request.container.offers_video(request.codec.model()) {
477        return Err(format!(
478            "the source's {} is not offered in {}",
479            request.codec.as_str(),
480            request.container
481        ));
482    }
483    let video_index = probed
484        .selected_video
485        .ok_or_else(|| "the source has no video stream".to_owned())?;
486    check_picture(
487        probed,
488        video_index,
489        (request.width, request.height),
490        request.color,
491    )?;
492    let audio_stream = request
493        .audio
494        .map(|audio| copyable_audio(probed, audio, request.container));
495
496    Ok((video_index, audio_stream))
497}
498
499/// Whether the video's pictures, shown as they are, already are the output's: size, upright,
500/// square pixels, and color tags.
501fn check_picture(
502    probed: &crate::ProbeResult,
503    video_index: usize,
504    (width, height): (u32, u32),
505    color: ColorMetadata,
506) -> Result<(), String> {
507    let video = probed
508        .streams
509        .iter()
510        .find(|stream| stream.index == video_index)
511        .ok_or_else(|| "the source's video stream is missing".to_owned())?;
512    if video.dimensions != Some((width, height)) {
513        return Err(format!(
514            "the source is {:?}, not the {width}x{height} output",
515            video.dimensions
516        ));
517    }
518    if video.orientation.mirror {
519        return Err(
520            "the source mirrors the picture in its display matrix, which a render applies"
521                .to_owned(),
522        );
523    }
524    if video.orientation.rotation != alpha2_media::Rotation::Deg0 {
525        return Err("the source is rotated".to_owned());
526    }
527    let aspect = video.sample_aspect_ratio;
528    if aspect != alpha2_media::SampleAspectRatio::default() {
529        return Err(format!(
530            "the source shows {}:{} pixels, which a render makes square",
531            aspect.num, aspect.den
532        ));
533    }
534    if video.color != Some(color) {
535        return Err(format!(
536            "the source is tagged {:?}, and the output must be tagged {color:?}",
537            video.color
538        ));
539    }
540    Ok(())
541}
542
543/// Whether the codec's pixel aspect ratio, which a copy carries (bitstream and `pasp`), shows
544/// the pictures as a render does. A render uses the container's ratio, so a codec ratio the
545/// container overrides to square would show differently. Only copies ask this; a YUV transcode
546/// encodes its own parameters.
547fn check_carried_display(aspect: AVRational) -> Result<(), String> {
548    if aspect.num > 0 && aspect.den > 0 && aspect.num != aspect.den {
549        return Err(format!(
550            "the source's codec declares {}:{} pixels, which a copy keeps and its container overrides to square",
551            aspect.num, aspect.den
552        ));
553    }
554    Ok(())
555}
556
557/// Whether the pictures are progressive 8-bit 4:2:0 in one of `formats`.
558fn check_sampling(
559    format: i32,
560    field_order: ffi::AVFieldOrder,
561    formats: &[ffi::AVPixelFormat],
562) -> Result<(), String> {
563    if !formats.contains(&format) {
564        return Err("the source is not 8-bit 4:2:0".to_owned());
565    }
566    if !matches!(
567        field_order,
568        ffi::AV_FIELD_PROGRESSIVE | ffi::AV_FIELD_UNKNOWN
569    ) {
570        return Err("the source is interlaced".to_owned());
571    }
572    Ok(())
573}
574
575/// Whether `source`'s decoded pictures can become a `width`x`height` output's frames with no
576/// conversion: the file side of a YUV transcode, encoded as `encoding`.
577///
578/// Unlike a copy any container, codec and frame grid qualify, since frames are picked exactly as
579/// for a render; only size, orientation, pixel shape, color, sampling and chroma siting decide.
580///
581/// # Errors
582/// Names what the render would have changed.
583pub fn check_yuv_transcode(
584    source: &SourceLocation,
585    width: u32,
586    height: u32,
587    encoding: YuvEncoding,
588) -> Result<(), String> {
589    let input =
590        crate::decode::open_input(source).map_err(|error| format!("probe failed: {error}"))?;
591    let probed = crate::decode::probe_context(&input, source)
592        .map_err(|error| format!("probe failed: {error}"))?;
593    let video_index = probed
594        .selected_video
595        .ok_or_else(|| "the source has no video stream".to_owned())?;
596    check_picture(&probed, video_index, (width, height), encoding.color)?;
597    let parameters = input.streams()[video_index].codecpar();
598    let extradata = alpha2_ffmpeg_bridge::codec_parameters_extradata(&parameters);
599    if let Some(declared) = stream_vui(parameters.codec_id, &extradata).and_then(|vui| vui.color)
600        && declared != encoding.color
601    {
602        return Err(format!(
603            "the source's stream declares {declared:?}, and the output must be tagged {:?}",
604            encoding.color
605        ));
606    }
607    check_sampling(
608        parameters.format,
609        parameters.field_order,
610        &[ffi::AV_PIX_FMT_YUV420P, ffi::AV_PIX_FMT_NV12],
611    )?;
612    let siting =
613        crate::convert::decoded_chroma_location(parameters.codec_id, parameters.chroma_location);
614    if !same_chroma_siting(siting, encoding.chroma) {
615        return Err(format!(
616            "the source's chroma sits {siting:?}, and the output's must sit {:?}",
617            encoding.chroma
618        ));
619    }
620    Ok(())
621}
622
623/// The VUI of an H.264 or HEVC stream's first SPS. `FFmpeg`'s decoders give the pictures its
624/// color over the container's.
625fn stream_vui(
626    codec_id: ffi::AVCodecID,
627    extradata: &[u8],
628) -> Option<alpha2_host_core::parameter_sets::Vui> {
629    use alpha2_host_core::parameter_sets::{ParameterSetCodec, sequence_facts};
630    let codec = match codec_id {
631        ffi::AV_CODEC_ID_H264 => ParameterSetCodec::H264,
632        ffi::AV_CODEC_ID_HEVC => ParameterSetCodec::Hevc,
633        _ => return None,
634    };
635    Some(sequence_facts(codec, extradata)?.vui)
636}
637
638/// Whether chroma sited at `source` matches `output`, reading unspecified as centred like import.
639#[must_use]
640pub fn same_chroma_siting(source: ChromaLocation, output: ChromaLocation) -> bool {
641    let centred = |location| {
642        if location == ChromaLocation::Unspecified {
643            ChromaLocation::Center
644        } else {
645            location
646        }
647    };
648    centred(source) == centred(output)
649}
650
651fn video_parameters(source: &SourceLocation, index: usize) -> Result<VideoParameters, String> {
652    let input = open(source)?;
653    let stream = input
654        .streams()
655        .get(index)
656        .ok_or_else(|| "the source's video stream is missing".to_owned())?;
657    let parameters = stream.codecpar();
658    Ok(VideoParameters {
659        codec_id: parameters.codec_id,
660        format: parameters.format,
661        field_order: parameters.field_order,
662        sample_aspect_ratio: parameters.sample_aspect_ratio,
663        extradata: alpha2_ffmpeg_bridge::codec_parameters_extradata(&parameters),
664        time_base: stream.time_base,
665        width: parameters.width,
666        height: parameters.height,
667        tags: (
668            parameters.color_primaries,
669            parameters.color_trc,
670            parameters.color_space,
671            parameters.color_range,
672        ),
673    })
674}
675
676/// The video stream's NAL framing and sample description, after the codec-parameter checks.
677fn stream_framing(
678    request: &PacketCopyRequest<'_>,
679    parameters: &VideoParameters,
680) -> Result<(usize, StreamContract), String> {
681    if parameters.codec_id != request.codec.codec_id() {
682        return Err(format!(
683            "the source's video is not {}",
684            request.codec.as_str()
685        ));
686    }
687    check_sampling(
688        parameters.format,
689        parameters.field_order,
690        &[ffi::AV_PIX_FMT_YUV420P],
691    )?;
692    check_carried_display(parameters.sample_aspect_ratio)?;
693    // A copy keeps the stream's own tags, so they must equal the output's exactly, not
694    // just read as the same color.
695    if parameters.tags != crate::convert::color_tags(request.color) {
696        return Err(format!(
697            "the source is tagged primaries {}, transfer {}, matrix {}, range {} (FFmpeg's numbers), and the output must be tagged {:?}",
698            parameters.tags.0,
699            parameters.tags.1,
700            parameters.tags.2,
701            parameters.tags.3,
702            request.color
703        ));
704    }
705    if let Some(signal) =
706        stream_vui(parameters.codec_id, &parameters.extradata).and_then(|vui| vui.signal)
707    {
708        let tags = crate::convert::color_tags(request.color);
709        let output = [tags.0, tags.1, tags.2].map(|tag| u8::try_from(tag).unwrap_or(u8::MAX));
710        if signal.full_range != (tags.3 == ffi::AVCOL_RANGE_JPEG)
711            || signal
712                .description
713                .is_some_and(|description| description != output)
714        {
715            return Err(format!(
716                "the source's stream declares {:?} (H.273 primaries, transfer, matrix) and full \
717                 range {}, and the output must be tagged {:?}",
718                signal.description, signal.full_range, request.color
719            ));
720        }
721    }
722    let length_size = nal_length_size(request.codec, &parameters.extradata)?;
723    Ok((
724        length_size,
725        StreamContract {
726            codec_id: parameters.codec_id,
727            width: parameters.width,
728            height: parameters.height,
729            format: parameters.format,
730            extradata: parameters.extradata.clone(),
731            time_base: (parameters.time_base.num, parameters.time_base.den),
732        },
733    ))
734}
735
736/// The source's audio stream, when it is what the export would mix.
737fn copyable_audio(
738    probed: &crate::ProbeResult,
739    audio: PacketCopyAudio,
740    container: alpha2_media::Container,
741) -> Result<usize, String> {
742    let index = probed
743        .selected_audio
744        .ok_or_else(|| "the source has no audio stream to copy".to_owned())?;
745    let stream = probed
746        .streams
747        .iter()
748        .find(|stream| stream.index == index && stream.kind == StreamKind::Audio)
749        .ok_or_else(|| "the source's audio stream is missing".to_owned())?;
750    if stream.codec != "aac" {
751        return Err(format!("the source's audio is {}, not AAC", stream.codec));
752    }
753    if !container.offers_audio(alpha2_media::AudioCodec::Aac) {
754        return Err(format!("the source's aac is not offered in {container}"));
755    }
756    if stream.sample_rate != Some(audio.sample_rate) || stream.channels != Some(audio.channels) {
757        return Err(format!(
758            "the source's audio is {:?} Hz x {:?}, not the export's {} Hz x {}",
759            stream.sample_rate, stream.channels, audio.sample_rate, audio.channels
760        ));
761    }
762    Ok(index)
763}
764
765fn open(source: &SourceLocation) -> Result<DemuxInput, String> {
766    crate::decode::open_input(source).map_err(|error| format!("cannot open the source: {error}"))
767}
768
769/// The byte width of each NAL length prefix. Only length-prefixed (MP4) streams are copied; Annex B
770/// would need its framing rewritten.
771pub(crate) fn nal_length_size(codec: NativeVideoCodec, extradata: &[u8]) -> Result<usize, String> {
772    let annex_b = || "the source's parameter sets are not in MP4 form".to_owned();
773    match codec {
774        NativeVideoCodec::H264 if extradata.len() >= 7 && extradata[0] == 1 => {
775            Ok(usize::from(extradata[4] & 0b11) + 1)
776        }
777        NativeVideoCodec::Hevc if extradata.len() >= 23 && extradata[0] == 1 => {
778            Ok(usize::from(extradata[21] & 0b11) + 1)
779        }
780        NativeVideoCodec::H264 | NativeVideoCodec::Hevc => Err(annex_b()),
781        other => Err(format!(
782            "{} is not copied; only H.264 and HEVC are",
783            other.as_str()
784        )),
785    }
786}
787
788/// Whether a length-prefixed access unit holds an IDR picture.
789pub(crate) fn is_idr(codec: NativeVideoCodec, length_size: usize, data: &[u8]) -> bool {
790    let mut at = 0_usize;
791    while at + length_size < data.len() {
792        let length = data[at..at + length_size]
793            .iter()
794            .fold(0_usize, |value, byte| (value << 8) | usize::from(*byte));
795        let Some(&header) = data.get(at + length_size) else {
796            return false;
797        };
798        let idr = match codec {
799            NativeVideoCodec::H264 => header & 0x1f == 5,
800            // IDR_W_RADL and IDR_N_LP. A CRA may be followed by pictures referring to the previous
801            // GOP, so it does not count.
802            NativeVideoCodec::Hevc => matches!((header >> 1) & 0x3f, 19 | 20),
803            _ => false,
804        };
805        if idr {
806            return true;
807        }
808        at = at.saturating_add(length_size).saturating_add(length);
809    }
810    false
811}
812
813struct Scan {
814    /// Every video packet, in decode order.
815    video: Vec<ScannedPacket>,
816    /// The span of audio packets a copy would carry, with their time base; `None` without a
817    /// timestamped audio stream.
818    audio: Option<AudioSpan>,
819}
820
821#[derive(Clone, Copy)]
822struct AudioSpan {
823    first: i64,
824    last: i64,
825    /// Where the last packet ends (latest presentation time plus duration), and that duration.
826    end: i64,
827    last_duration: i64,
828    time_base: AVRational,
829}
830
831/// Reads the source once: every packet of video stream `index` and the timestamps of audio stream
832/// `audio`. Other streams are discarded, and `cancel` is checked between packets.
833fn scan(
834    path: &SourceLocation,
835    index: usize,
836    codec: NativeVideoCodec,
837    length_size: usize,
838    audio: Option<usize>,
839    cancel: &CancelToken,
840) -> Result<Scan, String> {
841    let mut input = open(path)?;
842    crate::decode::interrupt_on_cancel(&input, cancel);
843    input.keep_only(
844        &[Some(index), audio]
845            .into_iter()
846            .flatten()
847            .collect::<Vec<_>>(),
848    );
849    let audio_time_base =
850        audio.and_then(|audio| input.streams().get(audio).map(|stream| stream.time_base));
851    let mut packets = Vec::new();
852    let mut audio_span: Option<(i64, i64, i64, i64)> = None;
853    let cancelled = || "the export was cancelled while its copy was planned".to_owned();
854    loop {
855        if cancel.is_cancelled() {
856            return Err(cancelled());
857        }
858        let packet = match input.read_packet() {
859            Ok(Some(packet)) => packet,
860            Ok(None) => break,
861            Err(_) if cancel.is_cancelled() => return Err(cancelled()),
862            Err(error) => return Err(format!("cannot read the source: {error}")),
863        };
864        // Lets a host's watchdog see the scan progressing.
865        crate::recovery::report_decode_progress();
866        let stream = usize::try_from(packet.stream_index).ok();
867        if stream.is_some() && stream == audio {
868            for time in [packet.pts, packet.dts] {
869                if time != ffi::AV_NOPTS_VALUE {
870                    let span = audio_span.get_or_insert((time, time, time, 0));
871                    span.0 = span.0.min(time);
872                    span.1 = span.1.max(time);
873                }
874            }
875            if packet.pts != ffi::AV_NOPTS_VALUE {
876                let end = packet.pts.saturating_add(packet.duration.max(0));
877                if let Some(span) = audio_span.as_mut()
878                    && end >= span.2
879                {
880                    span.2 = end;
881                    span.3 = packet.duration.max(0);
882                }
883            }
884            continue;
885        }
886        if stream != Some(index) {
887            continue;
888        }
889        if packet.pts == ffi::AV_NOPTS_VALUE {
890            return Err("a source video packet has no presentation time".to_owned());
891        }
892        let key = packet.flags & i32::try_from(ffi::AV_PKT_FLAG_KEY).unwrap_or(0) != 0;
893        packets.push(ScannedPacket {
894            pts: packet.pts,
895            dts: if packet.dts == ffi::AV_NOPTS_VALUE {
896                packet.pts
897            } else {
898                packet.dts
899            },
900            idr: key
901                && is_idr(
902                    codec,
903                    length_size,
904                    &alpha2_ffmpeg_bridge::packet_bytes(&packet),
905                ),
906            new_description: alpha2_ffmpeg_bridge::packet_has_side_data(
907                &packet,
908                ffi::AV_PKT_DATA_NEW_EXTRADATA,
909            ),
910        });
911    }
912    Ok(Scan {
913        video: packets,
914        audio: audio_span.zip(audio_time_base).map(
915            |((first, last, end, last_duration), time_base)| AudioSpan {
916                first,
917                last,
918                end,
919                last_duration,
920                time_base,
921            },
922        ),
923    })
924}
925
926/// How far outside the copied video's span copied audio may reach, in ticks: AAC priming before
927/// plus the last frame's duration after.
928const COPIED_AUDIO_SLACK: i64 = alpha2_time::TICKS_PER_SECOND;
929
930/// Whether the copied audio lands where the render's mix does: every timestamp, shifted to put
931/// the first video frame in place, within the output video give or take
932/// [`COPIED_AUDIO_SLACK`]. The shift itself is checked, since timestamps are unchecked file
933/// data (a fragment's `tfdt` is any 64-bit value).
934fn check_audio_span(
935    span: Option<AudioSpan>,
936    origin: i64,
937    video_time_base: AVRational,
938    request: &PacketCopyRequest<'_>,
939) -> Result<(), String> {
940    let Some(span) = span else {
941        return Ok(());
942    };
943    let out_of_range = || {
944        "the source's audio timestamps lie outside its video, so copying them would not play the render's mix".to_owned()
945    };
946    let output_start = request.output_start.ticks();
947    let video_ticks = request
948        .frame_times
949        .last()
950        .map_or(0, |last| last.ticks() - request.frame_times[0].ticks());
951    let earliest = output_start.saturating_sub(COPIED_AUDIO_SLACK);
952    let latest = output_start
953        .saturating_add(video_ticks)
954        .saturating_add(COPIED_AUDIO_SLACK);
955    let shift_by = av_rescale_q(
956        origin - av_rescale_q(output_start, tick_base(), video_time_base),
957        video_time_base,
958        span.time_base,
959    );
960    for time in [span.first, span.last] {
961        let moved = time.checked_sub(shift_by).ok_or_else(out_of_range)?;
962        let ticks = av_rescale_q(moved, span.time_base, tick_base());
963        if ticks == ffi::AV_NOPTS_VALUE || !(earliest..=latest).contains(&ticks) {
964            return Err(out_of_range());
965        }
966    }
967    // The mix covers exactly the range, so copied audio may overrun the last frame's end by at
968    // most its own last packet.
969    let frames = i64::try_from(request.frame_times.len()).unwrap_or(i64::MAX);
970    let frame_ticks = if frames > 1 {
971        video_ticks / (frames - 1)
972    } else {
973        0
974    };
975    let video_end = output_start
976        .saturating_add(video_ticks)
977        .saturating_add(frame_ticks);
978    let end = av_rescale_q(
979        span.end.checked_sub(shift_by).ok_or_else(out_of_range)?,
980        span.time_base,
981        tick_base(),
982    );
983    let last_packet = av_rescale_q(span.last_duration, span.time_base, tick_base());
984    if end > video_end.saturating_add(last_packet) {
985        return Err(format!(
986            "the source's audio outlasts its video by {} ms, and a render mixes only the range",
987            (end - video_end) * 1_000 / alpha2_time::TICKS_PER_SECOND
988        ));
989    }
990    Ok(())
991}
992
993/// Writes `copy`'s runs back to back into a new `container` file at `output`, with `audio`. The
994/// runs were planned for `container` ([`PacketCopyRequest::container`]).
995///
996/// The output is transactional and renamed into place only when complete. Encoded audio is
997/// written slightly ahead of the video so neither stream piles up in the muxer. `progress`
998/// receives the video packets written.
999///
1000/// # Errors
1001/// Returns an adapter failure for an existing output, a partial a running export holds, a read
1002/// or write failure, a failed mix, audio the plan does not copy, or a cancel.
1003pub fn copy_packets(
1004    copy: &PacketCopy,
1005    output: impl Into<crate::OutputTarget>,
1006    container: alpha2_media::Container,
1007    audio: CopyAudio<'_>,
1008    cancel: &CancelToken,
1009    progress: &mut dyn FnMut(u64),
1010) -> Result<PacketCopyReport, EncodeError> {
1011    let first = &copy.segments[0];
1012    let input = crate::decode::open_input(&first.source).map_err(encode_adapter_error)?;
1013    let video_stream = {
1014        let source = &input.streams()[first.video_stream];
1015        VideoStream {
1016            parameters: source.codecpar().clone(),
1017            time_base: source.time_base,
1018            copied: true,
1019        }
1020    };
1021    let audio_stream = match &audio {
1022        CopyAudio::None => None,
1023        CopyAudio::Source => {
1024            if !copy.copies_audio() {
1025                return Err(EncodeError::Adapter("the plan copies no audio".into()));
1026            }
1027            let index = first.audio_stream.unwrap_or(0);
1028            let source = &input.streams()[index];
1029            Some(AudioStream::Copy {
1030                parameters: source.codecpar().clone(),
1031                time_base: source.time_base,
1032            })
1033        }
1034        CopyAudio::Encode { config, .. } => Some(AudioStream::Encode(*config)),
1035    };
1036    drop(input);
1037    let copied_audio = matches!(audio, CopyAudio::Source);
1038    let mut writer = RunWriter {
1039        muxer: Muxer::open_streams(output, container, video_stream, audio_stream)?,
1040        mix: match audio {
1041            CopyAudio::Encode { feed, .. } => Some(MixWriter {
1042                feed,
1043                covered: 0,
1044                done: false,
1045            }),
1046            CopyAudio::None | CopyAudio::Source => None,
1047        },
1048        stages: crate::EncodeStageTimings::default(),
1049        report: PacketCopyReport::default(),
1050    };
1051    for segment in &copy.segments {
1052        writer.write_run(segment, copied_audio, cancel, progress)?;
1053    }
1054    if writer.report.video_packets != copy.video_packets() {
1055        return Err(EncodeError::Adapter(format!(
1056            "the copy wrote {} video packets of the planned {}",
1057            writer.report.video_packets,
1058            copy.video_packets()
1059        )));
1060    }
1061    let RunWriter {
1062        mut muxer,
1063        mut mix,
1064        mut stages,
1065        mut report,
1066    } = writer;
1067    if let Some(mix) = mix.as_mut() {
1068        mix.write_until(i64::MAX, &mut muxer, &mut stages, &mut report)?;
1069    }
1070    muxer.finish_audio()?;
1071    muxer.write_ready_audio(true, &mut stages)?;
1072    muxer.close(cancel)?;
1073    report.publish = muxer.publish_report();
1074    Ok(report)
1075}
1076
1077/// The output a copy writes its runs into, and the mix it interleaves.
1078struct RunWriter<'a> {
1079    muxer: Muxer,
1080    mix: Option<MixWriter<'a>>,
1081    stages: crate::EncodeStageTimings,
1082    report: PacketCopyReport,
1083}
1084
1085impl RunWriter<'_> {
1086    /// Copies one run's packets, plus its source's audio when `copied_audio` (whole file only).
1087    fn write_run(
1088        &mut self,
1089        run: &PacketCopyPlan,
1090        copied_audio: bool,
1091        cancel: &CancelToken,
1092        progress: &mut dyn FnMut(u64),
1093    ) -> Result<(), EncodeError> {
1094        let mut input = crate::decode::open_input(&run.source).map_err(encode_adapter_error)?;
1095        crate::decode::interrupt_on_cancel(&input, cancel);
1096        let audio_stream = copied_audio.then_some(run.audio_stream).flatten();
1097        input.keep_only(
1098            &[Some(run.video_stream), audio_stream]
1099                .into_iter()
1100                .flatten()
1101                .collect::<Vec<_>>(),
1102        );
1103        let shift_by = run.origin - run.offset;
1104        // Later runs seek to their first packet (an indexed IDR). Copied audio only travels with a
1105        // whole file, which starts at packet zero.
1106        let mut video_position = if run.first_packet > 0 {
1107            let stream = i32::try_from(run.video_stream)
1108                .map_err(|_| EncodeError::Adapter("video stream index is out of range".into()))?;
1109            input
1110                .seek(
1111                    stream,
1112                    run.first_timestamps.1,
1113                    i32::try_from(ffi::AVSEEK_FLAG_BACKWARD).unwrap_or(0),
1114                )
1115                .map_err(|error| {
1116                    if cancel.is_cancelled() {
1117                        EncodeError::Cancelled
1118                    } else {
1119                        encode_adapter_error_at("seeking to the run", error)
1120                    }
1121                })?;
1122            None
1123        } else {
1124            Some(0_u64)
1125        };
1126        while let Some(mut packet) = input.read_packet().map_err(|error| {
1127            if cancel.is_cancelled() {
1128                EncodeError::Cancelled
1129            } else {
1130                encode_adapter_error(error)
1131            }
1132        })? {
1133            if cancel.is_cancelled() {
1134                return Err(EncodeError::Cancelled);
1135            }
1136            let stream = usize::try_from(packet.stream_index).ok();
1137            if stream == Some(run.video_stream) {
1138                let position = match video_position {
1139                    Some(position) => position,
1140                    None if (packet.pts, packet.dts) == run.first_timestamps => run.first_packet,
1141                    None => continue,
1142                };
1143                video_position = Some(position + 1);
1144                if position < run.first_packet {
1145                    continue;
1146                }
1147                if position > run.last_packet {
1148                    // Copied audio only travels with the whole video.
1149                    break;
1150                }
1151                packet.set_pts(shift(packet.pts, shift_by)?);
1152                packet.set_dts(shift(packet.dts, shift_by)?);
1153                packet.set_pos(-1);
1154                if let Some(mix) = self.mix.as_mut() {
1155                    let at = av_rescale_q(packet.dts, run.video_time_base, tick_base());
1156                    mix.write_until(
1157                        at.saturating_add(MIX_LEAD),
1158                        &mut self.muxer,
1159                        &mut self.stages,
1160                        &mut self.report,
1161                    )?;
1162                }
1163                self.report.bytes = self
1164                    .report
1165                    .bytes
1166                    .saturating_add(u64::try_from(packet.size).unwrap_or(0));
1167                self.muxer.write_video(&mut packet, run.video_time_base)?;
1168                self.report.video_packets += 1;
1169                progress(self.report.video_packets);
1170            } else if stream.is_some() && stream == audio_stream {
1171                let source_base = input.streams()[run.audio_stream.unwrap_or(0)].time_base;
1172                // The same zero as the video's; audio keeps its own offset from it, priming
1173                // included.
1174                let origin = av_rescale_q(shift_by, run.video_time_base, source_base);
1175                packet.set_pts(shift(packet.pts, origin)?);
1176                packet.set_dts(shift(packet.dts, origin)?);
1177                packet.set_pos(-1);
1178                self.report.bytes = self
1179                    .report
1180                    .bytes
1181                    .saturating_add(u64::try_from(packet.size).unwrap_or(0));
1182                self.muxer.write_copied_audio(&mut packet)?;
1183                self.report.audio_packets += 1;
1184            }
1185        }
1186        Ok(())
1187    }
1188}
1189
1190/// How far ahead of the video the encoded mix is written, so the muxer always has audio to
1191/// interleave without either stream piling up.
1192const MIX_LEAD: i64 = alpha2_time::TICKS_PER_SECOND / 10;
1193
1194/// The export's mix, written into the muxer as the video advances.
1195struct MixWriter<'a> {
1196    feed: &'a mut dyn AudioBlockFeed,
1197    /// Output time the mix written so far reaches, in ticks.
1198    covered: i64,
1199    done: bool,
1200}
1201
1202impl MixWriter<'_> {
1203    /// Writes blocks until the mix reaches `target`, or ends.
1204    fn write_until(
1205        &mut self,
1206        target: i64,
1207        muxer: &mut Muxer,
1208        stages: &mut crate::EncodeStageTimings,
1209        report: &mut PacketCopyReport,
1210    ) -> Result<(), EncodeError> {
1211        while !self.done && self.covered < target {
1212            let Some(block) = self.feed.next_block().map_err(EncodeError::Adapter)? else {
1213                self.done = true;
1214                break;
1215            };
1216            let frames = block.channels.first().map_or(0, Vec::len);
1217            muxer.write_audio(&block, stages)?;
1218            report.encoded_audio_frames = report
1219                .encoded_audio_frames
1220                .saturating_add(u64::try_from(frames).unwrap_or(u64::MAX));
1221            self.covered = i64::try_from(report.encoded_audio_frames)
1222                .unwrap_or(i64::MAX)
1223                .saturating_mul(alpha2_time::TICKS_PER_SECOND)
1224                .div_euclid(i64::from(block.sample_rate.max(1)));
1225        }
1226        Ok(())
1227    }
1228}
1229
1230/// `value` moved back by `origin`, keeping a missing timestamp missing and refusing overflow.
1231fn shift(value: i64, origin: i64) -> Result<i64, EncodeError> {
1232    if value == ffi::AV_NOPTS_VALUE {
1233        return Ok(value);
1234    }
1235    value
1236        .checked_sub(origin)
1237        .filter(|moved| *moved != ffi::AV_NOPTS_VALUE)
1238        .ok_or_else(|| {
1239            EncodeError::Adapter(format!(
1240                "a source packet's timestamp {value} cannot be moved by {origin}"
1241            ))
1242        })
1243}