alpha2-engine 0.5.1

Player and exporter facade for alpha2.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
use alpha2_eval::FrameNeed;
use alpha2_media::{PixelLayout, SourceId, VideoCodec, YuvEncoding};
use alpha2_render::{FrameSubmitTimings, Renderer, Yuv420pReadback, Yuv420pTargets};
use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND, TimeRange};
use std::time::Duration;
use web_time::Instant;

use crate::schedule::frame_times;
use crate::{
    EngineError, EngineProject, FrameProvider, FrameRenderer, GpuFrameRenderer, MissingFramePolicy,
    QualityProfile,
};

/// Largest frame schedule accepted by one export operation.
pub const MAX_EXPORT_FRAMES: u64 = 10_000_000;
const MAX_PREFETCH_FRAMES: u32 = 120;

/// Decode requirements for one scheduled export frame.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExportFrameNeeds {
    /// Zero-based frame position inside the export operation.
    pub index: u64,
    /// Exact rational frame timestamp on the project timeline.
    pub time: MediaTime,
    /// Deduplicated source frames required before rendering this timestamp.
    pub needs: Vec<FrameNeed>,
}

/// Completed and total frame counts for deterministic export.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ExportProgress {
    /// Successfully rendered frames.
    pub completed: u64,
    /// Frame intervals that intersect the export range.
    pub total: u64,
}

impl ExportProgress {
    /// Completion ratio in the inclusive range zero to one.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn fraction(self) -> f64 {
        if self.total == 0 {
            1.0
        } else {
            self.completed as f64 / self.total as f64
        }
    }
}

/// Outcome of one non-blocking exporter step.
#[derive(Debug)]
// Almost every step renders a frame, so boxing the readback would allocate once per frame.
#[allow(clippy::large_enum_variant)]
pub enum ExportStep {
    /// Required decoded frames are not available; retry without advancing.
    Waiting {
        /// Timeline timestamp that remains pending.
        time: MediaTime,
        /// Sources the host must provide before retrying.
        missing_sources: Vec<SourceId>,
    },
    /// One frame was rendered and the cursor advanced exactly once.
    Rendered {
        /// Zero-based position inside this export operation.
        index: u64,
        /// Exact rational-frame timestamp.
        time: MediaTime,
        /// Submitted planar YUV420 readback for the encoder.
        readback: Yuv420pReadback,
    },
    /// Every scheduled frame has been produced.
    Complete,
}

/// One step of an export that leaves its picture as a rendered texture.
#[derive(Debug)]
pub enum ExportTextureStep<I = alpha2_render::RenderedTexture> {
    /// Required decoded frames are not available; retry without advancing.
    Waiting {
        /// Timeline timestamp that remains pending.
        time: MediaTime,
        /// Sources the host must provide before retrying.
        missing_sources: Vec<SourceId>,
    },
    /// One frame was rendered and the cursor advanced exactly once.
    Rendered {
        /// Zero-based position inside this export operation.
        index: u64,
        /// Exact rational-frame timestamp.
        time: MediaTime,
        /// The frame at export quality: a submitted texture in the intermediate format on the GPU,
        /// an image on the CPU.
        texture: I,
    },
    /// Every scheduled frame has been produced.
    Complete,
}

/// One step of an export that packs its picture straight into caller-owned planes.
#[derive(Debug)]
pub enum ExportPlaneStep {
    /// Required decoded frames are not available; retry without advancing.
    Waiting {
        /// Timeline timestamp that remains pending.
        time: MediaTime,
        /// Sources the host must provide before retrying.
        missing_sources: Vec<SourceId>,
    },
    /// One frame was packed into the caller's planes and the cursor advanced.
    Rendered {
        /// Zero-based position inside this export operation.
        index: u64,
        /// Exact rational-frame timestamp.
        time: MediaTime,
    },
    /// Every scheduled frame has been produced.
    Complete,
}

/// Where one [`Exporter::render_next_timed`] step spent its time.
///
/// Splits `frameSubmitMs` (evaluation, graph construction and submission) so a regression can
/// be attributed.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct ExportStepTimings {
    /// Evaluating the timeline at this frame's timestamp.
    pub evaluate: Duration,
    /// Applying the quality profile, which also trims the texture pool to its budget.
    pub prepare: Duration,
    /// Everything the renderer did with the evaluated frame.
    pub submit: FrameSubmitTimings,
}

impl ExportStepTimings {
    /// Adds another step's spans to these, saturating on overflow.
    #[must_use]
    pub fn merged(self, other: Self) -> Self {
        Self {
            evaluate: self.evaluate.saturating_add(other.evaluate),
            prepare: self.prepare.saturating_add(other.prepare),
            submit: self.submit.merged(other.submit),
        }
    }
}

/// Deterministic, retryable frame-sequence runner.
#[derive(Clone, Debug)]
pub struct Exporter {
    /// The [`EngineProject::generation`] it renders.
    snapshot: u64,
    quality: QualityProfile,
    encoding: YuvEncoding,
    pixels: PixelLayout,
    /// Whether frames draw the project background (ignored when the layout keeps alpha).
    background: bool,
    frame_rate: FrameRate,
    effective_range: TimeRange,
    next_frame: i64,
    end_frame: i64,
    completed: u64,
    total: u64,
}

