alpha2-host-core 0.10.0

FFmpeg-free native host logic for alpha2: the policies, audio timelines, cursor rules, providers, plugin runtime, protocol frames and request parsing native hosts share, and the decode, export and still pipeline the mobile hosts run.
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
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
//! The export loop: frame needs in, decoded and prepared frames into the store, rendered planes
//! out to the encoder.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::Range;
use std::sync::{Arc, Weak};

use alpha2_engine::ExportStepTimings;
use alpha2_engine::{
    EngineProject, ExportPlaneStep, Exporter, FrameProvider, FramesWithText, TextTextures,
};
use alpha2_eval::FrameNeed;
use alpha2_media::{
    CancelToken, DecodeError, DecodedVideoFrame, EncodeError, PixelLayout, SourceId,
};
use alpha2_render::{
    ColorPolicy, CpuRenderer, CpuSource, Nv12PlaneTargets, PlaneTarget, RenderSize, Renderer,
};
use alpha2_time::MediaTime;

use super::budget::FrameBudget;
use super::prepare::{GpuSource, SurfaceImport, prepare_cpu, prepare_gpu};
use crate::cursor::{CursorReads, DecodeCursorKey, decode_cursor_key};
use crate::encode::{LentBuffer, PlaneBuffer};
use crate::video_stream::{BackendImage, DroppedLayer, FrameFacts, StreamFrame, SurfaceLease};
use alpha2_engine::frame_store::{FramePair, FrameStore, StoredFrame, WorkingSetOverBudget};

/// Steps an export may wait on the same frame, refilling between them, before it fails: a frame
/// still missing after this many refills will not arrive.
pub const MAX_EXPORT_REFILLS: u32 = 4;

/// The renderer an export draws with.
#[derive(Clone, Copy)]
pub enum ExportRenderer<'a> {
    /// The GPU renderer.
    Gpu(&'a Renderer),
    /// The CPU renderer.
    Cpu(&'a CpuRenderer),
}

/// A decoded source frame: planes in memory, or a platform surface the GPU renderer imports.
#[derive(Clone, Debug)]
pub enum SourceFrame {
    /// Planes in memory, for either renderer.
    Cpu(Arc<DecodedVideoFrame>),
    /// A decoder surface, for the GPU renderer only.
    Surface(SurfaceFrame),
}

impl SourceFrame {
    /// When the frame is presented.
    #[must_use]
    pub fn pts(&self) -> MediaTime {
        match self {
            Self::Cpu(frame) => frame.pts,
            Self::Surface(surface) => surface.facts.pts,
        }
    }
}

/// A frame decoded on the way to the frame asked for.
#[derive(Debug)]
pub struct PassedFrame {
    /// The frame.
    pub frame: SourceFrame,
    /// The source times, in ticks, it is the frame shown at.
    pub shown: Range<i64>,
}

/// A decoder surface and the import that turns it into a GPU source.
#[derive(Clone)]
pub struct SurfaceFrame {
    /// The frame's facts.
    pub facts: FrameFacts,
    /// The surface, held until the frame is prepared.
    pub lease: Arc<dyn SurfaceLease>,
    /// Prepares the surface for the GPU renderer.
    pub import: Arc<dyn SurfaceImport>,
}

impl std::fmt::Debug for SurfaceFrame {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SurfaceFrame")
            .field("facts", &self.facts)
            .field("lease", &self.lease)
            .finish_non_exhaustive()
    }
}

/// Decoded frames of the project's sources, by need.
pub trait SourceFrames {
    /// The decoded frame `need` of output frame `index` shows: the frame presented at its media
    /// time; `None` for an audio source, which audio clips name but nothing draws.
    ///
    /// # Errors
    /// A source that cannot be opened or decoded there, with the reason.
    fn frame(
        &mut self,
        need: &FrameNeed,
        index: u64,
        cancel: &CancelToken,
    ) -> Result<Option<SourceFrame>, String>;

    /// As [`Self::frame`], handing `passed` the frames decoded on the way that are shown before
    /// the answer, in presentation order. The default decodes no frame on the way.
    ///
    /// # Errors
    /// As [`Self::frame`].
    fn frame_passing(
        &mut self,
        need: &FrameNeed,
        index: u64,
        cancel: &CancelToken,
        _passed: &mut dyn FnMut(PassedFrame),
    ) -> Result<Option<SourceFrame>, String> {
        self.frame(need, index, cancel)
    }

    /// The frame after the one [`Self::frame`] just answered for `need`, asked for a need that
    /// follows ([`FrameNeed::following`]). `None` when that frame is its source's last, which is
    /// also what the default answers: the clip then holds its frame.
    ///
    /// # Errors
    /// A source that cannot be decoded there, with the reason.
    fn following(
        &mut self,
        _need: &FrameNeed,
        _index: u64,
        _cancel: &CancelToken,
    ) -> Result<Option<SourceFrame>, String> {
        Ok(None)
    }

    /// Lets go of what only frames before timeline `time` read; called before the frame at `time`
    /// is decoded.
    fn release_finished(&mut self, _time: MediaTime) {}

    /// Bytes of decoded frames held outside the prepared-frame cache.
    fn held_bytes(&self) -> u64 {
        0
    }
}

/// Where rendered pictures go: the video encoder.
pub trait VideoSink {
    /// Takes frame `index` at `time`, packed as `layout` in one buffer per plane.
    ///
    /// # Errors
    /// An encoder or output failure.
    fn write_video(
        &mut self,
        index: u64,
        time: MediaTime,
        layout: PixelLayout,
        planes: &[PlaneBuffer],
    ) -> Result<(), EncodeError>;

    /// Finishes the frames the encoder holds, before the export waits. The default does nothing.
    ///
    /// # Errors
    /// An encoder or output failure.
    fn settle(&mut self) -> Result<(), EncodeError> {
        Ok(())
    }

    /// The encoder's buffers to render frames into, when it lends them. The default lends none.
    fn lender(&mut self) -> Option<&mut dyn SinkLender> {
        None
    }
}

