Skip to main content

spoolframe_protocol/
plan_summary.rs

1//! A playback plan as a player's info panel shows it: what kind of play
2//! it is, and what plays, flat ([`PlaybackPlan::summary`]).
3
4use spoolframe_types::{AudioCodec, Delivery, SubtitleFormat, VideoCodec};
5
6use crate::playback::{
7    AudioAction, ConvertedVideo, PlannedSubtitle, PlaybackPlan, Rung, SubtitleAction,
8    SubtitleDelivery,
9};
10
11/// What kind of play a plan is.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
14pub enum PlanKind {
15    /// The file as it is.
16    Direct,
17    /// Converted with the picture and sound copied: a new container,
18    /// nothing encoded. A text subtitle converted (to WebVTT for HLS) or
19    /// read from a bitmap one (OCR) is still a remux: the picture and
20    /// sound are the file's, and OCR takes the server little CPU. A
21    /// ladder with an encoded rung is not one.
22    Remux,
23    /// Converted with the video or audio encoded, or a subtitle burned in
24    /// (which encodes the video).
25    Convert,
26    /// The client cannot play this selection: see `reasons`.
27    Unsupported,
28    /// A plan kind this build does not know.
29    Unknown,
30}
31
32/// The video that plays.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub struct VideoSummary {
35    pub codec: VideoCodec,
36    /// Into the output as it is: the file's own.
37    pub copied: bool,
38    /// Shown as Dolby Vision: a copied profile 5 or 8 stream.
39    pub dolby_vision: bool,
40    /// An encode's cap, bits per second; `None` for a copy, or the
41    /// encoder's own choice.
42    pub max_bitrate: Option<u64>,
43}
44
45/// The audio that plays.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct AudioSummary {
48    pub codec: AudioCodec,
49    /// The position of the track in the item's audio list.
50    pub index: u32,
51    /// Into the output (or played) as it is.
52    pub copied: bool,
53    /// An encode's channels; `None` for a copy, which keeps the file's.
54    pub channels: Option<u32>,
55    /// An encode's bits per second; `None` for a copy.
56    pub bitrate: Option<u64>,
57}
58
59/// How the picked subtitle is shown.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum SubtitleHow {
62    /// A stream of the file played as it is.
63    Embedded,
64    /// A separate file the client fetches whole.
65    External,
66    /// Into the output as it is.
67    Copy,
68    /// Converted to another text format into the output.
69    Convert,
70    /// A picture subtitle read as text, fetched whole.
71    Ocr,
72    /// Drawn into the video.
73    BurnIn,
74    /// A way this build does not know.
75    Unknown,
76}
77
78/// The subtitle that shows.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub struct SubtitleSummary {
81    /// The position of the track in the item's subtitle list.
82    pub index: u32,
83    pub how: SubtitleHow,
84    /// The format the client gets: the output's after a conversion or
85    /// a reading as text; the file's for a burn-in, which the client
86    /// never gets.
87    pub format: Option<SubtitleFormat>,
88}
89
90/// A plan, flat ([`PlaybackPlan::summary`]).
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct PlanSummary {
93    pub kind: PlanKind,
94    /// How a converted output is sent; `None` for the file as it is.
95    pub delivery: Option<Delivery>,
96    pub video: Option<VideoSummary>,
97    pub audio: Option<AudioSummary>,
98    pub subtitle: Option<SubtitleSummary>,
99    /// Why it is not played as it is, or why it cannot play.
100    pub reasons: Vec<String>,
101    /// The lines an encode outputs; `None` where the picture is the
102    /// file's own.
103    pub target_height: Option<u32>,
104    /// A ladder's heights, highest first; empty for one encode.
105    pub ladder_heights: Vec<u32>,
106    /// HDR mapped to SDR.
107    pub tone_mapped: bool,
108}
109
110/// The parts of a plan a player reads, by value.
111#[cfg_attr(feature = "uniffi", uniffi::export)]
112impl PlaybackPlan {
113    /// What kind of play it is ([`PlaybackPlan::summary`]'s).
114    pub fn kind(&self) -> PlanKind {
115        self.summary().kind
116    }
117
118    /// A converted plan's video: copied or encoded; `None` for any other
119    /// plan, or no video.
120    pub fn converted_video(&self) -> Option<ConvertedVideo> {
121        match self {
122            PlaybackPlan::Converted { video, .. } => *video,
123            _ => None,
124        }
125    }
126
127    /// What a converted plan does to the audio; `None` for any other
128    /// plan, or no audio.
129    pub fn audio_action(&self) -> Option<AudioAction> {
130        match self {
131            PlaybackPlan::Converted { audio, .. } => audio.map(|a| a.action),
132            _ => None,
133        }
134    }
135
136    /// What a converted plan does to the subtitle; `None` for any other
137    /// plan, or none picked.
138    pub fn subtitle_action(&self) -> Option<SubtitleAction> {
139        match self {
140            PlaybackPlan::Converted { subtitle, .. } => subtitle.map(|s| s.action),
141            _ => None,
142        }
143    }
144
145    /// The subtitle is drawn into the video: the player shows none of
146    /// its own, and turning it off plans again.
147    pub fn burns_in_subtitle(&self) -> bool {
148        matches!(self.subtitle_action(), Some(SubtitleAction::BurnIn { .. }))
149    }
150}
151
152/// [`PlaybackPlan`]'s borrowing reads, owned, for Swift and Kotlin under
153/// the same names.
154#[cfg(feature = "uniffi")]
155#[uniffi::export]
156impl PlaybackPlan {
157    /// [`PlaybackPlan::ladder`].
158    #[uniffi::method(name = "ladder")]
159    pub fn ladder_owned(&self) -> Vec<Rung> {
160        self.ladder().to_vec()
161    }
162
163    /// [`PlaybackPlan::source_codec`].
164    #[uniffi::method(name = "source_codec")]
165    pub fn source_codec_owned(&self) -> Option<String> {
166        self.source_codec().map(str::to_owned)
167    }
168}
169
170#[cfg_attr(feature = "uniffi", uniffi::export)]
171impl PlaybackPlan {
172    /// The lines the server encodes the picture to, for a quality
173    /// picker's "Auto (720p)"; `None` where the picture is the file's
174    /// own (a direct play, a copied video) or there is none.
175    pub fn encoded_height(&self) -> Option<u32> {
176        match self {
177            PlaybackPlan::Converted {
178                video: Some(ConvertedVideo::Encode { height, .. }),
179                ..
180            } => Some(*height),
181            _ => None,
182        }
183    }
184}
185
186impl PlaybackPlan {
187    /// The encodes an HLS player switches between, highest first; empty
188    /// for one encode, or a plan that isn't converted.
189    pub fn ladder(&self) -> &[Rung] {
190        match self {
191            PlaybackPlan::Converted { ladder, .. } => ladder,
192            _ => &[],
193        }
194    }
195
196    /// The plan as an info panel shows it. A remux is a converted plan
197    /// whose streams are all copied, as [`PlaybackPlan::Converted`]
198    /// says, with no encoded rung in its ladder.
199    pub fn summary(&self) -> PlanSummary {
200        match self {
201            PlaybackPlan::Direct {
202                video,
203                audio,
204                subtitle,
205                ..
206            } => PlanSummary {
207                kind: PlanKind::Direct,
208                delivery: None,
209                video: video.map(|codec| VideoSummary {
210                    codec,
211                    copied: true,
212                    dolby_vision: false,
213                    max_bitrate: None,
214                }),
215                audio: audio.map(|a| AudioSummary {
216                    codec: a.codec,
217                    index: a.index,
218                    copied: true,
219                    channels: None,
220                    bitrate: None,
221                }),
222                subtitle: subtitle.map(|s| direct_subtitle(&s)),
223                reasons: Vec::new(),
224                target_height: None,
225                ladder_heights: Vec::new(),
226                tone_mapped: false,
227            },
228            PlaybackPlan::Converted {
229                delivery,
230                video,
231                audio,
232                subtitle,
233                ladder,
234                reasons,
235                ..
236            } => {
237                let video_summary = video.and_then(|v| converted_video(&v));
238                let audio = audio.and_then(|a| match a.action {
239                    AudioAction::Copy { codec } => Some(AudioSummary {
240                        codec,
241                        index: a.index,
242                        copied: true,
243                        channels: None,
244                        bitrate: None,
245                    }),
246                    AudioAction::Encode {
247                        codec,
248                        channels,
249                        bitrate,
250                    } => Some(AudioSummary {
251                        codec,
252                        index: a.index,
253                        copied: false,
254                        channels: Some(channels),
255                        bitrate: Some(bitrate),
256                    }),
257                    AudioAction::Unknown => None,
258                });
259                let subtitle = subtitle.map(|s| {
260                    let (how, format) = match s.action {
261                        SubtitleAction::Copy { format } => (SubtitleHow::Copy, Some(format)),
262                        SubtitleAction::Convert { to, .. } => (SubtitleHow::Convert, Some(to)),
263                        SubtitleAction::BurnIn { format } => (SubtitleHow::BurnIn, Some(format)),
264                        SubtitleAction::Ocr { to, .. } => (SubtitleHow::Ocr, Some(to)),
265                        SubtitleAction::Unknown => (SubtitleHow::Unknown, None),
266                    };
267                    SubtitleSummary {
268                        index: s.index,
269                        how,
270                        format,
271                    }
272                });
273                let target_height = self.encoded_height();
274                let tone_mapped =
275                    matches!(video, Some(ConvertedVideo::Encode { tone_map: true, .. }));
276                let copies_video = video.is_none_or(|v| matches!(v, ConvertedVideo::Copy { .. }))
277                    && ladder
278                        .iter()
279                        .all(|r| !matches!(r.video, Some(ConvertedVideo::Encode { .. })));
280                let copies_audio = audio.is_none_or(|a| a.copied);
281                let burns_subtitle = subtitle.is_some_and(|s| s.how == SubtitleHow::BurnIn);
282                let kind = if copies_video && copies_audio && !burns_subtitle {
283                    PlanKind::Remux
284                } else {
285                    PlanKind::Convert
286                };
287                PlanSummary {
288                    kind,
289                    delivery: Some(*delivery),
290                    video: video_summary,
291                    audio,
292                    subtitle,
293                    reasons: reasons.clone(),
294                    target_height,
295                    ladder_heights: ladder.iter().map(|r| r.height).collect(),
296                    tone_mapped,
297                }
298            }
299            PlaybackPlan::Unsupported { reasons } => PlanSummary {
300                reasons: reasons.clone(),
301                ..empty(PlanKind::Unsupported)
302            },
303            PlaybackPlan::Unknown => empty(PlanKind::Unknown),
304        }
305    }
306}
307
308fn empty(kind: PlanKind) -> PlanSummary {
309    PlanSummary {
310        kind,
311        delivery: None,
312        video: None,
313        audio: None,
314        subtitle: None,
315        reasons: Vec::new(),
316        target_height: None,
317        ladder_heights: Vec::new(),
318        tone_mapped: false,
319    }
320}
321
322fn direct_subtitle(s: &PlannedSubtitle) -> SubtitleSummary {
323    let how = match s.delivery {
324        SubtitleDelivery::Embedded => SubtitleHow::Embedded,
325        SubtitleDelivery::External => SubtitleHow::External,
326        SubtitleDelivery::Unknown => SubtitleHow::Unknown,
327    };
328    SubtitleSummary {
329        index: s.index,
330        how,
331        format: Some(s.format),
332    }
333}
334
335fn converted_video(v: &ConvertedVideo) -> Option<VideoSummary> {
336    match *v {
337        ConvertedVideo::Copy {
338            codec,
339            dolby_vision,
340        } => Some(VideoSummary {
341            codec,
342            copied: true,
343            dolby_vision,
344            max_bitrate: None,
345        }),
346        ConvertedVideo::Encode {
347            codec, max_bitrate, ..
348        } => Some(VideoSummary {
349            codec,
350            copied: false,
351            dolby_vision: false,
352            max_bitrate,
353        }),
354        ConvertedVideo::Unknown => None,
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361    use crate::playback::{ConvertedAudio, ConvertedSubtitle, PlannedAudio, Rung};
362    use spoolframe_types::Container;
363
364    fn copy_video() -> ConvertedVideo {
365        ConvertedVideo::Copy {
366            codec: VideoCodec::Hevc,
367            dolby_vision: true,
368        }
369    }
370
371    fn encode_video(height: u32, tone_map: bool) -> ConvertedVideo {
372        ConvertedVideo::Encode {
373            codec: VideoCodec::H264,
374            height,
375            max_bitrate: Some(8_000_000),
376            tone_map,
377        }
378    }
379
380    fn copy_audio() -> ConvertedAudio {
381        ConvertedAudio {
382            index: 1,
383            action: AudioAction::Copy {
384                codec: AudioCodec::Aac,
385            },
386        }
387    }
388
389    fn converted(
390        video: Option<ConvertedVideo>,
391        audio: Option<ConvertedAudio>,
392        subtitle: Option<SubtitleAction>,
393        ladder: Vec<Rung>,
394    ) -> PlaybackPlan {
395        PlaybackPlan::Converted {
396            delivery: Delivery::Hls,
397            container: Container::Mp4,
398            video,
399            audio,
400            subtitle: subtitle.map(|action| ConvertedSubtitle { index: 2, action }),
401            ladder,
402            reasons: vec!["audio 1: dts not supported".into()],
403            source_codec: None,
404        }
405    }
406
407    fn rung(height: u32, video: Option<ConvertedVideo>) -> Rung {
408        Rung {
409            height,
410            max_bitrate: 1_000_000,
411            video,
412        }
413    }
414
415    /// A player reads a plan's parts without matching on it: a burned-in
416    /// subtitle over an encode in a ladder.
417    #[test]
418    fn a_plan_s_parts_read_by_value() {
419        let burn = SubtitleAction::BurnIn {
420            format: SubtitleFormat::Pgs,
421        };
422        let ladder = vec![rung(1080, None), rung(720, None)];
423        let plan = converted(
424            Some(encode_video(1080, false)),
425            Some(copy_audio()),
426            Some(burn),
427            ladder.clone(),
428        );
429        assert_eq!(
430            (
431                plan.kind(),
432                plan.converted_video(),
433                plan.audio_action(),
434                plan.subtitle_action(),
435                plan.burns_in_subtitle(),
436                plan.ladder(),
437            ),
438            (
439                PlanKind::Convert,
440                Some(encode_video(1080, false)),
441                Some(copy_audio().action),
442                Some(burn),
443                true,
444                ladder.as_slice(),
445            )
446        );
447    }
448
449    #[test]
450    fn a_direct_play_has_no_converted_parts() {
451        let plan = PlaybackPlan::Direct {
452            container: Container::Matroska,
453            video: Some(VideoCodec::Hevc),
454            audio: None,
455            subtitle: None,
456            source_codec: Some("hvc1.2.4.L153.B0".into()),
457        };
458        assert_eq!(
459            (
460                plan.kind(),
461                plan.converted_video(),
462                plan.subtitle_action(),
463                plan.burns_in_subtitle(),
464                plan.ladder().is_empty(),
465                plan.source_codec(),
466            ),
467            (
468                PlanKind::Direct,
469                None,
470                None,
471                false,
472                true,
473                Some("hvc1.2.4.L153.B0"),
474            )
475        );
476    }
477
478    #[test]
479    fn a_direct_play_is_the_files_own_streams() {
480        let plan = PlaybackPlan::Direct {
481            container: Container::Matroska,
482            video: Some(VideoCodec::Hevc),
483            audio: Some(PlannedAudio {
484                index: 0,
485                codec: AudioCodec::Eac3,
486            }),
487            subtitle: Some(PlannedSubtitle {
488                index: 3,
489                format: SubtitleFormat::Srt,
490                delivery: SubtitleDelivery::External,
491            }),
492            source_codec: None,
493        };
494        let s = plan.summary();
495        assert_eq!(s.kind, PlanKind::Direct);
496        assert_eq!(s.delivery, None);
497        assert!(
498            s.video
499                .is_some_and(|v| v.copied && v.codec == VideoCodec::Hevc)
500        );
501        assert_eq!(
502            s.audio,
503            Some(AudioSummary {
504                codec: AudioCodec::Eac3,
505                index: 0,
506                copied: true,
507                channels: None,
508                bitrate: None,
509            })
510        );
511        assert_eq!(
512            s.subtitle,
513            Some(SubtitleSummary {
514                index: 3,
515                how: SubtitleHow::External,
516                format: Some(SubtitleFormat::Srt),
517            })
518        );
519    }
520
521    #[test]
522    fn every_stream_copied_is_a_remux() {
523        let plan = converted(
524            Some(copy_video()),
525            Some(copy_audio()),
526            Some(SubtitleAction::Copy {
527                format: SubtitleFormat::Srt,
528            }),
529            Vec::new(),
530        );
531        let s = plan.summary();
532        assert_eq!(s.kind, PlanKind::Remux);
533        assert_eq!(s.delivery, Some(Delivery::Hls));
534        assert!(s.video.is_some_and(|v| v.copied && v.dolby_vision));
535        assert_eq!(s.target_height, None);
536    }
537
538    #[test]
539    fn audio_encoded_makes_it_a_conversion_with_its_channels_and_bitrate() {
540        let audio = ConvertedAudio {
541            index: 1,
542            action: AudioAction::Encode {
543                codec: AudioCodec::Aac,
544                channels: 6,
545                bitrate: 384_000,
546            },
547        };
548        let s = converted(Some(copy_video()), Some(audio), None, Vec::new()).summary();
549        assert_eq!(s.kind, PlanKind::Convert);
550        assert_eq!(
551            s.audio.map(|a| (a.copied, a.channels, a.bitrate)),
552            Some((false, Some(6), Some(384_000)))
553        );
554    }
555
556    #[test]
557    fn an_encode_says_its_height_and_whether_it_maps_hdr() {
558        let s = converted(Some(encode_video(1080, true)), None, None, Vec::new()).summary();
559        assert_eq!(s.kind, PlanKind::Convert);
560        assert_eq!(s.target_height, Some(1080));
561        assert!(s.tone_mapped);
562        assert!(
563            s.video
564                .is_some_and(|v| !v.copied && v.max_bitrate == Some(8_000_000))
565        );
566    }
567
568    #[test]
569    fn only_an_encode_has_a_height_of_its_own() {
570        assert_eq!(
571            converted(Some(encode_video(540, false)), None, None, vec![]).encoded_height(),
572            Some(540)
573        );
574        assert_eq!(
575            converted(Some(copy_video()), None, None, vec![]).encoded_height(),
576            None
577        );
578        let direct = PlaybackPlan::Direct {
579            container: Container::Matroska,
580            video: Some(VideoCodec::Hevc),
581            audio: None,
582            subtitle: None,
583            source_codec: None,
584        };
585        assert_eq!(direct.encoded_height(), None);
586    }
587
588    #[test]
589    fn a_ladder_lists_its_heights_highest_first() {
590        let ladder = vec![rung(1080, None), rung(720, None), rung(480, None)];
591        let s = converted(Some(encode_video(1080, false)), None, None, ladder).summary();
592        assert_eq!(s.ladder_heights, [1080, 720, 480]);
593        assert!(!s.tone_mapped);
594    }
595
596    #[test]
597    fn a_copy_with_encoded_rungs_under_it_is_not_a_remux() {
598        let ladder = vec![
599            rung(2160, None),
600            rung(1080, Some(encode_video(1080, false))),
601        ];
602        let s = converted(Some(copy_video()), Some(copy_audio()), None, ladder).summary();
603        assert_eq!(s.kind, PlanKind::Convert);
604        assert_eq!(s.target_height, None);
605    }
606
607    #[test]
608    fn a_subtitle_says_how_it_shows_and_in_what_format() {
609        let cases = [
610            (
611                SubtitleAction::Convert {
612                    from: SubtitleFormat::Srt,
613                    to: SubtitleFormat::WebVtt,
614                },
615                SubtitleHow::Convert,
616                SubtitleFormat::WebVtt,
617            ),
618            (
619                SubtitleAction::Ocr {
620                    from: SubtitleFormat::Pgs,
621                    to: SubtitleFormat::Srt,
622                },
623                SubtitleHow::Ocr,
624                SubtitleFormat::Srt,
625            ),
626            (
627                SubtitleAction::BurnIn {
628                    format: SubtitleFormat::Pgs,
629                },
630                SubtitleHow::BurnIn,
631                SubtitleFormat::Pgs,
632            ),
633        ];
634        for (action, how, format) in cases {
635            let s = converted(Some(copy_video()), None, Some(action), Vec::new()).summary();
636            assert_eq!(
637                s.subtitle,
638                Some(SubtitleSummary {
639                    index: 2,
640                    how,
641                    format: Some(format),
642                })
643            );
644            // Only a burn-in touches the picture.
645            let kind = match how {
646                SubtitleHow::BurnIn => PlanKind::Convert,
647                _ => PlanKind::Remux,
648            };
649            assert_eq!(s.kind, kind, "{how:?}");
650        }
651    }
652
653    #[test]
654    fn a_conversion_keeps_its_reasons() {
655        let s = converted(None, Some(copy_audio()), None, Vec::new()).summary();
656        assert_eq!(s.reasons, ["audio 1: dts not supported"]);
657        assert_eq!(s.video, None);
658    }
659
660    #[test]
661    fn an_unsupported_plan_says_why() {
662        let plan = PlaybackPlan::Unsupported {
663            reasons: vec!["video: av1 not supported".into()],
664        };
665        let s = plan.summary();
666        assert_eq!(s.kind, PlanKind::Unsupported);
667        assert_eq!(s.reasons, ["video: av1 not supported"]);
668        assert_eq!(PlaybackPlan::Unknown.summary().kind, PlanKind::Unknown);
669    }
670}