impl Exporter {
    /// Creates an exporter for frame intervals intersecting a half-open timeline range.
    ///
    /// All refusals happen here, before a host opens an encoder: 4:2:0 output at `quality` must
    /// have even dimensions, and frames are packed per [`YuvEncoding::export`] for `codec`.
    /// Later steps refuse any other snapshot with [`EngineError::ExportProjectChanged`].
    ///
    /// # Errors
    /// Returns an error for an empty range, invalid quality, timeline overflow,
    /// or [`EngineError::OddExportDimensions`].
    pub fn new(
        snapshot: &EngineProject,
        range: TimeRange,
        frame_rate: FrameRate,
        quality: QualityProfile,
        codec: VideoCodec,
    ) -> Result<Self, EngineError> {
        quality.export_size(&snapshot.project().settings)?;
        Self::over(
            snapshot,
            range,
            frame_rate,
            quality,
            YuvEncoding::export(codec),
        )
    }

    /// An exporter of the single `frame_rate` frame containing `time`, for hosts that take the
    /// picture via [`Self::render_next_texture`] rather than 4:2:0, so odd sizes are allowed.
    ///
    /// # Errors
    /// Returns an error for invalid quality or a time past the timeline.
    pub fn still(
        snapshot: &EngineProject,
        time: MediaTime,
        frame_rate: FrameRate,
        quality: QualityProfile,
    ) -> Result<Self, EngineError> {
        quality.render_size(&snapshot.project().settings)?;
        let range = TimeRange::new(
            time,
            MediaTime::from_ticks(time.ticks().checked_add(1).ok_or(EngineError::OutOfRange)?),
        )
        .map_err(|_| EngineError::OutOfRange)?;
        Self::over(
            snapshot,
            range,
            frame_rate,
            quality,
            YuvEncoding::export(VideoCodec::H264),
        )
    }

    fn over(
        snapshot: &EngineProject,
        range: TimeRange,
        frame_rate: FrameRate,
        quality: QualityProfile,
        encoding: YuvEncoding,
    ) -> Result<Self, EngineError> {
        if range.is_empty() {
            return Err(EngineError::EmptyExportRange);
        }
        let next_frame = frame_rate
            .frame_at_or_before(range.start())
            .ok_or(EngineError::OutOfRange)?;
        let end_frame = first_frame_at_or_after(frame_rate, range.end())?;
        let count = end_frame
            .checked_sub(next_frame)
            .ok_or(EngineError::OutOfRange)?;
        let total = u64::try_from(count).map_err(|_| EngineError::OutOfRange)?;
        if total == 0 {
            return Err(EngineError::EmptyExportRange);
        }
        if total > MAX_EXPORT_FRAMES {
            return Err(EngineError::ExportTooLarge {
                frames: total,
                maximum: MAX_EXPORT_FRAMES,
            });
        }
        let effective_range = TimeRange::new(
            frame_rate
                .frame_start(next_frame)
                .ok_or(EngineError::OutOfRange)?,
            frame_rate
                .frame_start(end_frame)
                .ok_or(EngineError::OutOfRange)?,
        )
        .map_err(|_| EngineError::OutOfRange)?;
        Ok(Self {
            snapshot: snapshot.generation(),
            quality,
            encoding,
            pixels: PixelLayout::YUV420P,
            background: true,
            frame_rate,
            effective_range,
            next_frame,
            end_frame,
            completed: 0,
            total,
        })
    }

    /// How this export's frames are packed into 4:2:0 YUV.
    #[must_use]
    pub const fn encoding(&self) -> YuvEncoding {
        self.encoding
    }

    /// This exporter writing `pixels` ([`alpha2_media::resolve_pixels`]) instead of 8-bit 4:2:0.
    /// A layout with alpha drops the project background. The even-size rule of [`Self::new`]
    /// still applies, 4:4:4 included.
    #[must_use]
    pub const fn with_pixels(mut self, pixels: PixelLayout) -> Self {
        self.pixels = pixels;
        self
    }

    /// The layout this export's frames are packed in.
    #[must_use]
    pub const fn pixels(&self) -> PixelLayout {
        self.pixels
    }

    /// This exporter with the project background drawn or, if `drawn` is false, replaced by
    /// transparent black (for example a still taken via [`Self::render_next_texture`]).
    #[must_use]
    pub const fn with_background(mut self, drawn: bool) -> Self {
        self.background = drawn;
        self
    }