/// A sink whose encoder lends its input buffers: the renderer draws a frame into one, and the
/// sink encodes it.
pub trait SinkLender {
    /// A buffer for the next frame, waiting while the encoder is busy.
    ///
    /// # Errors
    /// An encoder failure, or an encoder that stays busy.
    fn lend(&mut self) -> Result<LentBuffer, EncodeError>;

    /// Encodes frame `index` at `time`, drawn into `buffer`.
    ///
    /// # Errors
    /// An encoder or output failure.
    fn write_lent(
        &mut self,
        index: u64,
        time: MediaTime,
        buffer: LentBuffer,
    ) -> Result<(), EncodeError>;
}

/// The luma and chroma render targets of a lent buffer, as the NV12 pack writes them.
#[derive(Clone, Debug)]
pub struct LentPlanes {
    /// `R8Unorm`, at the output size.
    pub luma: wgpu::TextureView,
    /// `Rg8Unorm`, at half the output size each way.
    pub chroma: wgpu::TextureView,
}

/// Makes lent encoder buffers render targets on the GPU renderer's device: the platform's half
/// of rendering frames in place, as [`SurfaceImport`] is of decoding them.
pub trait EncoderTargets {
    /// The planes of `buffer` as render targets for a frame of `size`.
    ///
    /// # Errors
    /// A buffer that cannot be a render target there; the export then reads frames back.
    fn planes(&mut self, buffer: &LentBuffer, size: RenderSize) -> Result<LentPlanes, String>;

    /// Waits until the GPU finished the frame rendered into `buffer`'s planes.
    ///
    /// # Errors
    /// A wait that failed or ran out of time.
    fn finished(&mut self, buffer: &LentBuffer) -> Result<(), String>;
}

/// Why an export stopped.
#[derive(Debug)]
pub enum ExportError {
    /// The caller cancelled.
    Cancelled,
    /// A source could not be decoded.
    Source {
        /// The source.
        source: SourceId,
        /// Why.
        reason: String,
    },
    /// A frame's sources never arrived after [`MAX_EXPORT_REFILLS`] refills.
    Stalled {
        /// The frame's timeline time.
        time: MediaTime,
        /// The sources still missing.
        missing: Vec<SourceId>,
    },
    /// The engine failed to evaluate or render.
    Render(String),
    /// The encoder or output failed.
    Encode(EncodeError),
}

impl std::fmt::Display for ExportError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Cancelled => write!(formatter, "the export was cancelled"),
            Self::Source { source, reason } => write!(formatter, "source {source}: {reason}"),
            Self::Stalled { time, missing } => write!(
                formatter,
                "frame at {} ticks still lacks {} after {MAX_EXPORT_REFILLS} refills",
                time.ticks(),
                missing
                    .iter()
                    .map(SourceId::as_str)
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Self::Render(reason) => write!(formatter, "{reason}"),
            Self::Encode(error) => write!(formatter, "{error}"),
        }
    }
}

impl std::error::Error for ExportError {}

/// Prepared frames for whichever renderer runs.
/// Decoded source frames prepared for one renderer, kept within a byte budget: what an export or a
/// preview renders from.
pub struct SourceFrameCache {
    store: Store,
    passed: Passed,
}

enum Store {
    Gpu(FrameStore<GpuSource>),
    Cpu(FrameStore<CpuSource>),
}

#[derive(Default)]
struct Passed {
    share: u64,
    kept: Vec<KeptPassed>,
    frame_bytes: Option<u64>,
}

struct KeptPassed {
    source: String,
    shown: Range<i64>,
    bytes: u64,
}

impl SourceFrameCache {
    /// An empty cache for `renderer`, keeping up to `bytes` of frames.
    #[must_use]
    pub fn for_renderer(renderer: ExportRenderer<'_>, bytes: u64) -> Self {
        let store = match renderer {
            ExportRenderer::Gpu(_) => {
                Store::Gpu(FrameStore::sized(GpuSource::retained_bytes, bytes))
            }
            ExportRenderer::Cpu(_) => {
                Store::Cpu(FrameStore::sized(CpuSource::retained_bytes, bytes))
            }
        };
        Self {
            store,
            passed: Passed::default(),
        }
    }

    /// Sets the cache's budget to `budget` less the `held` bytes the sources keep, evicting at once
    /// to fit. It never goes below the last output frame's working set, so a budget lowered under
    /// memory pressure still lets the next frame of the same shape render.
    pub fn follow(&mut self, budget: &FrameBudget, held: u64) {
        let bytes = budget.bytes().saturating_sub(held);
        match &mut self.store {
            Store::Gpu(store) => {
                store.set_video_byte_budget(bytes.max(store.last_working_set_bytes()));
            }
            Store::Cpu(store) => {
                store.set_video_byte_budget(bytes.max(store.last_working_set_bytes()));
            }
        }
    }

    /// Keeps up to `bytes` of the frames decoded on the way to those [`Self::fill`] asks for, and
    /// answers later needs from them; 0, the default, keeps none and drops those kept.
    pub fn keep_passed(&mut self, bytes: u64) {
        self.passed.share = bytes;
        self.trim_passed(None, &[]);
    }

    /// Bytes of the frames kept from those decoded on the way ([`Self::keep_passed`]).
    #[must_use]
    pub fn passed_bytes(&self) -> u64 {
        self.passed.kept.iter().map(|kept| kept.bytes).sum()
    }

    /// The frames, for the renderer.
    #[must_use]
    pub fn provider(&self) -> &dyn FrameProvider {
        match &self.store {
            Store::Gpu(store) => store,
            Store::Cpu(store) => store,
        }
    }

    /// Decodes and prepares every frame `needs` (of output frame `index`) names that the cache
    /// does not hold, and keeps them until [`Self::unpin`].
    ///
    /// # Errors
    /// A source that cannot be decoded or prepared, or one past the budget.
    pub fn fill(
        &mut self,
        renderer: ExportRenderer<'_>,
        size: RenderSize,
        color: ColorPolicy,
        (index, needs): (u64, &[FrameNeed]),
        sources: &mut dyn SourceFrames,
        cancel: &CancelToken,
    ) -> Result<(), ExportError> {
        fill(self, renderer, size, color, (index, needs), sources, cancel)
    }

