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