    fn evaluate<'a>(
        &self,
        project: &'a EngineProject,
        time: MediaTime,
    ) -> Result<alpha2_eval::FrameDesc<'a>, EngineError> {
        let mut frame = project.evaluate(time)?;
        if self.pixels.alpha || !self.background {
            frame.background = None;
        }
        Ok(frame)
    }

    /// The timeline range this export covers: the requested range widened to
    /// the frame grid, `[floor(start), ceil(end))`.
    ///
    /// The first frame may start up to one frame before the request. Its start is the output's
    /// zero, so hosts place audio and report the export from this range.
    #[must_use]
    pub const fn effective_range(&self) -> TimeRange {
        self.effective_range
    }

    /// The [`export_audio_window`] of [`Self::effective_range`] at `sample_rate`.
    ///
    /// # Errors
    /// Returns [`EngineError::OutOfRange`] when the range does not fit in
    /// memory-addressable samples.
    pub fn audio_window(&self, sample_rate: u32) -> Result<ExportAudioWindow, EngineError> {
        export_audio_window(self.effective_range, sample_rate)
    }

    /// Creates an exporter over [`EngineProject::timeline_range`], packed for `codec`.
    ///
    /// # Errors
    /// Returns an error for an empty project or invalid schedule.
    pub fn for_project(
        project: &EngineProject,
        quality: QualityProfile,
        codec: VideoCodec,
    ) -> Result<Self, EngineError> {
        let range = project
            .timeline_range()
            .ok_or(EngineError::EmptyExportRange)?;
        Self::new(
            project,
            range,
            project.project().settings.frame_rate,
            quality,
            codec,
        )
    }

    /// The only policy an export can apply.
    ///
    /// Export output must not depend on decode timing: pipelined and synchronous exports are
    /// byte-identical. Repeating a late frame would break that, so this is a constant.
    /// [`Player`] can choose differently because real-time playback has no such guarantee.
    ///
    /// [`Player`]: crate::Player
    pub const MISSING_FRAME_POLICY: MissingFramePolicy = MissingFramePolicy::Wait;

    /// Returns the policy used when source frames are unavailable.
    #[must_use]
    pub const fn missing_frame_policy(&self) -> MissingFramePolicy {
        Self::MISSING_FRAME_POLICY
    }

    /// Returns current deterministic export progress.
    #[must_use]
    pub const fn progress(&self) -> ExportProgress {
        ExportProgress {
            completed: self.completed,
            total: self.total,
        }
    }

    /// The size frames of `project` render at, for preparing captions.
    ///
    /// # Errors
    /// Returns an error when the quality profile cannot size the project.
    pub fn render_size(
        &self,
        project: &EngineProject,
    ) -> Result<alpha2_render::RenderSize, EngineError> {
        self.quality.render_size(&project.project().settings)
    }

    fn check(&self, project: &EngineProject) -> Result<(), EngineError> {
        if project.generation() == self.snapshot {
            Ok(())
        } else {
            Err(EngineError::ExportProjectChanged)
        }
    }

    /// Returns the pending frame timestamp, or `None` after completion.
    #[must_use]
    pub fn pending_time(&self) -> Option<MediaTime> {
        (self.next_frame < self.end_frame)
            .then(|| self.frame_rate.frame_start(self.next_frame))
            .flatten()
    }

    /// Skips rendering the pending frame (supplied elsewhere, such as an earlier bake) and
    /// advances the cursor as a render would. Returns its index and time, or `None` when done.
    ///
    /// # Errors
    /// Returns [`EngineError::OutOfRange`] if the cursor would overflow.
    pub fn take_next(&mut self) -> Result<Option<(u64, MediaTime)>, EngineError> {
        let Some(time) = self.pending_time() else {
            return Ok(None);
        };
        let index = self.completed;
        self.next_frame = self
            .next_frame
            .checked_add(1)
            .ok_or(EngineError::OutOfRange)?;
        self.completed += 1;
        Ok(Some((index, time)))
    }

    /// The frame grid the export renders on.
    #[must_use]
    pub const fn frame_rate(&self) -> FrameRate {
        self.frame_rate
    }

    /// The times of the pending frame and up to `frames - 1` after it, without moving the
    /// cursor. `frames` is clamped as in [`Self::prefetch_needs`].
    ///
    /// # Errors
    /// Returns [`EngineError::OutOfRange`] if a time overflows.
    pub fn upcoming_times(&self, frames: u32) -> Result<Vec<MediaTime>, EngineError> {
        Ok(frame_times(
            self.frame_rate,
            self.next_frame,
            frames.min(MAX_PREFETCH_FRAMES),
            Some(self.end_frame),
        )?
        .into_iter()
        .map(|(_, time)| time)
        .collect())
    }

    /// Returns decode requirements for the pending frame and bounded lookahead.
    ///
    /// The cursor is not changed. `frames` counts the current frame and is clamped to 120.
    ///
    /// # Errors
    /// Returns evaluation or timeline overflow errors, and
    /// [`EngineError::ExportProjectChanged`] for another snapshot.
    pub fn prefetch_needs(
        &self,
        project: &EngineProject,
        frames: u32,
    ) -> Result<Vec<ExportFrameNeeds>, EngineError> {
        self.check(project)?;
        let count = frames.min(MAX_PREFETCH_FRAMES);
        let times = frame_times(
            self.frame_rate,
            self.next_frame,
            count,
            Some(self.end_frame),
        )?;
        times
            .into_iter()
            .enumerate()
            .map(|(offset, (_, time))| {
                let offset = u64::try_from(offset).map_err(|_| EngineError::OutOfRange)?;
                let index = self
                    .completed
                    .checked_add(offset)
                    .ok_or(EngineError::OutOfRange)?;
                Ok(ExportFrameNeeds {
                    index,
                    time,
                    needs: project.frame_needs(time)?,
                })
            })
            .collect()
    }

    /// Attempts one frame without blocking on host decode.
    ///
    /// Waiting does not change progress. A successful render advances the
    /// exact rational frame cursor once, so retries cannot skip timestamps.
    ///
    /// # Errors
    /// Returns timeline evaluation, quality, or rendering failures, and
    /// [`EngineError::ExportProjectChanged`] for another snapshot.
    pub fn render_next(
        &mut self,
        project: &EngineProject,
        renderer: &Renderer,
        frames: &dyn FrameProvider,
    ) -> Result<ExportStep, EngineError> {
        self.render_next_measured(project, renderer, frames, None)
    }

    /// Attempts one frame and reports where the step spent its time.
    ///
    /// Renders exactly what [`Exporter::render_next`] does. A waiting step records only the
    /// stages that ran.
    ///
    /// # Errors
    /// Returns timeline evaluation, quality, or rendering failures, and
    /// [`EngineError::ExportProjectChanged`] for another snapshot.
    pub fn render_next_timed(
        &mut self,
        project: &EngineProject,
        renderer: &Renderer,
        frames: &dyn FrameProvider,
        timings: &mut ExportStepTimings,
    ) -> Result<ExportStep, EngineError> {
        self.render_next_measured(project, renderer, frames, Some(timings))
    }

    /// Renders the next frame straight into caller-owned NV12 plane textures.
    ///
    /// Readback-free counterpart of [`Self::render_next_timed`] with identical cursor
    /// accounting.
    ///
    /// # Errors
    /// Returns an engine error when evaluation or rendering fails, and
    /// [`EngineError::ExportProjectChanged`] for another snapshot.
    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
    pub fn render_next_nv12_timed(
        &mut self,
        project: &EngineProject,
        renderer: &Renderer,
        frames: &dyn FrameProvider,
        planes: alpha2_render::Nv12PlaneTargets<'_>,
        timings: &mut ExportStepTimings,
    ) -> Result<ExportPlaneStep, EngineError> {
        self.check(project)?;
        let Some(time) = self.pending_time() else {
            return Ok(ExportPlaneStep::Complete);
        };
        let evaluate_started = Instant::now();
        let frame = self.evaluate(project, time)?;
        crate::frame::check_frame_effects(renderer, &frame)?;
        let prepare_started = Instant::now();
        let evaluate = prepare_started.duration_since(evaluate_started);
        let size = self.quality.render_size(&project.project().settings)?;
        renderer.set_texture_budget_bytes(self.quality.texture_budget_bytes);
        renderer.set_quality_controls(
            self.quality.max_filter_samples,
            self.quality.motion_blur_subframes,
        );
        let prepare = prepare_started.elapsed();
        let mut submit = FrameSubmitTimings::default();
        let attempt = renderer.render_frame_nv12_timed(
            size,
            &frame,
            frames,
            planes,
            self.encoding,
            &mut submit,
        )?;
        *timings = ExportStepTimings {
            evaluate,
            prepare,
            submit,
        };
        if !attempt.submitted {
            return Ok(ExportPlaneStep::Waiting {
                time,
                missing_sources: attempt.report.missing_sources,
            });
        }
        let index = self.completed;
        self.next_frame = self
            .next_frame
            .checked_add(1)
            .ok_or(EngineError::OutOfRange)?;
        self.completed += 1;
        Ok(ExportPlaneStep::Rendered { index, time })
    }

    /// Renders the next frame straight into caller-owned YUV420 planes on either renderer.
    ///
    /// The cursor advances as for [`Self::render_next`]; a waiting step writes nothing.
    /// `timings` records the whole draw as its submit span.
    ///
    /// # Errors
    /// Returns an engine error when evaluation or rendering fails, and
    /// [`EngineError::ExportProjectChanged`] for another snapshot.
    pub fn render_next_into_yuv420p<R: FrameRenderer + ?Sized>(
        &mut self,
        project: &EngineProject,
        renderer: &R,
        frames: &dyn FrameProvider,
        targets: &mut Yuv420pTargets<'_>,
        timings: Option<&mut ExportStepTimings>,
    ) -> Result<ExportPlaneStep, EngineError> {
        self.check(project)?;
        let Some(time) = self.pending_time() else {
            return Ok(ExportPlaneStep::Complete);
        };
        let evaluate_started = Instant::now();
        let frame = self.evaluate(project, time)?;
        crate::frame::check_frame_effects(renderer, &frame)?;
        let prepare_started = Instant::now();
        let evaluate = prepare_started.duration_since(evaluate_started);
        let size = self.quality.render_size(&project.project().settings)?;
        renderer.set_texture_budget_bytes(self.quality.texture_budget_bytes);
        renderer.set_quality_controls(
            self.quality.max_filter_samples,
            self.quality.motion_blur_subframes,
        );
        let draw_started = Instant::now();
        let prepare = draw_started.duration_since(prepare_started);
        let report =
            renderer.render_frame_into_yuv420p(size, &frame, frames, self.encoding, targets)?;
        if let Some(timings) = timings {
            *timings = ExportStepTimings {
                evaluate,
                prepare,
                submit: FrameSubmitTimings {
                    command_encode: draw_started.elapsed(),
                    ..FrameSubmitTimings::default()
                },
            };
        }
        if !report.is_complete() {
            return Ok(ExportPlaneStep::Waiting {
                time,
                missing_sources: report.missing_sources,
            });
        }
        let index = self.completed;
        self.next_frame = self
            .next_frame
            .checked_add(1)
            .ok_or(EngineError::OutOfRange)?;
        self.completed += 1;
        Ok(ExportPlaneStep::Rendered { index, time })
    }

    /// [`Self::render_next_into_yuv420p`] for this export's layout ([`Self::pixels`]), one buffer
    /// per plane in [`PixelLayout::planes`] order.
    ///
    /// # Errors
    /// As [`Self::render_next_into_yuv420p`].
    pub fn render_next_into_planes<R: FrameRenderer + ?Sized>(
        &mut self,
        project: &EngineProject,
        renderer: &R,
        frames: &dyn FrameProvider,
        targets: &mut [alpha2_render::PlaneTarget<'_>],
        timings: Option<&mut ExportStepTimings>,
    ) -> Result<ExportPlaneStep, EngineError> {
        if self.pixels.is_yuv420p() {
            let [y, u, v] = targets else {
                return Err(EngineError::Render(
                    alpha2_render::RenderError::TextureReadback(
                        alpha2_render::ReadbackFailure::Layout,
                    ),
                ));
            };
            let mut planes = Yuv420pTargets {
                y: y.reborrow(),
                u: u.reborrow(),
                v: v.reborrow(),
            };
            return self.render_next_into_yuv420p(project, renderer, frames, &mut planes, timings);
        }
        self.check(project)?;
        let Some(time) = self.pending_time() else {
            return Ok(ExportPlaneStep::Complete);
        };
        let evaluate_started = Instant::now();
        let frame = self.evaluate(project, time)?;
        crate::frame::check_frame_effects(renderer, &frame)?;
        let prepare_started = Instant::now();
        let evaluate = prepare_started.duration_since(evaluate_started);
        let size = self.quality.render_size(&project.project().settings)?;
        renderer.set_texture_budget_bytes(self.quality.texture_budget_bytes);
        renderer.set_quality_controls(
            self.quality.max_filter_samples,
            self.quality.motion_blur_subframes,
        );
        let draw_started = Instant::now();
        let prepare = draw_started.duration_since(prepare_started);
        let report = renderer.render_frame_into_planes(
            size,
            &frame,
            frames,
            self.encoding,
            self.pixels,
            targets,
        )?;
        if let Some(timings) = timings {
            *timings = ExportStepTimings {
                evaluate,
                prepare,
                submit: FrameSubmitTimings {
                    command_encode: draw_started.elapsed(),
                    ..FrameSubmitTimings::default()
                },
            };
        }
        if !report.is_complete() {
            return Ok(ExportPlaneStep::Waiting {
                time,
                missing_sources: report.missing_sources,
            });
        }
        let index = self.completed;
        self.next_frame = self
            .next_frame
            .checked_add(1)
            .ok_or(EngineError::OutOfRange)?;
        self.completed += 1;
        Ok(ExportPlaneStep::Rendered { index, time })
    }

    /// Renders the next frame and hands over its texture without readback or packing.
    ///
    /// The cursor advances exactly as it does for [`Self::render_next`].
    ///
    /// # Errors
    /// Returns an engine error when evaluation or rendering fails, and
    /// [`EngineError::ExportProjectChanged`] for another snapshot.
    pub fn render_next_texture<R: crate::FrameRenderer + ?Sized>(
        &mut self,
        project: &EngineProject,
        renderer: &R,
        frames: &dyn FrameProvider,
    ) -> Result<ExportTextureStep<R::Image>, EngineError> {
        self.check(project)?;
        let Some(time) = self.pending_time() else {
            return Ok(ExportTextureStep::Complete);
        };
        let frame = self.evaluate(project, time)?;
        crate::frame::check_frame_effects(renderer, &frame)?;
        let size = self.quality.render_size(&project.project().settings)?;
        renderer.set_texture_budget_bytes(self.quality.texture_budget_bytes);
        renderer.set_quality_controls(
            self.quality.max_filter_samples,
            self.quality.motion_blur_subframes,
        );
        let render = crate::FrameRenderer::render_frame(renderer, size, &frame, frames)?;
        let Some(texture) = render.texture else {
            return Ok(ExportTextureStep::Waiting {
                time,
                missing_sources: render.report.missing_sources,
            });
        };
        let index = self.completed;
        self.next_frame = self
            .next_frame
            .checked_add(1)
            .ok_or(EngineError::OutOfRange)?;
        self.completed += 1;
        Ok(ExportTextureStep::Rendered {
            index,
            time,
            texture,
        })
    }

    fn render_next_measured(
        &mut self,
        project: &EngineProject,
        renderer: &Renderer,
        frames: &dyn FrameProvider,
        timings: Option<&mut ExportStepTimings>,
    ) -> Result<ExportStep, EngineError> {
        self.check(project)?;
        let Some(time) = self.pending_time() else {
            return Ok(ExportStep::Complete);
        };
        let evaluate_started = timings.as_ref().map(|_| Instant::now());
        let frame = self.evaluate(project, time)?;
        crate::frame::check_frame_effects(renderer, &frame)?;
        let prepare_started = evaluate_started.map(|_| Instant::now());
        let evaluate = evaluate_started
            .zip(prepare_started)
            .map_or(Duration::ZERO, |(started, ended)| {
                ended.duration_since(started)
            });
        let size = self.quality.render_size(&project.project().settings)?;
        renderer.set_texture_budget_bytes(self.quality.texture_budget_bytes);
        renderer.set_quality_controls(
            self.quality.max_filter_samples,
            self.quality.motion_blur_subframes,
        );
        let prepare = prepare_started.map_or(Duration::ZERO, |started| started.elapsed());
        if !self.pixels.is_yuv420p() {
            // Read back as stored and pack on the CPU once the readback finishes.
            let submit_started = Instant::now();
            let render = crate::FrameRenderer::render_frame(renderer, size, &frame, frames)?;
            let Some(texture) = render.texture else {
                return Ok(ExportStep::Waiting {
                    time,
                    missing_sources: render.report.missing_sources,
                });
            };
            let readback = renderer.begin_layout_readback(&texture, self.encoding, self.pixels)?;
            if let Some(timings) = timings {
                *timings = ExportStepTimings {
                    evaluate,
                    prepare,
                    submit: FrameSubmitTimings {
                        command_encode: submit_started.elapsed(),
                        ..FrameSubmitTimings::default()
                    },
                };
            }
            return self.rendered(time, readback);
        }
        let attempt = match timings {
            Some(timings) => {
                let mut submit = FrameSubmitTimings::default();
                let attempt = renderer.render_frame_yuv420p_timed(
                    size,
                    &frame,
                    frames,
                    self.encoding,
                    &mut submit,
                )?;
                *timings = ExportStepTimings {
                    evaluate,
                    prepare,
                    submit,
                };
                attempt
            }
            None => renderer.render_frame_yuv420p(size, &frame, frames, self.encoding)?,
        };
        let Some(readback) = attempt.readback else {
            return Ok(ExportStep::Waiting {
                time,
                missing_sources: attempt.report.missing_sources,
            });
        };
        self.rendered(time, readback)
    }

    /// Advances past the frame at `time`, whose `readback` was submitted.
    fn rendered(
        &mut self,
        time: MediaTime,
        readback: alpha2_render::Yuv420pReadback,
    ) -> Result<ExportStep, EngineError> {
        let index = self.completed;
        self.next_frame = self
            .next_frame
            .checked_add(1)
            .ok_or(EngineError::OutOfRange)?;
        self.completed += 1;
        Ok(ExportStep::Rendered {
            index,
            time,
            readback,
        })
    }
}

