Skip to main content

alpha2_host_core/export/
run.rs

1//! The export loop: frame needs in, decoded and prepared frames into the store, rendered planes
2//! out to the encoder.
3
4use std::collections::{BTreeMap, HashMap, HashSet};
5use std::sync::{Arc, Weak};
6
7use alpha2_engine::ExportStepTimings;
8use alpha2_engine::{
9    EngineProject, ExportPlaneStep, Exporter, FrameProvider, FramesWithText, TextTextures,
10};
11use alpha2_eval::FrameNeed;
12use alpha2_media::{CancelToken, DecodedVideoFrame, EncodeError, PixelLayout, SourceId};
13use alpha2_render::{
14    ColorPolicy, CpuRenderer, CpuSource, Nv12PlaneTargets, PlaneTarget, RenderSize, Renderer,
15};
16use alpha2_time::MediaTime;
17
18use super::budget::FrameBudget;
19use super::prepare::{GpuSource, SurfaceImport, prepare_cpu, prepare_gpu};
20use crate::cursor::{CursorReads, DecodeCursorKey, decode_cursor_key};
21use crate::encode::{LentBuffer, PlaneBuffer};
22use crate::video_stream::{BackendImage, DroppedLayer, FrameFacts, StreamFrame, SurfaceLease};
23use alpha2_engine::frame_store::FrameStore;
24
25/// Steps an export may wait on the same frame, refilling between them, before it fails: a frame
26/// still missing after this many refills will not arrive.
27pub const MAX_EXPORT_REFILLS: u32 = 4;
28
29/// The renderer an export draws with.
30#[derive(Clone, Copy)]
31pub enum ExportRenderer<'a> {
32    /// The GPU renderer.
33    Gpu(&'a Renderer),
34    /// The CPU renderer.
35    Cpu(&'a CpuRenderer),
36}
37
38/// A decoded source frame: planes in memory, or a platform surface the GPU renderer imports.
39#[derive(Clone, Debug)]
40pub enum SourceFrame {
41    /// Planes in memory, for either renderer.
42    Cpu(Arc<DecodedVideoFrame>),
43    /// A decoder surface, for the GPU renderer only.
44    Surface(SurfaceFrame),
45}
46
47/// A decoder surface and the import that turns it into a GPU source.
48#[derive(Clone)]
49pub struct SurfaceFrame {
50    /// The frame's facts.
51    pub facts: FrameFacts,
52    /// The surface, held until the frame is prepared.
53    pub lease: Arc<dyn SurfaceLease>,
54    /// Prepares the surface for the GPU renderer.
55    pub import: Arc<dyn SurfaceImport>,
56}
57
58impl std::fmt::Debug for SurfaceFrame {
59    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        formatter
61            .debug_struct("SurfaceFrame")
62            .field("facts", &self.facts)
63            .field("lease", &self.lease)
64            .finish_non_exhaustive()
65    }
66}
67
68/// Decoded frames of the project's sources, by need.
69pub trait SourceFrames {
70    /// The decoded frame `need` of output frame `index` shows: the frame presented at its media
71    /// time; `None` for an audio source, which audio clips name but nothing draws.
72    ///
73    /// # Errors
74    /// A source that cannot be opened or decoded there, with the reason.
75    fn frame(
76        &mut self,
77        need: &FrameNeed,
78        index: u64,
79        cancel: &CancelToken,
80    ) -> Result<Option<SourceFrame>, String>;
81
82    /// Lets go of what only frames before timeline `time` read; called before the frame at `time`
83    /// is decoded.
84    fn release_finished(&mut self, _time: MediaTime) {}
85
86    /// Bytes of decoded frames held outside the prepared-frame cache.
87    fn held_bytes(&self) -> u64 {
88        0
89    }
90}
91
92/// Where rendered pictures go: the video encoder.
93pub trait VideoSink {
94    /// Takes frame `index` at `time`, packed as `layout` in one buffer per plane.
95    ///
96    /// # Errors
97    /// An encoder or output failure.
98    fn write_video(
99        &mut self,
100        index: u64,
101        time: MediaTime,
102        layout: PixelLayout,
103        planes: &[PlaneBuffer],
104    ) -> Result<(), EncodeError>;
105
106    /// Finishes the frames the encoder holds, before the export waits. The default does nothing.
107    ///
108    /// # Errors
109    /// An encoder or output failure.
110    fn settle(&mut self) -> Result<(), EncodeError> {
111        Ok(())
112    }
113
114    /// The encoder's buffers to render frames into, when it lends them. The default lends none.
115    fn lender(&mut self) -> Option<&mut dyn SinkLender> {
116        None
117    }
118}
119
120/// A sink whose encoder lends its input buffers: the renderer draws a frame into one, and the
121/// sink encodes it.
122pub trait SinkLender {
123    /// A buffer for the next frame, waiting while the encoder is busy.
124    ///
125    /// # Errors
126    /// An encoder failure, or an encoder that stays busy.
127    fn lend(&mut self) -> Result<LentBuffer, EncodeError>;
128
129    /// Encodes frame `index` at `time`, drawn into `buffer`.
130    ///
131    /// # Errors
132    /// An encoder or output failure.
133    fn write_lent(
134        &mut self,
135        index: u64,
136        time: MediaTime,
137        buffer: LentBuffer,
138    ) -> Result<(), EncodeError>;
139}
140
141/// The luma and chroma render targets of a lent buffer, as the NV12 pack writes them.
142#[derive(Clone, Debug)]
143pub struct LentPlanes {
144    /// `R8Unorm`, at the output size.
145    pub luma: wgpu::TextureView,
146    /// `Rg8Unorm`, at half the output size each way.
147    pub chroma: wgpu::TextureView,
148}
149
150/// Makes lent encoder buffers render targets on the GPU renderer's device: the platform's half
151/// of rendering frames in place, as [`SurfaceImport`] is of decoding them.
152pub trait EncoderTargets {
153    /// The planes of `buffer` as render targets for a frame of `size`.
154    ///
155    /// # Errors
156    /// A buffer that cannot be a render target there; the export then reads frames back.
157    fn planes(&mut self, buffer: &LentBuffer, size: RenderSize) -> Result<LentPlanes, String>;
158
159    /// Waits until the GPU finished the frame rendered into `buffer`'s planes.
160    ///
161    /// # Errors
162    /// A wait that failed or ran out of time.
163    fn finished(&mut self, buffer: &LentBuffer) -> Result<(), String>;
164}
165
166/// Why an export stopped.
167#[derive(Debug)]
168pub enum ExportError {
169    /// The caller cancelled.
170    Cancelled,
171    /// A source could not be decoded.
172    Source {
173        /// The source.
174        source: SourceId,
175        /// Why.
176        reason: String,
177    },
178    /// A frame's sources never arrived after [`MAX_EXPORT_REFILLS`] refills.
179    Stalled {
180        /// The frame's timeline time.
181        time: MediaTime,
182        /// The sources still missing.
183        missing: Vec<SourceId>,
184    },
185    /// The engine failed to evaluate or render.
186    Render(String),
187    /// The encoder or output failed.
188    Encode(EncodeError),
189}
190
191impl std::fmt::Display for ExportError {
192    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        match self {
194            Self::Cancelled => write!(formatter, "the export was cancelled"),
195            Self::Source { source, reason } => write!(formatter, "source {source}: {reason}"),
196            Self::Stalled { time, missing } => write!(
197                formatter,
198                "frame at {} ticks still lacks {} after {MAX_EXPORT_REFILLS} refills",
199                time.ticks(),
200                missing
201                    .iter()
202                    .map(SourceId::as_str)
203                    .collect::<Vec<_>>()
204                    .join(", ")
205            ),
206            Self::Render(reason) => write!(formatter, "{reason}"),
207            Self::Encode(error) => write!(formatter, "{error}"),
208        }
209    }
210}
211
212impl std::error::Error for ExportError {}
213
214/// Prepared frames for whichever renderer runs.
215/// Decoded source frames prepared for one renderer, kept within a byte budget: what an export or a
216/// preview renders from.
217pub enum SourceFrameCache {
218    /// Frames uploaded for the GPU renderer.
219    Gpu(FrameStore<GpuSource>),
220    /// Frames converted for the CPU renderer.
221    Cpu(FrameStore<CpuSource>),
222}
223
224impl SourceFrameCache {
225    /// An empty cache for `renderer`, keeping up to `bytes` of frames.
226    #[must_use]
227    pub fn for_renderer(renderer: ExportRenderer<'_>, bytes: u64) -> Self {
228        match renderer {
229            ExportRenderer::Gpu(_) => {
230                Self::Gpu(FrameStore::sized(GpuSource::retained_bytes, bytes))
231            }
232            ExportRenderer::Cpu(_) => {
233                Self::Cpu(FrameStore::sized(CpuSource::retained_bytes, bytes))
234            }
235        }
236    }
237
238    /// Sets the cache's budget to `budget` less the `held` bytes the sources keep, evicting at once
239    /// to fit. It never goes below the last output frame's working set, so a budget lowered under
240    /// memory pressure still lets the next frame of the same shape render.
241    pub fn follow(&mut self, budget: &FrameBudget, held: u64) {
242        let bytes = budget.bytes().saturating_sub(held);
243        match self {
244            Self::Gpu(store) => {
245                store.set_video_byte_budget(bytes.max(store.last_working_set_bytes()));
246            }
247            Self::Cpu(store) => {
248                store.set_video_byte_budget(bytes.max(store.last_working_set_bytes()));
249            }
250        }
251    }
252
253    /// The frames, for the renderer.
254    #[must_use]
255    pub fn provider(&self) -> &dyn FrameProvider {
256        match self {
257            Self::Gpu(store) => store,
258            Self::Cpu(store) => store,
259        }
260    }
261
262    /// Decodes and prepares every frame `needs` (of output frame `index`) names that the cache
263    /// does not hold, and keeps them until [`Self::unpin`].
264    ///
265    /// # Errors
266    /// A source that cannot be decoded or prepared, or one past the budget.
267    pub fn fill(
268        &mut self,
269        renderer: ExportRenderer<'_>,
270        size: RenderSize,
271        color: ColorPolicy,
272        (index, needs): (u64, &[FrameNeed]),
273        sources: &mut dyn SourceFrames,
274        cancel: &CancelToken,
275    ) -> Result<(), ExportError> {
276        fill(self, renderer, size, color, (index, needs), sources, cancel)
277    }
278
279    /// Lets the frames the last [`Self::fill`] kept go when the budget needs room.
280    pub fn unpin(&mut self) {
281        match self {
282            Self::Gpu(store) => store.unpin(),
283            Self::Cpu(store) => store.unpin(),
284        }
285    }
286
287    fn pin(&mut self, keys: Vec<(String, i64)>) {
288        match self {
289            Self::Gpu(store) => store.pin(keys),
290            Self::Cpu(store) => store.pin(keys),
291        }
292    }
293
294    fn holds(&self, source: &str, time: i64) -> bool {
295        match self {
296            Self::Gpu(store) => store.get(source, time).is_some(),
297            Self::Cpu(store) => store.get(source, time).is_some(),
298        }
299    }
300}
301
302/// Renders every frame of `exporter` into `sink`, decoding sources through `sources`.
303///
304/// Frames wait for their sources and never repeat a late one, so output does not depend on
305/// decode timing. Decoded frames stay within `budget`, read before every frame. `before_frame`
306/// runs at the top of every turn with the sink (it may block, as a host's pause does), and
307/// `progress` is told after each frame. With the GPU renderer, `targets` and a sink that lends,
308/// frames are drawn into the encoder's buffers; once `targets` refuses one, the rest of the
309/// export reads frames back.
310///
311/// # Errors
312/// Cancellation, a source or render failure, a frame whose sources never arrive, or a sink
313/// failure.
314#[allow(clippy::too_many_arguments)]
315pub fn export_video(
316    snapshot: &EngineProject,
317    exporter: &mut Exporter,
318    (renderer, mut targets): (ExportRenderer<'_>, Option<&mut (dyn EncoderTargets + '_)>),
319    texts: &mut TextTextures,
320    sources: &mut dyn SourceFrames,
321    sink: &mut dyn VideoSink,
322    (budget, cancel): (&FrameBudget, &CancelToken),
323    before_frame: &mut dyn FnMut(&mut dyn VideoSink) -> Result<(), EncodeError>,
324    progress: &mut dyn FnMut(u64, u64),
325) -> Result<(), ExportError> {
326    let size = exporter
327        .render_size(snapshot)
328        .map_err(|error| ExportError::Render(error.to_string()))?;
329    let color = alpha2_engine::color_policy(&snapshot.project().settings.color);
330    let mut store = SourceFrameCache::for_renderer(renderer, budget.bytes());
331    let layout = exporter.pixels();
332    let mut planes = plane_buffers(layout, size);
333    let mut refills = 0;
334    let mut kept: Option<LentBuffer> = None;
335    loop {
336        before_frame(sink).map_err(ExportError::Encode)?;
337        if cancel.is_cancelled() {
338            return Err(ExportError::Cancelled);
339        }
340        let needs = exporter
341            .prefetch_needs(snapshot, 1)
342            .map_err(|error| ExportError::Render(error.to_string()))?;
343        let Some(frame) = needs.first() else {
344            return Ok(());
345        };
346        sources.release_finished(frame.time);
347        store.follow(budget, sources.held_bytes());
348        fill(
349            &mut store,
350            renderer,
351            size,
352            color,
353            (frame.index, &frame.needs),
354            sources,
355            cancel,
356        )?;
357        if let Some(time) = exporter.pending_time() {
358            let upload: &dyn alpha2_engine::TextUpload = match renderer {
359                ExportRenderer::Gpu(renderer) => renderer,
360                ExportRenderer::Cpu(renderer) => renderer,
361            };
362            texts
363                .prepare_at(upload, snapshot, time, size)
364                .map_err(|error| ExportError::Render(error.to_string()))?;
365        }
366        let provider = FramesWithText::new(store.provider(), texts);
367        let lent = match (renderer, targets.as_deref_mut(), sink.lender()) {
368            (ExportRenderer::Gpu(gpu), Some(lending), Some(lender)) => Some(render_lent(
369                (snapshot, exporter, gpu, &provider, size),
370                lending,
371                lender,
372                &mut kept,
373            )?),
374            _ => None,
375        };
376        let (step, buffer) = match lent {
377            Some(LentStep::Drawn(step, buffer)) => (step, Some(buffer)),
378            refused => {
379                if matches!(refused, Some(LentStep::Refused)) {
380                    targets = None;
381                }
382                let step = render_readback(snapshot, exporter, renderer, &provider, &mut planes)?;
383                (step, None)
384            }
385        };
386        match step {
387            ExportPlaneStep::Rendered { index, time } => {
388                refills = 0;
389                store.unpin();
390                match buffer {
391                    Some(buffer) => write_lent(targets.as_deref_mut(), sink, index, time, buffer)?,
392                    None => sink
393                        .write_video(index, time, layout, &planes)
394                        .map_err(ExportError::Encode)?,
395                }
396                let done = exporter.progress();
397                progress(done.completed, done.total);
398            }
399            ExportPlaneStep::Waiting {
400                time,
401                missing_sources,
402            } => {
403                kept = buffer;
404                refills += 1;
405                if refills > MAX_EXPORT_REFILLS {
406                    return Err(ExportError::Stalled {
407                        time,
408                        missing: missing_sources,
409                    });
410                }
411            }
412            ExportPlaneStep::Complete => return Ok(()),
413        }
414    }
415}
416
417fn plane_buffers(layout: PixelLayout, size: RenderSize) -> Vec<PlaneBuffer> {
418    layout
419        .planes(size.width, size.height)
420        .into_iter()
421        .map(|(width, height, bytes)| {
422            let stride = usize::try_from(width * bytes).unwrap_or(0);
423            PlaneBuffer {
424                bytes: vec![0; stride * usize::try_from(height).unwrap_or(0)],
425                stride,
426                width,
427                height,
428            }
429        })
430        .collect()
431}
432
433enum LentStep {
434    Drawn(ExportPlaneStep, LentBuffer),
435    Refused,
436}
437
438fn render_lent(
439    (snapshot, exporter, renderer, provider, size): (
440        &EngineProject,
441        &mut Exporter,
442        &Renderer,
443        &dyn FrameProvider,
444        RenderSize,
445    ),
446    targets: &mut (dyn EncoderTargets + '_),
447    lender: &mut dyn SinkLender,
448    kept: &mut Option<LentBuffer>,
449) -> Result<LentStep, ExportError> {
450    let buffer = match kept.take() {
451        Some(buffer) => buffer,
452        None => lender.lend().map_err(ExportError::Encode)?,
453    };
454    let Ok(planes) = targets.planes(&buffer, size) else {
455        return Ok(LentStep::Refused);
456    };
457    let step = exporter
458        .render_next_nv12_timed(
459            snapshot,
460            renderer,
461            provider,
462            Nv12PlaneTargets {
463                luma: &planes.luma,
464                chroma: &planes.chroma,
465            },
466            &mut ExportStepTimings::default(),
467        )
468        .map_err(|error| ExportError::Render(error.to_string()))?;
469    Ok(LentStep::Drawn(step, buffer))
470}
471
472fn render_readback(
473    snapshot: &EngineProject,
474    exporter: &mut Exporter,
475    renderer: ExportRenderer<'_>,
476    provider: &dyn FrameProvider,
477    planes: &mut [PlaneBuffer],
478) -> Result<ExportPlaneStep, ExportError> {
479    let mut targets = planes
480        .iter_mut()
481        .map(|plane| PlaneTarget::new(&mut plane.bytes, plane.stride))
482        .collect::<Vec<_>>();
483    match renderer {
484        ExportRenderer::Gpu(renderer) => {
485            exporter.render_next_into_planes(snapshot, renderer, provider, &mut targets, None)
486        }
487        ExportRenderer::Cpu(renderer) => {
488            exporter.render_next_into_planes(snapshot, renderer, provider, &mut targets, None)
489        }
490    }
491    .map_err(|error| ExportError::Render(error.to_string()))
492}
493
494fn write_lent(
495    targets: Option<&mut (dyn EncoderTargets + '_)>,
496    sink: &mut dyn VideoSink,
497    index: u64,
498    time: MediaTime,
499    buffer: LentBuffer,
500) -> Result<(), ExportError> {
501    let (Some(targets), Some(lender)) = (targets, sink.lender()) else {
502        return Err(ExportError::Render(
503            "a frame drawn into a lent buffer lost its lender".into(),
504        ));
505    };
506    targets.finished(&buffer).map_err(ExportError::Render)?;
507    lender
508        .write_lent(index, time, buffer)
509        .map_err(ExportError::Encode)
510}
511
512/// Decodes and prepares every frame `needs` names that the store does not hold, pinning them.
513fn fill(
514    store: &mut SourceFrameCache,
515    renderer: ExportRenderer<'_>,
516    size: RenderSize,
517    color: ColorPolicy,
518    (index, needs): (u64, &[FrameNeed]),
519    sources: &mut dyn SourceFrames,
520    cancel: &CancelToken,
521) -> Result<(), ExportError> {
522    let keys = needs
523        .iter()
524        .map(|need| (need.source_id.as_str().to_owned(), need.media_time.ticks()))
525        .collect::<Vec<_>>();
526    store.pin(keys);
527    let mut done = HashSet::new();
528    for need in needs {
529        let key = (need.source_id.as_str().to_owned(), need.media_time.ticks());
530        if !done.insert(key.clone()) || store.holds(&key.0, key.1) {
531            continue;
532        }
533        let failed = |reason: String| ExportError::Source {
534            source: need.source_id.clone(),
535            reason,
536        };
537        let Some(frame) = sources.frame(need, index, cancel).map_err(failed)? else {
538            continue;
539        };
540        let inserted = match (store as &mut SourceFrameCache, renderer, frame) {
541            (
542                SourceFrameCache::Gpu(store),
543                ExportRenderer::Gpu(renderer),
544                SourceFrame::Cpu(frame),
545            ) => {
546                let prepared = prepare_gpu(renderer, size, color, &frame).map_err(failed)?;
547                store.insert(key, prepared).map(|_| ())
548            }
549            (
550                SourceFrameCache::Gpu(store),
551                ExportRenderer::Gpu(renderer),
552                SourceFrame::Surface(surface),
553            ) => {
554                let prepared = surface
555                    .import
556                    .prepare(renderer, size, color, &surface.facts, &surface.lease)
557                    .map_err(failed)?;
558                store.insert(key, prepared).map(|_| ())
559            }
560            (
561                SourceFrameCache::Cpu(store),
562                ExportRenderer::Cpu(renderer),
563                SourceFrame::Cpu(frame),
564            ) => {
565                let prepared = prepare_cpu(renderer, size, color, frame).map_err(failed)?;
566                store.insert(key, prepared).map(|_| ())
567            }
568            (SourceFrameCache::Cpu(_), ExportRenderer::Cpu(_), SourceFrame::Surface(_)) => {
569                return Err(failed(
570                    "the decoder produced a GPU surface, which the CPU renderer cannot draw".into(),
571                ));
572            }
573            _ => unreachable!("the store matches the renderer"),
574        };
575        inserted.map_err(|over| {
576            failed(format!(
577                "the frame's sources need {} bytes, over the {} byte budget",
578                over.needed(),
579                over.budget
580            ))
581        })?;
582    }
583    Ok(())
584}
585
586/// Opens one [`crate::video_stream::VideoStream`] per cursor and keeps decoding forward while
587/// requests stay within the sequential gap, seeking otherwise.
588///
589/// A cursor its reads say is finished is closed, at most a set number of video streams stay open,
590/// and one decoded still serves every cursor of its source. A closed cursor reopens with a seek.
591pub struct StreamSources<F> {
592    open: F,
593    streams: HashMap<DecodeCursorKey, Cursor>,
594    /// When each cursor reads, which closes a finished one.
595    reads: Option<CursorReads>,
596    /// Video streams open at most, beyond the ones the current output frame reads.
597    session_limit: Option<usize>,
598    /// Each still source's decoded picture while a cursor holds it.
599    stills: HashMap<SourceId, Weak<DecodedVideoFrame>>,
600    /// Sources that opened as something other than a video stream.
601    not_video: HashSet<SourceId>,
602    /// What each source's pictures go without, noted when it first opens.
603    dropped: BTreeMap<SourceId, DroppedLayer>,
604    /// Prepares the decoder surfaces the streams produce.
605    surfaces: Option<Arc<dyn SurfaceImport>>,
606    /// Supplies the extension sources.
607    #[cfg(feature = "providers")]
608    providers: Option<Arc<crate::providers::ProviderMedia>>,
609}
610
611/// What a source decodes from: a video stream, or a still shown at every time.
612pub enum SourceStream {
613    /// A video track's frames.
614    Video(Box<crate::video_stream::VideoStream>),
615    /// One picture.
616    Still(Arc<DecodedVideoFrame>),
617    /// Audio alone: audio clips name the source, but it has no pictures.
618    AudioOnly,
619}
620
621/// One cursor's source, the time it was last asked for and the frame it answered, and the output
622/// frame that last read it.
623struct Cursor {
624    stream: SourceStream,
625    last: Option<(MediaTime, StreamFrame)>,
626    used: u64,
627}
628
629impl<F> StreamSources<F>
630where
631    F: FnMut(&SourceId) -> Result<SourceStream, String>,
632{
633    /// Opens sources with `open`, a source's stream from the start.
634    pub fn new(open: F) -> Self {
635        Self {
636            open,
637            streams: HashMap::new(),
638            reads: None,
639            session_limit: None,
640            stills: HashMap::new(),
641            not_video: HashSet::new(),
642            dropped: BTreeMap::new(),
643            surfaces: None,
644            #[cfg(feature = "providers")]
645            providers: None,
646        }
647    }
648
649    /// Closes a cursor once `reads` say it reads nothing more ([`SourceFrames::release_finished`]).
650    /// A cursor `reads` does not know is never closed this way.
651    #[must_use]
652    pub fn with_reads(mut self, reads: CursorReads) -> Self {
653        self.reads = Some(reads);
654        self
655    }
656
657    /// Before opening a video stream while `limit` are open, closes the one read longest ago that
658    /// the current output frame does not read.
659    #[must_use]
660    pub fn with_session_limit(mut self, limit: usize) -> Self {
661        self.session_limit = Some(limit.max(1));
662        self
663    }
664
665    /// Video streams open now.
666    #[must_use]
667    pub fn open_streams(&self) -> usize {
668        self.streams
669            .values()
670            .filter(|cursor| matches!(cursor.stream, SourceStream::Video(_)))
671            .count()
672    }
673
674    /// Closes the least recently read video stream other than those output frame `index` read,
675    /// while `limit` or more are open.
676    fn make_room(&mut self, limit: usize, index: u64) {
677        while self.open_streams() >= limit {
678            let Some(oldest) = self
679                .streams
680                .iter()
681                .filter(|(_, cursor)| {
682                    cursor.used != index && matches!(cursor.stream, SourceStream::Video(_))
683                })
684                .min_by_key(|(_, cursor)| cursor.used)
685                .map(|(key, _)| key.clone())
686            else {
687                return;
688            };
689            self.streams.remove(&oldest);
690            self.collect_surfaces();
691        }
692    }
693
694    /// Lets the surface import free what the closed streams' frames held.
695    fn collect_surfaces(&self) {
696        if let Some(import) = &self.surfaces {
697            import.collect();
698        }
699    }
700
701    /// Opens `source`'s stream, reusing a still another cursor holds.
702    fn open_stream(&mut self, source: &SourceId, index: u64) -> Result<SourceStream, String> {
703        if let Some(still) = self.stills.get(source).and_then(Weak::upgrade) {
704            return Ok(SourceStream::Still(still));
705        }
706        if let Some(limit) = self.session_limit
707            && !self.not_video.contains(source)
708        {
709            self.make_room(limit, index);
710        }
711        let stream = (self.open)(source)?;
712        match &stream {
713            SourceStream::Still(still) => {
714                self.stills.insert(source.clone(), Arc::downgrade(still));
715                self.not_video.insert(source.clone());
716            }
717            SourceStream::AudioOnly => {
718                self.not_video.insert(source.clone());
719            }
720            SourceStream::Video(video) => {
721                if let Some(dropped) = video.dropped_layer() {
722                    self.dropped
723                        .entry(source.clone())
724                        .or_insert_with(|| dropped.clone());
725                }
726            }
727        }
728        Ok(stream)
729    }
730
731    /// What the pictures of each source opened so far go without, one entry per source.
732    #[must_use]
733    pub const fn dropped_layers(&self) -> &BTreeMap<SourceId, DroppedLayer> {
734        &self.dropped
735    }
736
737    /// Prepares the decoder surfaces the streams produce with `import`; without it a surface
738    /// frame fails its source.
739    #[must_use]
740    pub fn with_surface_import(mut self, import: Arc<dyn SurfaceImport>) -> Self {
741        self.surfaces = Some(import);
742        self
743    }
744
745    /// Also takes the frames of the sources `providers` supplies from it.
746    #[cfg(feature = "providers")]
747    #[must_use]
748    pub fn with_providers(mut self, providers: Arc<crate::providers::ProviderMedia>) -> Self {
749        self.providers = Some(providers);
750        self
751    }
752}
753
754impl<F> SourceFrames for StreamSources<F>
755where
756    F: FnMut(&SourceId) -> Result<SourceStream, String>,
757{
758    fn frame(
759        &mut self,
760        need: &FrameNeed,
761        index: u64,
762        cancel: &CancelToken,
763    ) -> Result<Option<SourceFrame>, String> {
764        let cursor = decode_cursor_key(need);
765        // Only provider sources keep frames by output frame.
766        #[cfg(not(feature = "providers"))]
767        let _ = index;
768        #[cfg(feature = "providers")]
769        if let Some(providers) = self
770            .providers
771            .as_ref()
772            .filter(|providers| providers.supplies(&need.source_id))
773        {
774            return providers
775                .frame(&cursor, need.media_time, index)
776                .map(|frame| Some(SourceFrame::Cpu(Arc::new(frame))))
777                .map_err(|error| error.to_string());
778        }
779        if !self.streams.contains_key(&cursor) {
780            let stream = self.open_stream(&need.source_id, index)?;
781            self.streams.insert(
782                cursor.clone(),
783                Cursor {
784                    stream,
785                    last: None,
786                    used: index,
787                },
788            );
789        }
790        let entry = self
791            .streams
792            .get_mut(&cursor)
793            .ok_or_else(|| "the stream was not opened".to_owned())?;
794        entry.used = index;
795        let stream = match &mut entry.stream {
796            SourceStream::Still(frame) => return Ok(Some(SourceFrame::Cpu(Arc::clone(frame)))),
797            SourceStream::AudioOnly => return Ok(None),
798            SourceStream::Video(stream) => stream,
799        };
800        let time = need.media_time;
801        let frame = match entry.last.take() {
802            Some((previous, frame)) if crate::cursor::decodes_on(previous, time) => {
803                decode_forward(stream, time, Some(frame), cancel)?
804            }
805            _ => stream
806                .seek(time, cancel)
807                .map_err(|error| error.to_string())?,
808        };
809        entry.last = Some((time, frame.clone()));
810        source_frame(frame, self.surfaces.as_ref()).map(Some)
811    }
812
813    fn release_finished(&mut self, time: MediaTime) {
814        if let Some(reads) = &self.reads {
815            let open = self.streams.len();
816            self.streams
817                .retain(|cursor, _| !reads.finished(cursor, time));
818            if self.streams.len() < open {
819                self.collect_surfaces();
820            }
821        }
822    }
823
824    fn held_bytes(&self) -> u64 {
825        let mut stills = HashSet::new();
826        self.streams
827            .values()
828            .map(|cursor| match &cursor.stream {
829                SourceStream::Video(stream) => {
830                    stream.lookahead_bytes()
831                        + cursor
832                            .last
833                            .as_ref()
834                            .map_or(0, |(_, frame)| frame.retained_bytes())
835                }
836                SourceStream::Still(still) if stills.insert(Arc::as_ptr(still)) => still
837                    .planes
838                    .iter()
839                    .map(|plane| plane.bytes.len() as u64)
840                    .sum(),
841                SourceStream::Still(_) | SourceStream::AudioOnly => 0,
842            })
843            .sum()
844    }
845}
846
847fn source_frame(
848    frame: StreamFrame,
849    surfaces: Option<&Arc<dyn SurfaceImport>>,
850) -> Result<SourceFrame, String> {
851    match frame.image {
852        BackendImage::Surface(lease) => {
853            let import = surfaces.ok_or_else(|| {
854                "the decoder produced a GPU surface, and nothing here imports it".to_owned()
855            })?;
856            Ok(SourceFrame::Surface(SurfaceFrame {
857                facts: frame.facts,
858                lease,
859                import: Arc::clone(import),
860            }))
861        }
862        BackendImage::Cpu { .. } => frame
863            .to_cpu()
864            .map(|cpu| SourceFrame::Cpu(Arc::new(cpu)))
865            .ok_or_else(|| "a CPU frame without planes".to_owned()),
866    }
867}
868
869/// The frame shown at `time`, decoding forward from where `stream` is; `previous` is the frame it
870/// last answered, still shown when no later frame is due. That holds for a `previous` later than
871/// `time` too: a seek before the stream's first frame answers that frame, shown until it is due.
872fn decode_forward(
873    stream: &mut crate::video_stream::VideoStream,
874    time: MediaTime,
875    previous: Option<StreamFrame>,
876    cancel: &CancelToken,
877) -> Result<StreamFrame, String> {
878    let deadline = time.presentation_deadline(stream.presentation_slack());
879    let mut shown = previous;
880    while let Some(pts) = stream.peek_pts(cancel).map_err(|error| error.to_string())?
881        && pts <= deadline
882    {
883        shown = stream.next(cancel).map_err(|error| error.to_string())?;
884    }
885    match shown {
886        Some(frame) => Ok(frame),
887        None => stream.seek(time, cancel).map_err(|error| error.to_string()),
888    }
889}
890
891#[cfg(test)]
892#[path = "run_tests.rs"]
893mod tests;