    /// Lets the frames the last [`Self::fill`] kept go when the budget needs room.
    pub fn unpin(&mut self) {
        match &mut self.store {
            Store::Gpu(store) => store.unpin(),
            Store::Cpu(store) => store.unpin(),
        }
    }

    /// Drops the frames of the sources in `sources`, whose media changed.
    pub fn release_sources(&mut self, sources: &HashSet<SourceId>) {
        let stale = sources.iter().map(SourceId::as_str).collect::<HashSet<_>>();
        match &mut self.store {
            Store::Gpu(store) => store.retain_sources(|source| !stale.contains(source)),
            Store::Cpu(store) => store.retain_sources(|source| !stale.contains(source)),
        }
        self.passed
            .kept
            .retain(|kept| !stale.contains(kept.source.as_str()));
    }

    /// Drops every frame.
    pub fn clear(&mut self) {
        match &mut self.store {
            Store::Gpu(store) => store.clear(),
            Store::Cpu(store) => store.clear(),
        }
        self.passed.kept.clear();
    }

    fn pin(&mut self, keys: Vec<(String, i64)>) {
        match &mut self.store {
            Store::Gpu(store) => store.pin(keys),
            Store::Cpu(store) => store.pin(keys),
        }
    }

    fn holds(&self, source: &str, time: i64) -> bool {
        match &self.store {
            Store::Gpu(store) => store.get(source, time).is_some(),
            Store::Cpu(store) => store.get(source, time).is_some(),
        }
    }

    fn follows(&self, source: &str, time: i64) -> bool {
        match &self.store {
            Store::Gpu(store) => store.follows(source, time),
            Store::Cpu(store) => store.follows(source, time),
        }
    }

    fn insert(&mut self, key: (String, i64), frame: Prepared) -> Result<(), WorkingSetOverBudget> {
        match (&mut self.store, frame) {
            (Store::Gpu(store), Prepared::Gpu(frame)) => store.insert(key, frame).map(|_| ()),
            (Store::Cpu(store), Prepared::Cpu(frame)) => store.insert(key, frame).map(|_| ()),
            _ => unreachable!("the store matches the renderer"),
        }
    }

    fn insert_following(
        &mut self,
        key: (String, i64),
        frame: Prepared,
        times: FramePair,
    ) -> Result<(), WorkingSetOverBudget> {
        match (&mut self.store, frame) {
            (Store::Gpu(store), Prepared::Gpu(frame)) => {
                store.insert_following(key, frame, times).map(|_| ())
            }
            (Store::Cpu(store), Prepared::Cpu(frame)) => {
                store.insert_following(key, frame, times).map(|_| ())
            }
            _ => unreachable!("the store matches the renderer"),
        }
    }

    fn share(
        &mut self,
        pts: i64,
        key: &(String, i64),
        times: Option<FramePair>,
    ) -> Result<bool, WorkingSetOverBudget> {
        macro_rules! share {
            ($store:expr) => {{
                let Some((existing, kept)) = $store.kept_at(&key.0, pts) else {
                    return Ok(false);
                };
                match times {
                    Some(times) => $store.alias_following((&existing, kept), key.clone(), times),
                    None => $store.alias_kept((&existing, kept), key.clone()),
                }
            }};
        }
        match &mut self.store {
            Store::Gpu(store) => share!(store),
            Store::Cpu(store) => share!(store),
        }
    }

    fn set_last(&mut self, key: (String, i64)) {
        match &mut self.store {
            Store::Gpu(store) => store.set_last(key),
            Store::Cpu(store) => store.set_last(key),
        };
    }

    fn answer_from_passed(&mut self, key: &(String, i64)) -> Result<bool, WorkingSetOverBudget> {
        self.forget_evicted_passed();
        let Some(kept) = self
            .passed
            .kept
            .iter()
            .find(|kept| kept.source == key.0 && kept.shown.contains(&key.1))
        else {
            return Ok(false);
        };
        let existing = (kept.source.clone(), kept.shown.start);
        match &mut self.store {
            Store::Gpu(store) => store.alias(&existing, key.clone()),
            Store::Cpu(store) => store.alias(&existing, key.clone()),
        }
    }

    fn keep_passed_frame(
        &mut self,
        (renderer, size, color): (ExportRenderer<'_>, RenderSize, ColorPolicy),
        (source, target): (&str, i64),
        pinned: &[(String, i64)],
        passed: PassedFrame,
    ) {
        let shown = passed.shown;
        if self
            .passed
            .kept
            .iter()
            .any(|kept| kept.source == source && kept.shown.start == shown.start)
        {
            return;
        }
        if let Some(bytes) = self.passed.frame_bytes {
            let length = (shown.end - shown.start).max(1);
            let between = u64::try_from(target.saturating_sub(shown.end) / length).unwrap_or(0);
            if between.saturating_mul(bytes) >= self.passed.share {
                return;
            }
        }
        let (import, planes) = match &passed.frame {
            SourceFrame::Surface(surface) => (Some(Arc::clone(&surface.import)), 0),
            SourceFrame::Cpu(frame) => (
                None,
                frame
                    .planes
                    .iter()
                    .map(|plane| plane.bytes.len() as u64)
                    .sum(),
            ),
        };
        let Ok(prepared) = prepare(renderer, size, color, passed.frame) else {
            return;
        };
        let bytes = match &prepared {
            Prepared::Gpu(frame) => {
                if let (ExportRenderer::Gpu(renderer), Some(pending)) =
                    (renderer, frame.pending_work())
                {
                    renderer.submit_pending_source(pending);
                    if let Some(import) = import {
                        let _ = renderer.reclaim_external_leases();
                        import.collect();
                    }
                }
                frame.retained_bytes()
            }
            Prepared::Cpu(frame) => frame.retained_bytes().max(planes),
        };
        self.passed.frame_bytes = Some(bytes);
        if self
            .insert((source.to_owned(), shown.start), prepared)
            .is_err()
        {
            return;
        }
        self.passed.kept.push(KeptPassed {
            source: source.to_owned(),
            shown,
            bytes,
        });
        self.trim_passed(Some((source, target)), pinned);
    }

    fn trim_passed(&mut self, target: Option<(&str, i64)>, pinned: &[(String, i64)]) {
        self.forget_evicted_passed();
        let distance = |kept: &KeptPassed| match target {
            Some((source, time)) if source == kept.source => kept.shown.start.abs_diff(time),
            _ => u64::MAX,
        };
        while self.passed_bytes() > self.passed.share {
            let Some(farthest) = self
                .passed
                .kept
                .iter()
                .enumerate()
                .filter(|(_, kept)| {
                    !pinned
                        .iter()
                        .any(|key| key.0 == kept.source && key.1 == kept.shown.start)
                })
                .max_by_key(|(_, kept)| distance(kept))
                .map(|(at, _)| at)
            else {
                return;
            };
            let kept = self.passed.kept.swap_remove(farthest);
            match &mut self.store {
                Store::Gpu(store) => store.remove(&kept.source, kept.shown.start),
                Store::Cpu(store) => store.remove(&kept.source, kept.shown.start),
            };
        }
    }

    fn forget_evicted_passed(&mut self) {
        let mut kept = std::mem::take(&mut self.passed.kept);
        kept.retain(|kept| self.holds(&kept.source, kept.shown.start));
        self.passed.kept = kept;
    }
}

#[expect(
    clippy::large_enum_variant,
    reason = "moved once into the store, which keeps the value itself"
)]
enum Prepared {
    Gpu(GpuSource),
    Cpu(CpuSource),
}