/// The project-rate samples an export's audio covers.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ExportAudioWindow {
    /// First sample, at the project sample rate.
    pub start_sample: i64,
    /// Sample count.
    pub frames: usize,
}

/// The audio samples an export over `range` writes: each end is the nearest sample, halves
/// rounding up.
///
/// Every host places export audio through this from [`Exporter::effective_range`], so audio
/// stays within half a sample of the video on every output path.
///
/// # Errors
/// Returns [`EngineError::OutOfRange`] when the range does not fit in
/// memory-addressable samples.
pub fn export_audio_window(
    range: TimeRange,
    sample_rate: u32,
) -> Result<ExportAudioWindow, EngineError> {
    let nearest = |ticks: i64| {
        let doubled =
            i128::from(ticks) * i128::from(sample_rate) * 2 + i128::from(TICKS_PER_SECOND);
        i64::try_from(doubled.div_euclid(i128::from(TICKS_PER_SECOND) * 2))
            .map_err(|_| EngineError::OutOfRange)
    };
    let start_sample = nearest(range.start().ticks())?;
    let end = nearest(range.end().ticks())?;
    let frames = end
        .checked_sub(start_sample)
        .and_then(|frames| usize::try_from(frames).ok())
        .ok_or(EngineError::OutOfRange)?;
    Ok(ExportAudioWindow {
        start_sample,
        frames,
    })
}

