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 std::path::{Path, PathBuf};
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 file.
35    pub source: &'a Path,
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: PathBuf,
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<PathBuf, 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: &Path) -> &mut SourceFacts {
342        self.sources.entry(source.to_owned()).or_default()
343    }
344
345    fn probe(&mut self, source: &Path) -> 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: &Path, 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: &Path,
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: &Path,
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    check_sampling(
599        parameters.format,
600        parameters.field_order,
601        &[ffi::AV_PIX_FMT_YUV420P, ffi::AV_PIX_FMT_NV12],
602    )?;
603    let siting =
604        crate::convert::decoded_chroma_location(parameters.codec_id, parameters.chroma_location);
605    if !same_chroma_siting(siting, encoding.chroma) {
606        return Err(format!(
607            "the source's chroma sits {siting:?}, and the output's must sit {:?}",
608            encoding.chroma
609        ));
610    }
611    Ok(())
612}
613
614/// Whether chroma sited at `source` matches `output`, reading unspecified as centred like import.
615#[must_use]
616pub fn same_chroma_siting(source: ChromaLocation, output: ChromaLocation) -> bool {
617    let centred = |location| {
618        if location == ChromaLocation::Unspecified {
619            ChromaLocation::Center
620        } else {
621            location
622        }
623    };
624    centred(source) == centred(output)
625}
626
627fn video_parameters(source: &Path, index: usize) -> Result<VideoParameters, String> {
628    let input = open(source)?;
629    let stream = input
630        .streams()
631        .get(index)
632        .ok_or_else(|| "the source's video stream is missing".to_owned())?;
633    let parameters = stream.codecpar();
634    Ok(VideoParameters {
635        codec_id: parameters.codec_id,
636        format: parameters.format,
637        field_order: parameters.field_order,
638        sample_aspect_ratio: parameters.sample_aspect_ratio,
639        extradata: alpha2_ffmpeg_bridge::codec_parameters_extradata(&parameters),
640        time_base: stream.time_base,
641        width: parameters.width,
642        height: parameters.height,
643        tags: (
644            parameters.color_primaries,
645            parameters.color_trc,
646            parameters.color_space,
647            parameters.color_range,
648        ),
649    })
650}
651
652/// The video stream's NAL framing and sample description, after the codec-parameter checks.
653fn stream_framing(
654    request: &PacketCopyRequest<'_>,
655    parameters: &VideoParameters,
656) -> Result<(usize, StreamContract), String> {
657    if parameters.codec_id != request.codec.codec_id() {
658        return Err(format!(
659            "the source's video is not {}",
660            request.codec.as_str()
661        ));
662    }
663    check_sampling(
664        parameters.format,
665        parameters.field_order,
666        &[ffi::AV_PIX_FMT_YUV420P],
667    )?;
668    check_carried_display(parameters.sample_aspect_ratio)?;
669    // A copy keeps the stream's own tags, so they must equal the output's exactly, not
670    // just read as the same color.
671    if parameters.tags != crate::convert::color_tags(request.color) {
672        return Err(format!(
673            "the source is tagged primaries {}, transfer {}, matrix {}, range {} (FFmpeg's numbers), and the output must be tagged {:?}",
674            parameters.tags.0,
675            parameters.tags.1,
676            parameters.tags.2,
677            parameters.tags.3,
678            request.color
679        ));
680    }
681    let length_size = nal_length_size(request.codec, &parameters.extradata)?;
682    Ok((
683        length_size,
684        StreamContract {
685            codec_id: parameters.codec_id,
686            width: parameters.width,
687            height: parameters.height,
688            format: parameters.format,
689            extradata: parameters.extradata.clone(),
690            time_base: (parameters.time_base.num, parameters.time_base.den),
691        },
692    ))
693}
694
695/// The source's audio stream, when it is what the export would mix.
696fn copyable_audio(
697    probed: &crate::ProbeResult,
698    audio: PacketCopyAudio,
699    container: alpha2_media::Container,
700) -> Result<usize, String> {
701    let index = probed
702        .selected_audio
703        .ok_or_else(|| "the source has no audio stream to copy".to_owned())?;
704    let stream = probed
705        .streams
706        .iter()
707        .find(|stream| stream.index == index && stream.kind == StreamKind::Audio)
708        .ok_or_else(|| "the source's audio stream is missing".to_owned())?;
709    if stream.codec != "aac" {
710        return Err(format!("the source's audio is {}, not AAC", stream.codec));
711    }
712    if !container.offers_audio(alpha2_media::AudioCodec::Aac) {
713        return Err(format!("the source's aac is not offered in {container}"));
714    }
715    if stream.sample_rate != Some(audio.sample_rate) || stream.channels != Some(audio.channels) {
716        return Err(format!(
717            "the source's audio is {:?} Hz x {:?}, not the export's {} Hz x {}",
718            stream.sample_rate, stream.channels, audio.sample_rate, audio.channels
719        ));
720    }
721    Ok(index)
722}
723
724fn open(path: &Path) -> Result<DemuxInput, String> {
725    crate::decode::open_input(path).map_err(|error| format!("cannot open the source: {error}"))
726}
727
728/// The byte width of each NAL length prefix. Only length-prefixed (MP4) streams are copied; Annex B
729/// would need its framing rewritten.
730pub(crate) fn nal_length_size(codec: NativeVideoCodec, extradata: &[u8]) -> Result<usize, String> {
731    let annex_b = || "the source's parameter sets are not in MP4 form".to_owned();
732    match codec {
733        NativeVideoCodec::H264 if extradata.len() >= 7 && extradata[0] == 1 => {
734            Ok(usize::from(extradata[4] & 0b11) + 1)
735        }
736        NativeVideoCodec::Hevc if extradata.len() >= 23 && extradata[0] == 1 => {
737            Ok(usize::from(extradata[21] & 0b11) + 1)
738        }
739        NativeVideoCodec::H264 | NativeVideoCodec::Hevc => Err(annex_b()),
740        other => Err(format!(
741            "{} is not copied; only H.264 and HEVC are",
742            other.as_str()
743        )),
744    }
745}
746
747/// Whether a length-prefixed access unit holds an IDR picture.
748pub(crate) fn is_idr(codec: NativeVideoCodec, length_size: usize, data: &[u8]) -> bool {
749    let mut at = 0_usize;
750    while at + length_size < data.len() {
751        let length = data[at..at + length_size]
752            .iter()
753            .fold(0_usize, |value, byte| (value << 8) | usize::from(*byte));
754        let Some(&header) = data.get(at + length_size) else {
755            return false;
756        };
757        let idr = match codec {
758            NativeVideoCodec::H264 => header & 0x1f == 5,
759            // IDR_W_RADL and IDR_N_LP. A CRA may be followed by pictures referring to the previous
760            // GOP, so it does not count.
761            NativeVideoCodec::Hevc => matches!((header >> 1) & 0x3f, 19 | 20),
762            _ => false,
763        };
764        if idr {
765            return true;
766        }
767        at = at.saturating_add(length_size).saturating_add(length);
768    }
769    false
770}
771
772struct Scan {
773    /// Every video packet, in decode order.
774    video: Vec<ScannedPacket>,
775    /// The span of audio packets a copy would carry, with their time base; `None` without a
776    /// timestamped audio stream.
777    audio: Option<AudioSpan>,
778}
779
780#[derive(Clone, Copy)]
781struct AudioSpan {
782    first: i64,
783    last: i64,
784    /// Where the last packet ends (latest presentation time plus duration), and that duration.
785    end: i64,
786    last_duration: i64,
787    time_base: AVRational,
788}
789
790/// Reads the source once: every packet of video stream `index` and the timestamps of audio stream
791/// `audio`. Other streams are discarded, and `cancel` is checked between packets.
792fn scan(
793    path: &Path,
794    index: usize,
795    codec: NativeVideoCodec,
796    length_size: usize,
797    audio: Option<usize>,
798    cancel: &CancelToken,
799) -> Result<Scan, String> {
800    let mut input = open(path)?;
801    crate::decode::interrupt_on_cancel(&input, cancel);
802    input.keep_only(
803        &[Some(index), audio]
804            .into_iter()
805            .flatten()
806            .collect::<Vec<_>>(),
807    );
808    let audio_time_base =
809        audio.and_then(|audio| input.streams().get(audio).map(|stream| stream.time_base));
810    let mut packets = Vec::new();
811    let mut audio_span: Option<(i64, i64, i64, i64)> = None;
812    let cancelled = || "the export was cancelled while its copy was planned".to_owned();
813    loop {
814        if cancel.is_cancelled() {
815            return Err(cancelled());
816        }
817        let packet = match input.read_packet() {
818            Ok(Some(packet)) => packet,
819            Ok(None) => break,
820            Err(_) if cancel.is_cancelled() => return Err(cancelled()),
821            Err(error) => return Err(format!("cannot read the source: {error}")),
822        };
823        // Lets a host's watchdog see the scan progressing.
824        crate::recovery::report_decode_progress();
825        let stream = usize::try_from(packet.stream_index).ok();
826        if stream.is_some() && stream == audio {
827            for time in [packet.pts, packet.dts] {
828                if time != ffi::AV_NOPTS_VALUE {
829                    let span = audio_span.get_or_insert((time, time, time, 0));
830                    span.0 = span.0.min(time);
831                    span.1 = span.1.max(time);
832                }
833            }
834            if packet.pts != ffi::AV_NOPTS_VALUE {
835                let end = packet.pts.saturating_add(packet.duration.max(0));
836                if let Some(span) = audio_span.as_mut()
837                    && end >= span.2
838                {
839                    span.2 = end;
840                    span.3 = packet.duration.max(0);
841                }
842            }
843            continue;
844        }
845        if stream != Some(index) {
846            continue;
847        }
848        if packet.pts == ffi::AV_NOPTS_VALUE {
849            return Err("a source video packet has no presentation time".to_owned());
850        }
851        let key = packet.flags & i32::try_from(ffi::AV_PKT_FLAG_KEY).unwrap_or(0) != 0;
852        packets.push(ScannedPacket {
853            pts: packet.pts,
854            dts: if packet.dts == ffi::AV_NOPTS_VALUE {
855                packet.pts
856            } else {
857                packet.dts
858            },
859            idr: key
860                && is_idr(
861                    codec,
862                    length_size,
863                    &alpha2_ffmpeg_bridge::packet_bytes(&packet),
864                ),
865            new_description: alpha2_ffmpeg_bridge::packet_has_side_data(
866                &packet,
867                ffi::AV_PKT_DATA_NEW_EXTRADATA,
868            ),
869        });
870    }
871    Ok(Scan {
872        video: packets,
873        audio: audio_span.zip(audio_time_base).map(
874            |((first, last, end, last_duration), time_base)| AudioSpan {
875                first,
876                last,
877                end,
878                last_duration,
879                time_base,
880            },
881        ),
882    })
883}
884
885/// How far outside the copied video's span copied audio may reach, in ticks: AAC priming before
886/// plus the last frame's duration after.
887const COPIED_AUDIO_SLACK: i64 = alpha2_time::TICKS_PER_SECOND;
888
889/// Whether the copied audio lands where the render's mix does: every timestamp, shifted to put
890/// the first video frame in place, within the output video give or take
891/// [`COPIED_AUDIO_SLACK`]. The shift itself is checked, since timestamps are unchecked file
892/// data (a fragment's `tfdt` is any 64-bit value).
893fn check_audio_span(
894    span: Option<AudioSpan>,
895    origin: i64,
896    video_time_base: AVRational,
897    request: &PacketCopyRequest<'_>,
898) -> Result<(), String> {
899    let Some(span) = span else {
900        return Ok(());
901    };
902    let out_of_range = || {
903        "the source's audio timestamps lie outside its video, so copying them would not play the render's mix".to_owned()
904    };
905    let output_start = request.output_start.ticks();
906    let video_ticks = request
907        .frame_times
908        .last()
909        .map_or(0, |last| last.ticks() - request.frame_times[0].ticks());
910    let earliest = output_start.saturating_sub(COPIED_AUDIO_SLACK);
911    let latest = output_start
912        .saturating_add(video_ticks)
913        .saturating_add(COPIED_AUDIO_SLACK);
914    let shift_by = av_rescale_q(
915        origin - av_rescale_q(output_start, tick_base(), video_time_base),
916        video_time_base,
917        span.time_base,
918    );
919    for time in [span.first, span.last] {
920        let moved = time.checked_sub(shift_by).ok_or_else(out_of_range)?;
921        let ticks = av_rescale_q(moved, span.time_base, tick_base());
922        if ticks == ffi::AV_NOPTS_VALUE || !(earliest..=latest).contains(&ticks) {
923            return Err(out_of_range());
924        }
925    }
926    // The mix covers exactly the range, so copied audio may overrun the last frame's end by at
927    // most its own last packet.
928    let frames = i64::try_from(request.frame_times.len()).unwrap_or(i64::MAX);
929    let frame_ticks = if frames > 1 {
930        video_ticks / (frames - 1)
931    } else {
932        0
933    };
934    let video_end = output_start
935        .saturating_add(video_ticks)
936        .saturating_add(frame_ticks);
937    let end = av_rescale_q(
938        span.end.checked_sub(shift_by).ok_or_else(out_of_range)?,
939        span.time_base,
940        tick_base(),
941    );
942    let last_packet = av_rescale_q(span.last_duration, span.time_base, tick_base());
943    if end > video_end.saturating_add(last_packet) {
944        return Err(format!(
945            "the source's audio outlasts its video by {} ms, and a render mixes only the range",
946            (end - video_end) * 1_000 / alpha2_time::TICKS_PER_SECOND
947        ));
948    }
949    Ok(())
950}
951
952/// Writes `copy`'s runs back to back into a new `container` file at `output`, with `audio`. The
953/// runs were planned for `container` ([`PacketCopyRequest::container`]).
954///
955/// The output is transactional and renamed into place only when complete. Encoded audio is
956/// written slightly ahead of the video so neither stream piles up in the muxer. `progress`
957/// receives the video packets written.
958///
959/// # Errors
960/// Returns an adapter failure for an existing output, a partial a running export holds, a read
961/// or write failure, a failed mix, audio the plan does not copy, or a cancel.
962pub fn copy_packets(
963    copy: &PacketCopy,
964    output: impl Into<crate::OutputTarget>,
965    container: alpha2_media::Container,
966    audio: CopyAudio<'_>,
967    cancel: &CancelToken,
968    progress: &mut dyn FnMut(u64),
969) -> Result<PacketCopyReport, EncodeError> {
970    let first = &copy.segments[0];
971    let input = crate::decode::open_input(&first.source).map_err(encode_adapter_error)?;
972    let video_stream = {
973        let source = &input.streams()[first.video_stream];
974        VideoStream {
975            parameters: source.codecpar().clone(),
976            time_base: source.time_base,
977            copied: true,
978        }
979    };
980    let audio_stream = match &audio {
981        CopyAudio::None => None,
982        CopyAudio::Source => {
983            if !copy.copies_audio() {
984                return Err(EncodeError::Adapter("the plan copies no audio".into()));
985            }
986            let index = first.audio_stream.unwrap_or(0);
987            let source = &input.streams()[index];
988            Some(AudioStream::Copy {
989                parameters: source.codecpar().clone(),
990                time_base: source.time_base,
991            })
992        }
993        CopyAudio::Encode { config, .. } => Some(AudioStream::Encode(*config)),
994    };
995    drop(input);
996    let copied_audio = matches!(audio, CopyAudio::Source);
997    let mut writer = RunWriter {
998        muxer: Muxer::open_streams(output, container, video_stream, audio_stream)?,
999        mix: match audio {
1000            CopyAudio::Encode { feed, .. } => Some(MixWriter {
1001                feed,
1002                covered: 0,
1003                done: false,
1004            }),
1005            CopyAudio::None | CopyAudio::Source => None,
1006        },
1007        stages: crate::EncodeStageTimings::default(),
1008        report: PacketCopyReport::default(),
1009    };
1010    for segment in &copy.segments {
1011        writer.write_run(segment, copied_audio, cancel, progress)?;
1012    }
1013    if writer.report.video_packets != copy.video_packets() {
1014        return Err(EncodeError::Adapter(format!(
1015            "the copy wrote {} video packets of the planned {}",
1016            writer.report.video_packets,
1017            copy.video_packets()
1018        )));
1019    }
1020    let RunWriter {
1021        mut muxer,
1022        mut mix,
1023        mut stages,
1024        mut report,
1025    } = writer;
1026    if let Some(mix) = mix.as_mut() {
1027        mix.write_until(i64::MAX, &mut muxer, &mut stages, &mut report)?;
1028    }
1029    muxer.finish_audio()?;
1030    muxer.write_ready_audio(true, &mut stages)?;
1031    muxer.close(cancel)?;
1032    report.publish = muxer.publish_report();
1033    Ok(report)
1034}
1035
1036/// The output a copy writes its runs into, and the mix it interleaves.
1037struct RunWriter<'a> {
1038    muxer: Muxer,
1039    mix: Option<MixWriter<'a>>,
1040    stages: crate::EncodeStageTimings,
1041    report: PacketCopyReport,
1042}
1043
1044impl RunWriter<'_> {
1045    /// Copies one run's packets, plus its source's audio when `copied_audio` (whole file only).
1046    fn write_run(
1047        &mut self,
1048        run: &PacketCopyPlan,
1049        copied_audio: bool,
1050        cancel: &CancelToken,
1051        progress: &mut dyn FnMut(u64),
1052    ) -> Result<(), EncodeError> {
1053        let mut input = crate::decode::open_input(&run.source).map_err(encode_adapter_error)?;
1054        crate::decode::interrupt_on_cancel(&input, cancel);
1055        let audio_stream = copied_audio.then_some(run.audio_stream).flatten();
1056        input.keep_only(
1057            &[Some(run.video_stream), audio_stream]
1058                .into_iter()
1059                .flatten()
1060                .collect::<Vec<_>>(),
1061        );
1062        let shift_by = run.origin - run.offset;
1063        // Later runs seek to their first packet (an indexed IDR). Copied audio only travels with a
1064        // whole file, which starts at packet zero.
1065        let mut video_position = if run.first_packet > 0 {
1066            let stream = i32::try_from(run.video_stream)
1067                .map_err(|_| EncodeError::Adapter("video stream index is out of range".into()))?;
1068            input
1069                .seek(
1070                    stream,
1071                    run.first_timestamps.1,
1072                    i32::try_from(ffi::AVSEEK_FLAG_BACKWARD).unwrap_or(0),
1073                )
1074                .map_err(|error| {
1075                    if cancel.is_cancelled() {
1076                        EncodeError::Cancelled
1077                    } else {
1078                        encode_adapter_error_at("seeking to the run", error)
1079                    }
1080                })?;
1081            None
1082        } else {
1083            Some(0_u64)
1084        };
1085        while let Some(mut packet) = input.read_packet().map_err(|error| {
1086            if cancel.is_cancelled() {
1087                EncodeError::Cancelled
1088            } else {
1089                encode_adapter_error(error)
1090            }
1091        })? {
1092            if cancel.is_cancelled() {
1093                return Err(EncodeError::Cancelled);
1094            }
1095            let stream = usize::try_from(packet.stream_index).ok();
1096            if stream == Some(run.video_stream) {
1097                let position = match video_position {
1098                    Some(position) => position,
1099                    None if (packet.pts, packet.dts) == run.first_timestamps => run.first_packet,
1100                    None => continue,
1101                };
1102                video_position = Some(position + 1);
1103                if position < run.first_packet {
1104                    continue;
1105                }
1106                if position > run.last_packet {
1107                    // Copied audio only travels with the whole video.
1108                    break;
1109                }
1110                packet.set_pts(shift(packet.pts, shift_by)?);
1111                packet.set_dts(shift(packet.dts, shift_by)?);
1112                packet.set_pos(-1);
1113                if let Some(mix) = self.mix.as_mut() {
1114                    let at = av_rescale_q(packet.dts, run.video_time_base, tick_base());
1115                    mix.write_until(
1116                        at.saturating_add(MIX_LEAD),
1117                        &mut self.muxer,
1118                        &mut self.stages,
1119                        &mut self.report,
1120                    )?;
1121                }
1122                self.report.bytes = self
1123                    .report
1124                    .bytes
1125                    .saturating_add(u64::try_from(packet.size).unwrap_or(0));
1126                self.muxer.write_video(&mut packet, run.video_time_base)?;
1127                self.report.video_packets += 1;
1128                progress(self.report.video_packets);
1129            } else if stream.is_some() && stream == audio_stream {
1130                let source_base = input.streams()[run.audio_stream.unwrap_or(0)].time_base;
1131                // The same zero as the video's; audio keeps its own offset from it, priming
1132                // included.
1133                let origin = av_rescale_q(shift_by, run.video_time_base, source_base);
1134                packet.set_pts(shift(packet.pts, origin)?);
1135                packet.set_dts(shift(packet.dts, origin)?);
1136                packet.set_pos(-1);
1137                self.report.bytes = self
1138                    .report
1139                    .bytes
1140                    .saturating_add(u64::try_from(packet.size).unwrap_or(0));
1141                self.muxer.write_copied_audio(&mut packet)?;
1142                self.report.audio_packets += 1;
1143            }
1144        }
1145        Ok(())
1146    }
1147}
1148
1149/// How far ahead of the video the encoded mix is written, so the muxer always has audio to
1150/// interleave without either stream piling up.
1151const MIX_LEAD: i64 = alpha2_time::TICKS_PER_SECOND / 10;
1152
1153/// The export's mix, written into the muxer as the video advances.
1154struct MixWriter<'a> {
1155    feed: &'a mut dyn AudioBlockFeed,
1156    /// Output time the mix written so far reaches, in ticks.
1157    covered: i64,
1158    done: bool,
1159}
1160
1161impl MixWriter<'_> {
1162    /// Writes blocks until the mix reaches `target`, or ends.
1163    fn write_until(
1164        &mut self,
1165        target: i64,
1166        muxer: &mut Muxer,
1167        stages: &mut crate::EncodeStageTimings,
1168        report: &mut PacketCopyReport,
1169    ) -> Result<(), EncodeError> {
1170        while !self.done && self.covered < target {
1171            let Some(block) = self.feed.next_block().map_err(EncodeError::Adapter)? else {
1172                self.done = true;
1173                break;
1174            };
1175            let frames = block.channels.first().map_or(0, Vec::len);
1176            muxer.write_audio(&block, stages)?;
1177            report.encoded_audio_frames = report
1178                .encoded_audio_frames
1179                .saturating_add(u64::try_from(frames).unwrap_or(u64::MAX));
1180            self.covered = i64::try_from(report.encoded_audio_frames)
1181                .unwrap_or(i64::MAX)
1182                .saturating_mul(alpha2_time::TICKS_PER_SECOND)
1183                .div_euclid(i64::from(block.sample_rate.max(1)));
1184        }
1185        Ok(())
1186    }
1187}
1188
1189/// `value` moved back by `origin`, keeping a missing timestamp missing and refusing overflow.
1190fn shift(value: i64, origin: i64) -> Result<i64, EncodeError> {
1191    if value == ffi::AV_NOPTS_VALUE {
1192        return Ok(value);
1193    }
1194    value
1195        .checked_sub(origin)
1196        .filter(|moved| *moved != ffi::AV_NOPTS_VALUE)
1197        .ok_or_else(|| {
1198            EncodeError::Adapter(format!(
1199                "a source packet's timestamp {value} cannot be moved by {origin}"
1200            ))
1201        })
1202}