fn prepare(
    renderer: ExportRenderer<'_>,
    size: RenderSize,
    color: ColorPolicy,
    frame: SourceFrame,
) -> Result<Prepared, String> {
    match (renderer, frame) {
        (ExportRenderer::Gpu(renderer), SourceFrame::Cpu(frame)) => {
            prepare_gpu(renderer, size, color, &frame).map(Prepared::Gpu)
        }
        (ExportRenderer::Gpu(renderer), SourceFrame::Surface(surface)) => surface
            .import
            .prepare(renderer, size, color, &surface.facts, &surface.lease)
            .map(Prepared::Gpu),
        (ExportRenderer::Cpu(renderer), SourceFrame::Cpu(frame)) => {
            prepare_cpu(renderer, size, color, frame).map(Prepared::Cpu)
        }
        (ExportRenderer::Cpu(_), SourceFrame::Surface(_)) => {
            Err("the decoder produced a GPU surface, which the CPU renderer cannot draw".into())
        }
    }
}

/// Renders every frame of `exporter` into `sink`, decoding sources through `sources`.
///
/// Frames wait for their sources and never repeat a late one, so output does not depend on
/// decode timing. Decoded frames stay within `budget`, read before every frame. `before_frame`
/// runs at the top of every turn with the sink (it may block, as a host's pause does), and
/// `progress` is told after each frame. With the GPU renderer, `targets` and a sink that lends,
/// frames are drawn into the encoder's buffers; once `targets` refuses one, the rest of the
/// export reads frames back.
///
/// # Errors
/// Cancellation, a source or render failure, a frame whose sources never arrive, or a sink
/// failure.
#[allow(clippy::too_many_arguments)]
pub fn export_video(
    snapshot: &EngineProject,
    exporter: &mut Exporter,
    (renderer, mut targets): (ExportRenderer<'_>, Option<&mut (dyn EncoderTargets + '_)>),
    texts: &mut TextTextures,
    sources: &mut dyn SourceFrames,
    sink: &mut dyn VideoSink,
    (budget, cancel): (&FrameBudget, &CancelToken),
    before_frame: &mut dyn FnMut(&mut dyn VideoSink) -> Result<(), EncodeError>,
    progress: &mut dyn FnMut(u64, u64),
) -> Result<(), ExportError> {
    let size = exporter
        .render_size(snapshot)
        .map_err(|error| ExportError::Render(error.to_string()))?;
    let color = alpha2_engine::color_policy(&snapshot.project().settings.color);
    let mut store = SourceFrameCache::for_renderer(renderer, budget.bytes());
    let layout = exporter.pixels();
    let mut planes = plane_buffers(layout, size);
    let mut refills = 0;
    let mut kept: Option<LentBuffer> = None;
    loop {
        before_frame(sink).map_err(ExportError::Encode)?;
        if cancel.is_cancelled() {
            return Err(ExportError::Cancelled);
        }
        let needs = exporter
            .prefetch_needs(snapshot, 1)
            .map_err(|error| ExportError::Render(error.to_string()))?;
        let Some(frame) = needs.first() else {
            return Ok(());
        };
        sources.release_finished(frame.time);
        store.follow(budget, sources.held_bytes());
        fill(
            &mut store,
            renderer,
            size,
            color,
            (frame.index, &frame.needs),
            sources,
            cancel,
        )?;
        if let Some(time) = exporter.pending_time() {
            let upload: &dyn alpha2_engine::TextUpload = match renderer {
                ExportRenderer::Gpu(renderer) => renderer,
                ExportRenderer::Cpu(renderer) => renderer,
            };
            texts
                .prepare_at(upload, snapshot, time, size)
                .map_err(|error| ExportError::Render(error.to_string()))?;
        }
        let provider = FramesWithText::new(store.provider(), texts);
        let lent = match (renderer, targets.as_deref_mut(), sink.lender()) {
            (ExportRenderer::Gpu(gpu), Some(lending), Some(lender)) => Some(render_lent(
                (snapshot, exporter, gpu, &provider, size),
                lending,
                lender,
                &mut kept,
            )?),
            _ => None,
        };
        let (step, buffer) = match lent {
            Some(LentStep::Drawn(step, buffer)) => (step, Some(buffer)),
            refused => {
                if matches!(refused, Some(LentStep::Refused)) {
                    targets = None;
                }
                let step = render_readback(snapshot, exporter, renderer, &provider, &mut planes)?;
                (step, None)
            }
        };
        match step {
            ExportPlaneStep::Rendered { index, time } => {
                refills = 0;
                store.unpin();
                match buffer {
                    Some(buffer) => write_lent(targets.as_deref_mut(), sink, index, time, buffer)?,
                    None => sink
                        .write_video(index, time, layout, &planes)
                        .map_err(ExportError::Encode)?,
                }
                let done = exporter.progress();
                progress(done.completed, done.total);
            }
            ExportPlaneStep::Waiting {
                time,
                missing_sources,
            } => {
                kept = buffer;
                refills += 1;
                if refills > MAX_EXPORT_REFILLS {
                    return Err(ExportError::Stalled {
                        time,
                        missing: missing_sources,
                    });
                }
            }
            ExportPlaneStep::Complete => return Ok(()),
        }
    }
}