fn first_frame_at_or_after(rate: FrameRate, time: MediaTime) -> Result<i64, EngineError> {
    let floor = rate
        .frame_at_or_before(time)
        .ok_or(EngineError::OutOfRange)?;
    let floor_time = rate.frame_start(floor).ok_or(EngineError::OutOfRange)?;
    if floor_time < time {
        floor.checked_add(1).ok_or(EngineError::OutOfRange)
    } else {
        Ok(floor)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Player;
    use alpha2_model::{Project, ProjectId, ProjectSettings};

    fn snapshot(width: u32, height: u32) -> EngineProject {
        EngineProject::new(Project::new(
            ProjectId::new("export".to_owned()).expect("id"),
            "export",
            ProjectSettings::new(width, height, FrameRate::new(30, 1).expect("rate"), 48_000)
                .expect("settings"),
        ))
        .expect("valid project")
    }

    #[test]
    fn an_odd_4_2_0_output_is_refused_before_anything_is_encoded() {
        let range =
            TimeRange::new(MediaTime::ZERO, MediaTime::from_seconds(1)).expect("valid range");
        let rate = FrameRate::new(30, 1).expect("valid rate");
        for (size, suggested) in [((65, 49), (64, 48)), ((64, 49), (64, 48)), ((1, 3), (2, 2))] {
            let error = Exporter::new(
                &snapshot(size.0, size.1),
                range,
                rate,
                QualityProfile::export(),
                VideoCodec::H264,
            )
            .expect_err("odd output");
            assert_eq!(
                error,
                EngineError::OddExportDimensions {
                    width: size.0,
                    height: size.1,
                    suggested,
                }
            );
            assert!(
                error
                    .to_string()
                    .contains(&format!("{}x{}", suggested.0, suggested.1))
            );
        }
        assert!(
            Exporter::new(
                &snapshot(64, 48),
                range,
                rate,
                QualityProfile::export(),
                VideoCodec::H264
            )
            .is_ok()
        );
    }

    #[test]
    fn runners_expose_distinct_missing_frame_policies() {
        let rate = FrameRate::new(30, 1).expect("valid rate");
        let range =
            TimeRange::new(MediaTime::ZERO, MediaTime::from_seconds(1)).expect("valid range");
        let exporter = Exporter::new(
            &snapshot(16, 16),
            range,
            rate,
            QualityProfile::export(),
            VideoCodec::H264,
        )
        .expect("valid exporter");
        assert_eq!(
            Player::<alpha2_render::RenderedTexture>::default().missing_frame_policy(),
            MissingFramePolicy::HoldPrevious
        );
        assert_eq!(exporter.missing_frame_policy(), MissingFramePolicy::Wait);
    }

    #[test]
    fn schedule_uses_exact_rational_frame_boundaries() {
        let rate = FrameRate::new(30_000, 1_001).expect("valid rate");
        let start = rate.frame_start(10).expect("representable");
        let end = rate.frame_start(20).expect("representable");
        let exporter = Exporter::new(
            &snapshot(16, 16),
            TimeRange::new(start, end).expect("valid range"),
            rate,
            QualityProfile::export(),
            VideoCodec::H264,
        )
        .expect("valid exporter");
        assert_eq!(exporter.pending_time(), Some(start));
        assert_eq!(
            exporter.progress(),
            ExportProgress {
                completed: 0,
                total: 10,
            }
        );
    }

    #[test]
    fn schedule_includes_every_frame_intersecting_an_unaligned_range() {
        let rate = FrameRate::new(30, 1).expect("valid rate");
        let subframe = Exporter::new(
            &snapshot(16, 16),
            TimeRange::new(MediaTime(2_000), MediaTime(4_000)).expect("non-empty range"),
            rate,
            QualityProfile::export(),
            VideoCodec::H264,
        )
        .expect("one intersecting frame");
        assert_eq!(subframe.pending_time(), Some(MediaTime::ZERO));
        assert_eq!(subframe.progress().total, 1);

        let unaligned = Exporter::new(
            &snapshot(16, 16),
            TimeRange::new(MediaTime(2_000), MediaTime(6_000)).expect("non-empty range"),
            rate,
            QualityProfile::export(),
            VideoCodec::H264,
        )
        .expect("two intersecting frames");
        assert_eq!(unaligned.pending_time(), Some(MediaTime::ZERO));
        assert_eq!(unaligned.progress().total, 2);
        assert_eq!(
            unaligned.effective_range(),
            TimeRange::new(MediaTime::ZERO, MediaTime(8_000)).expect("frame grid")
        );
    }

    #[test]
    fn effective_range_is_the_request_widened_to_the_frame_grid() {
        let rate = FrameRate::new(30_000, 1_001).expect("valid rate");
        let frame = |index| rate.frame_start(index).expect("representable").ticks();
        for (start, end) in [
            (frame(3), frame(9)),
            (frame(3) + 1, frame(9) - 1),
            (frame(4) - 1, frame(8) + 1),
        ] {
            let exporter = Exporter::new(
                &snapshot(16, 16),
                TimeRange::new(MediaTime(start), MediaTime(end)).expect("non-empty range"),
                rate,
                QualityProfile::export(),
                VideoCodec::H264,
            )
            .expect("valid exporter");
            let effective = exporter.effective_range();
            assert_eq!(
                (effective.start(), effective.end()),
                (MediaTime(frame(3)), MediaTime(frame(9))),
                "{start}..{end}"
            );
            assert_eq!(exporter.pending_time(), Some(effective.start()));
        }
    }

    #[test]
    fn schedule_rejects_unbounded_frame_counts() {
        let rate = FrameRate::new(30, 1).expect("valid rate");
        let range = TimeRange::new(MediaTime::ZERO, MediaTime(i64::MAX)).expect("ordered range");
        assert!(matches!(
            Exporter::new(
                &snapshot(16, 16),
                range,
                rate,
                QualityProfile::export(),
                VideoCodec::H264
            ),
            Err(EngineError::ExportTooLarge { .. })
        ));
    }

    #[test]
    fn prefetch_reports_future_indices_without_advancing_the_cursor() {
        let rate = FrameRate::new(30, 1).expect("valid rate");
        let project = Project::new(
            ProjectId::new("prefetch").expect("project ID"),
            "prefetch",
            ProjectSettings::new(16, 16, rate, 48_000).expect("settings"),
        );
        let snapshot = EngineProject::new(project).expect("snapshot");
        let range =
            TimeRange::new(MediaTime::ZERO, MediaTime::from_seconds(1)).expect("non-empty range");
        let exporter = Exporter::new(
            &snapshot,
            range,
            rate,
            QualityProfile::export(),
            VideoCodec::H264,
        )
        .expect("valid exporter");

        let prefetched = exporter.prefetch_needs(&snapshot, 2).expect("prefetch");
        assert_eq!(
            prefetched
                .iter()
                .map(|frame| (frame.index, frame.time))
                .collect::<Vec<_>>(),
            vec![(0, MediaTime::ZERO), (1, MediaTime::from_ticks(4_000))]
        );
        assert!(prefetched.iter().all(|frame| frame.needs.is_empty()));
        assert_eq!(exporter.pending_time(), Some(MediaTime::ZERO));
        assert_eq!(exporter.progress().completed, 0);
    }

    #[test]
    fn upcoming_times_are_the_frames_the_cursor_reaches_next() {
        let rate = FrameRate::new(30, 1).expect("valid rate");
        let snapshot = snapshot(16, 16);
        // Three frames: 0, 1/30 s, and 2/30 s.
        let range = TimeRange::new(MediaTime::ZERO, MediaTime::from_ticks(12_000))
            .expect("non-empty range");
        let mut exporter = Exporter::new(
            &snapshot,
            range,
            rate,
            QualityProfile::export(),
            VideoCodec::H264,
        )
        .expect("valid exporter");
        let frame = MediaTime::from_ticks;
        assert_eq!(
            exporter.upcoming_times(2).expect("times"),
            vec![frame(0), frame(4_000)]
        );
        let (_, taken) = exporter.take_next().expect("take").expect("a frame");
        assert_eq!(taken, frame(0));
        // Fewer near the end; the cursor is not moved.
        assert_eq!(
            exporter.upcoming_times(5).expect("times"),
            vec![frame(4_000), frame(8_000)]
        );
        assert_eq!(exporter.pending_time(), Some(frame(4_000)));
        exporter.take_next().expect("take");
        exporter.take_next().expect("take");
        assert_eq!(exporter.upcoming_times(2).expect("times"), Vec::new());
    }

    #[test]
    fn a_whole_project_export_covers_its_caption_cues() {
        let project = |clips: &str| {
            let json = format!(
                r#"{{"schema_version": 1, "id": "p", "name": "p",
                  "settings": {{"width": 16, "height": 16, "frame_rate": {{"num": 30, "den": 1}}, "sample_rate": 48000}},
                  "sources": [{{"id": "v", "kind": "video", "locator": "v.mp4"}}],
                  "timeline": {{"tracks": [
                    {{"id": "t", "name": "T", "kind": "video", "clips": [{clips}]}},
                    {{"id": "c", "name": "C", "kind": "caption", "captions": {{"cues": [
                      {{"timeline_range": {{"start": 1080000, "end": 1440000}}, "text": "last line"}}]}}}}]}}}}"#
            );
            EngineProject::new(Project::from_json(&json).expect("valid")).expect("valid project")
        };
        let clip = r#"{"id": "a", "source_id": "v", "timeline_range": {"start": 0, "end": 1200000}, "source_range": {"start": 0, "end": 1200000}}"#;
        for (snapshot, start) in [(project(clip), 0), (project(""), 1_080_000)] {
            let range = snapshot.timeline_range().expect("something is shown");
            assert_eq!(
                (range.start().ticks(), range.end().ticks()),
                (start, 1_440_000)
            );
            let exporter =
                Exporter::for_project(&snapshot, QualityProfile::export(), VideoCodec::H264)
                    .expect("an export of the whole project");
            assert_eq!(exporter.effective_range(), range);
        }
    }
}