fn plane_buffers(layout: PixelLayout, size: RenderSize) -> Vec<PlaneBuffer> {
    layout
        .planes(size.width, size.height)
        .into_iter()
        .map(|(width, height, bytes)| {
            let stride = usize::try_from(width * bytes).unwrap_or(0);
            PlaneBuffer {
                bytes: vec![0; stride * usize::try_from(height).unwrap_or(0)],
                stride,
                width,
                height,
            }
        })
        .collect()
}

enum LentStep {
    Drawn(ExportPlaneStep, LentBuffer),
    Refused,
}

fn render_lent(
    (snapshot, exporter, renderer, provider, size): (
        &EngineProject,
        &mut Exporter,
        &Renderer,
        &dyn FrameProvider,
        RenderSize,
    ),
    targets: &mut (dyn EncoderTargets + '_),
    lender: &mut dyn SinkLender,
    kept: &mut Option<LentBuffer>,
) -> Result<LentStep, ExportError> {
    let buffer = match kept.take() {
        Some(buffer) => buffer,
        None => lender.lend().map_err(ExportError::Encode)?,
    };
    let Ok(planes) = targets.planes(&buffer, size) else {
        return Ok(LentStep::Refused);
    };
    let step = exporter
        .render_next_nv12_timed(
            snapshot,
            renderer,
            provider,
            Nv12PlaneTargets {
                luma: &planes.luma,
                chroma: &planes.chroma,
            },
            &mut ExportStepTimings::default(),
        )
        .map_err(|error| ExportError::Render(error.to_string()))?;
    Ok(LentStep::Drawn(step, buffer))
}

fn render_readback(
    snapshot: &EngineProject,
    exporter: &mut Exporter,
    renderer: ExportRenderer<'_>,
    provider: &dyn FrameProvider,
    planes: &mut [PlaneBuffer],
) -> Result<ExportPlaneStep, ExportError> {
    let mut targets = planes
        .iter_mut()
        .map(|plane| PlaneTarget::new(&mut plane.bytes, plane.stride))
        .collect::<Vec<_>>();
    match renderer {
        ExportRenderer::Gpu(renderer) => {
            exporter.render_next_into_planes(snapshot, renderer, provider, &mut targets, None)
        }
        ExportRenderer::Cpu(renderer) => {
            exporter.render_next_into_planes(snapshot, renderer, provider, &mut targets, None)
        }
    }
    .map_err(|error| ExportError::Render(error.to_string()))
}

fn write_lent(
    targets: Option<&mut (dyn EncoderTargets + '_)>,
    sink: &mut dyn VideoSink,
    index: u64,
    time: MediaTime,
    buffer: LentBuffer,
) -> Result<(), ExportError> {
    let (Some(targets), Some(lender)) = (targets, sink.lender()) else {
        return Err(ExportError::Render(
            "a frame drawn into a lent buffer lost its lender".into(),
        ));
    };
    targets.finished(&buffer).map_err(ExportError::Render)?;
    lender
        .write_lent(index, time, buffer)
        .map_err(ExportError::Encode)
}

/// Decodes and prepares every frame `needs` names that the store does not hold, pinning them.
fn fill(
    store: &mut SourceFrameCache,
    renderer: ExportRenderer<'_>,
    size: RenderSize,
    color: ColorPolicy,
    (index, needs): (u64, &[FrameNeed]),
    sources: &mut dyn SourceFrames,
    cancel: &CancelToken,
) -> Result<(), ExportError> {
    let keys = needs
        .iter()
        .map(|need| (need.source_id.as_str().to_owned(), need.media_time.ticks()))
        .collect::<Vec<_>>();
    store.pin(keys.clone());
    let mut done = HashSet::new();
    for need in needs {
        let key = (need.source_id.as_str().to_owned(), need.media_time.ticks());
        if !done.insert(key.clone())
            || (store.holds(&key.0, key.1) && (!need.following || store.follows(&key.0, key.1)))
        {
            continue;
        }
        let failed = |reason: String| ExportError::Source {
            source: need.source_id.clone(),
            reason,
        };
        let over = |over: WorkingSetOverBudget| {
            failed(format!(
                "the frame's sources need {} bytes, over the {} byte budget",
                over.needed(),
                over.budget
            ))
        };
        let keeps_passed = store.passed.share > 0 && !need.following;
        if keeps_passed && store.answer_from_passed(&key).map_err(over)? {
            continue;
        }
        let answer = if keeps_passed {
            sources.frame_passing(need, index, cancel, &mut |passed| {
                store.keep_passed_frame((renderer, size, color), (&key.0, key.1), &keys, passed);
            })
        } else {
            sources.frame(need, index, cancel)
        };
        let Some(frame) = answer.map_err(failed)? else {
            continue;
        };
        if !need.following {
            let prepared = prepare(renderer, size, color, frame).map_err(failed)?;
            store.insert(key, prepared).map_err(over)?;
            continue;
        }
        let after = sources.following(need, index, cancel).map_err(failed)?;
        let presented_at = frame.pts().ticks();
        if !store.share(presented_at, &key, None).map_err(over)? {
            let prepared = prepare(renderer, size, color, frame).map_err(failed)?;
            store.insert(key.clone(), prepared).map_err(over)?;
        }
        let Some(after) = after else {
            store.set_last(key);
            continue;
        };
        let times = FramePair {
            presented_at,
            at: after.pts().ticks(),
        };
        if !store.share(times.at, &key, Some(times)).map_err(over)? {
            let prepared = prepare(renderer, size, color, after).map_err(failed)?;
            store.insert_following(key, prepared, times).map_err(over)?;
        }
    }
    Ok(())
}

/// Opens one [`crate::video_stream::VideoStream`] per cursor and keeps decoding forward while
/// requests stay within the sequential gap, seeking otherwise.
///
/// A cursor its reads say is finished is closed, at most a set number of video streams stay open,
/// and one decoded still serves every cursor of its source. A closed cursor reopens with a seek.
pub struct StreamSources<F> {
    open: F,
    streams: HashMap<DecodeCursorKey, Cursor>,
    /// When each cursor reads, which closes a finished one.
    reads: Option<CursorReads>,
    /// Video streams open at most, beyond the ones the current output frame reads.
    session_limit: Option<usize>,
    /// Each still source's decoded picture while a cursor holds it.
    stills: HashMap<SourceId, Weak<DecodedVideoFrame>>,
    /// Sources that opened as something other than a video stream.
    not_video: HashSet<SourceId>,
    /// What each source's pictures go without, noted when it first opens.
    dropped: BTreeMap<SourceId, DroppedLayer>,
    /// Prepares the decoder surfaces the streams produce.
    surfaces: Option<Arc<dyn SurfaceImport>>,
    /// Supplies the extension sources.
    #[cfg(feature = "providers")]
    providers: Option<Arc<crate::providers::ProviderMedia>>,
}

/// What a source decodes from: a video stream, or a still shown at every time.
pub enum SourceStream {
    /// A video track's frames.
    Video(Box<crate::video_stream::VideoStream>),
    /// One picture.
    Still(Arc<DecodedVideoFrame>),
    /// Audio alone: audio clips name the source, but it has no pictures.
    AudioOnly,
}

/// One cursor's source, the time it was last asked for and the frame it answered, and the output
/// frame that last read it.
struct Cursor {
    stream: SourceStream,
    last: Option<(MediaTime, StreamFrame)>,
    reached: bool,
    same_keyframe_until: Option<MediaTime>,
    following: Option<StreamFrame>,
    used: u64,
}

impl<F> StreamSources<F>
where
    F: FnMut(&SourceId) -> Result<SourceStream, String>,
{
    /// Opens sources with `open`, a source's stream from the start.
    pub fn new(open: F) -> Self {
        Self {
            open,
            streams: HashMap::new(),
            reads: None,
            session_limit: None,
            stills: HashMap::new(),
            not_video: HashSet::new(),
            dropped: BTreeMap::new(),
            surfaces: None,
            #[cfg(feature = "providers")]
            providers: None,
        }
    }

    /// Closes a cursor once `reads` say it reads nothing more ([`SourceFrames::release_finished`]).
    /// A cursor `reads` does not know is never closed this way.
    #[must_use]
    pub fn with_reads(mut self, reads: CursorReads) -> Self {
        self.reads = Some(reads);
        self
    }

    /// Before opening a video stream while `limit` are open, closes the one read longest ago that
    /// the current output frame does not read.
    #[must_use]
    pub fn with_session_limit(mut self, limit: usize) -> Self {
        self.session_limit = Some(limit.max(1));
        self
    }

    /// From now on, before opening a video stream while `limit` are open, closes the one read
    /// longest ago that the current output frame does not read.
    pub fn set_session_limit(&mut self, limit: usize) {
        self.session_limit = Some(limit.max(1));
    }

    /// Opens the sources read from now on with `open`; open cursors stay.
    pub fn set_opener(&mut self, open: F) {
        self.open = open;
    }

    /// Closes every cursor of the sources in `stale` and forgets what their opening noted.
    pub fn forget(&mut self, stale: &HashSet<SourceId>) {
        let open = self.streams.len();
        self.streams
            .retain(|(source, ..), _| !stale.contains(source));
        self.stills.retain(|source, _| !stale.contains(source));
        self.not_video.retain(|source| !stale.contains(source));
        self.dropped.retain(|source, _| !stale.contains(source));
        if self.streams.len() < open {
            self.collect_surfaces();
        }
    }

    /// Closes every cursor `keep` refuses.
    pub fn retain_cursors(&mut self, keep: impl Fn(&DecodeCursorKey) -> bool) {
        let open = self.streams.len();
        self.streams.retain(|cursor, _| keep(cursor));
        if self.streams.len() < open {
            self.collect_surfaces();
        }
    }

    /// Video streams open now.
    #[must_use]
    pub fn open_streams(&self) -> usize {
        self.streams
            .values()
            .filter(|cursor| matches!(cursor.stream, SourceStream::Video(_)))
            .count()
    }

    /// Closes the least recently read video stream other than those output frame `index` read,
    /// while `limit` or more are open.
    fn make_room(&mut self, limit: usize, index: u64) {
        while self.open_streams() >= limit {
            let Some(oldest) = self
                .streams
                .iter()
                .filter(|(_, cursor)| {
                    cursor.used != index && matches!(cursor.stream, SourceStream::Video(_))
                })
                .min_by_key(|(_, cursor)| cursor.used)
                .map(|(key, _)| key.clone())
            else {
                return;
            };
            self.streams.remove(&oldest);
            self.collect_surfaces();
        }
    }

    /// Lets the surface import free what the closed streams' frames held.
    fn collect_surfaces(&self) {
        if let Some(import) = &self.surfaces {
            import.collect();
        }
    }

    /// Opens `source`'s stream, reusing a still another cursor holds.
    fn open_stream(&mut self, source: &SourceId, index: u64) -> Result<SourceStream, String> {
        if let Some(still) = self.stills.get(source).and_then(Weak::upgrade) {
            return Ok(SourceStream::Still(still));
        }
        if let Some(limit) = self.session_limit
            && !self.not_video.contains(source)
        {
            self.make_room(limit, index);
        }
        let stream = (self.open)(source)?;
        match &stream {
            SourceStream::Still(still) => {
                self.stills.insert(source.clone(), Arc::downgrade(still));
                self.not_video.insert(source.clone());
            }
            SourceStream::AudioOnly => {
                self.not_video.insert(source.clone());
            }
            SourceStream::Video(video) => {
                if let Some(dropped) = video.dropped_layer() {
                    self.dropped
                        .entry(source.clone())
                        .or_insert_with(|| dropped.clone());
                }
            }
        }
        Ok(stream)
    }

    /// What the pictures of each source opened so far go without, one entry per source.
    #[must_use]
    pub const fn dropped_layers(&self) -> &BTreeMap<SourceId, DroppedLayer> {
        &self.dropped
    }

    /// Prepares the decoder surfaces the streams produce with `import`; without it a surface
    /// frame fails its source.
    #[must_use]
    pub fn with_surface_import(mut self, import: Arc<dyn SurfaceImport>) -> Self {
        self.surfaces = Some(import);
        self
    }

    /// Also takes the frames of the sources `providers` supplies from it.
    #[cfg(feature = "providers")]
    #[must_use]
    pub fn with_providers(mut self, providers: Arc<crate::providers::ProviderMedia>) -> Self {
        self.providers = Some(providers);
        self
    }

    /// Takes the frames of the sources `providers` supplies from it from now on, instead of the
    /// extension sources set before.
    #[cfg(feature = "providers")]
    pub fn set_providers(&mut self, providers: Arc<crate::providers::ProviderMedia>) {
        self.providers = Some(providers);
    }
}

impl Cursor {
    fn stop(&mut self, time: MediaTime, stopped: Stopped, cancelled: bool) -> String {
        self.following = None;
        if cancelled {
            self.last = stopped.reached.map(|frame| (frame.facts.pts, frame));
            self.reached = true;
            self.same_keyframe_until = if stopped.sought {
                Some(time)
            } else {
                self.same_keyframe_until.filter(|until| time <= *until)
            };
        } else {
            self.same_keyframe_until = None;
        }
        stopped.error
    }
}

impl<F> StreamSources<F>
where
    F: FnMut(&SourceId) -> Result<SourceStream, String>,
{
    fn frame_with(
        &mut self,
        need: &FrameNeed,
        index: u64,
        cancel: &CancelToken,
        passed: Option<&mut dyn FnMut(PassedFrame)>,
    ) -> Result<Option<SourceFrame>, String> {
        let cursor = decode_cursor_key(need);
        // Only provider sources keep frames by output frame.
        #[cfg(not(feature = "providers"))]
        let _ = index;
        #[cfg(feature = "providers")]
        if let Some(providers) = self
            .providers
            .as_ref()
            .filter(|providers| providers.supplies(&need.source_id))
        {
            return providers
                .frame(&cursor, need.media_time, index)
                .map(|frame| Some(SourceFrame::Cpu(Arc::new(frame))))
                .map_err(|error| error.to_string());
        }
        if !self.streams.contains_key(&cursor) {
            let stream = self.open_stream(&need.source_id, index)?;
            self.streams.insert(
                cursor.clone(),
                Cursor {
                    stream,
                    last: None,
                    reached: false,
                    same_keyframe_until: None,
                    following: None,
                    used: index,
                },
            );
        }
        let entry = self
            .streams
            .get_mut(&cursor)
            .ok_or_else(|| "the stream was not opened".to_owned())?;
        entry.used = index;
        let stream = match &mut entry.stream {
            SourceStream::Still(frame) => return Ok(Some(SourceFrame::Cpu(Arc::clone(frame)))),
            SourceStream::AudioOnly => return Ok(None),
            SourceStream::Video(stream) => stream,
        };
        let time = need.media_time;
        let slack = stream.presentation_slack().ticks();
        let surfaces = self.surfaces.as_ref();
        let mut hand_on = passed.map(|passed| {
            move |frame: StreamFrame, next: MediaTime| {
                let from = frame.facts.pts.ticks().saturating_sub(slack);
                if let Ok(frame) = source_frame(frame, surfaces) {
                    passed(PassedFrame {
                        frame,
                        shown: from..next.ticks().saturating_sub(slack),
                    });
                }
            }
        });
        let hand_on = hand_on
            .as_mut()
            .map(|hand_on| hand_on as &mut dyn FnMut(StreamFrame, MediaTime));
        let same_keyframe = entry.same_keyframe_until.is_some_and(|until| time <= until);
        let decoded = match entry.last.take() {
            Some((previous, frame))
                if crate::cursor::decodes_on(previous, time)
                    || (same_keyframe && previous <= time) =>
            {
                decode_forward(
                    stream,
                    time,
                    (Some(frame), entry.reached, &mut entry.following),
                    cancel,
                    hand_on,
                )
            }
            None if same_keyframe => decode_forward(
                stream,
                time,
                (None, true, &mut entry.following),
                cancel,
                hand_on,
            ),
            _ => {
                entry.following = None;
                stream
                    .seek_passing(time, cancel, hand_on)
                    .map_err(|error| Stopped::seeking(stream, &error))
            }
        };
        let frame = decoded.map_err(|stopped| entry.stop(time, stopped, cancel.is_cancelled()))?;
        entry.last = Some((time, frame.clone()));
        entry.reached = false;
        entry.same_keyframe_until = None;
        source_frame(frame, self.surfaces.as_ref()).map(Some)
    }
}

impl<F> SourceFrames for StreamSources<F>
where
    F: FnMut(&SourceId) -> Result<SourceStream, String>,
{
    fn frame(
        &mut self,
        need: &FrameNeed,
        index: u64,
        cancel: &CancelToken,
    ) -> Result<Option<SourceFrame>, String> {
        self.frame_with(need, index, cancel, None)
    }

    fn frame_passing(
        &mut self,
        need: &FrameNeed,
        index: u64,
        cancel: &CancelToken,
        passed: &mut dyn FnMut(PassedFrame),
    ) -> Result<Option<SourceFrame>, String> {
        self.frame_with(need, index, cancel, Some(passed))
    }

    fn following(
        &mut self,
        need: &FrameNeed,
        index: u64,
        cancel: &CancelToken,
    ) -> Result<Option<SourceFrame>, String> {
        let cursor = decode_cursor_key(need);
        #[cfg(not(feature = "providers"))]
        let _ = index;
        #[cfg(feature = "providers")]
        if let Some(providers) = self
            .providers
            .as_ref()
            .filter(|providers| providers.supplies(&need.source_id))
        {
            let shown = providers
                .frame(&cursor, need.media_time, index)
                .map_err(|error| error.to_string())?;
            return providers
                .following_watched(&cursor, &shown, index, None::<&crate::providers::Unwatched>)
                .map(|frame| frame.map(|frame| SourceFrame::Cpu(Arc::new(frame))))
                .map_err(|error| error.to_string());
        }
        let Some(entry) = self.streams.get_mut(&cursor) else {
            return Ok(None);
        };
        let SourceStream::Video(stream) = &mut entry.stream else {
            return Ok(None);
        };
        if !matches!(entry.last, Some((time, _)) if time == need.media_time) {
            return Ok(None);
        }
        if entry.following.is_none()
            && stream
                .peek_pts(cancel)
                .map_err(|error| error.to_string())?
                .is_some()
        {
            entry.following = stream.next(cancel).map_err(|error| error.to_string())?;
        }
        entry
            .following
            .clone()
            .map(|frame| source_frame(frame, self.surfaces.as_ref()))
            .transpose()
    }

    fn release_finished(&mut self, time: MediaTime) {
        if let Some(reads) = &self.reads {
            let open = self.streams.len();
            self.streams
                .retain(|cursor, _| !reads.finished(cursor, time));
            if self.streams.len() < open {
                self.collect_surfaces();
            }
        }
    }

    fn held_bytes(&self) -> u64 {
        let mut stills = HashSet::new();
        self.streams
            .values()
            .map(|cursor| match &cursor.stream {
                SourceStream::Video(stream) => {
                    stream.lookahead_bytes()
                        + cursor
                            .last
                            .as_ref()
                            .map_or(0, |(_, frame)| frame.retained_bytes())
                        + cursor
                            .following
                            .as_ref()
                            .map_or(0, StreamFrame::retained_bytes)
                }
                SourceStream::Still(still) if stills.insert(Arc::as_ptr(still)) => still
                    .planes
                    .iter()
                    .map(|plane| plane.bytes.len() as u64)
                    .sum(),
                SourceStream::Still(_) | SourceStream::AudioOnly => 0,
            })
            .sum()
    }
}

fn source_frame(
    frame: StreamFrame,
    surfaces: Option<&Arc<dyn SurfaceImport>>,
) -> Result<SourceFrame, String> {
    match frame.image {
        BackendImage::Surface(lease) => {
            let import = surfaces.ok_or_else(|| {
                "the decoder produced a GPU surface, and nothing here imports it".to_owned()
            })?;
            Ok(SourceFrame::Surface(SurfaceFrame {
                facts: frame.facts,
                lease,
                import: Arc::clone(import),
            }))
        }
        BackendImage::Cpu { .. } => frame
            .to_cpu()
            .map(|cpu| SourceFrame::Cpu(Arc::new(cpu)))
            .ok_or_else(|| "a CPU frame without planes".to_owned()),
    }
}

struct Stopped {
    error: String,
    reached: Option<StreamFrame>,
    sought: bool,
}

impl Stopped {
    fn seeking(stream: &mut crate::video_stream::VideoStream, error: &DecodeError) -> Self {
        Self {
            error: error.to_string(),
            reached: stream.take_passed(),
            sought: true,
        }
    }
}

/// The frame shown at `time`, decoding forward from where `stream` is; `previous` is the frame it
/// last answered, still shown when no later frame is due. That holds for a `previous` later than
/// `time` too: a seek before the stream's first frame answers that frame, shown until it is due.
fn decode_forward(
    stream: &mut crate::video_stream::VideoStream,
    time: MediaTime,
    (previous, unanswered, following): (Option<StreamFrame>, bool, &mut Option<StreamFrame>),
    cancel: &CancelToken,
    mut passed: Option<&mut dyn FnMut(StreamFrame, MediaTime)>,
) -> Result<StreamFrame, Stopped> {
    let deadline = time.presentation_deadline(stream.presentation_slack());
    let mut shown = previous;
    let mut handed_on = !unanswered;
    let mut pass = |before: Option<StreamFrame>, after: Option<&StreamFrame>| {
        let answered = std::mem::replace(&mut handed_on, false);
        if let (false, Some(passed), Some(before), Some(after)) =
            (answered, passed.as_deref_mut(), before, after)
            && before.facts.pts < after.facts.pts
        {
            passed(before, after.facts.pts);
        }
    };
    if let Some(kept) = following.take_if(|kept| kept.facts.pts <= deadline) {
        let before = shown.replace(kept);
        pass(before, shown.as_ref());
    }
    while following.is_none() {
        let due = match stream.peek_pts(cancel) {
            Ok(pts) => pts.is_some_and(|pts| pts <= deadline),
            Err(error) => {
                return Err(Stopped {
                    error: error.to_string(),
                    reached: shown,
                    sought: false,
                });
            }
        };
        if !due {
            break;
        }
        match stream.next(cancel) {
            Ok(next) => {
                let before = std::mem::replace(&mut shown, next);
                pass(before, shown.as_ref());
            }
            Err(error) => {
                return Err(Stopped {
                    error: error.to_string(),
                    reached: shown,
                    sought: false,
                });
            }
        }
    }
    match shown {
        Some(frame) => Ok(frame),
        None => stream
            .seek_passing(time, cancel, passed)
            .map_err(|error| Stopped::seeking(stream, &error)),
    }
}

#[cfg(test)]
#[path = "run_tests.rs"]
mod tests;