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, SubtitleAction, SubtitleDelivery,
8};
9
10/// What kind of play a plan is.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum PlanKind {
13    /// The file as it is.
14    Direct,
15    /// Converted with every stream copied: a new container, nothing
16    /// encoded. A ladder with an encoded rung is not one.
17    Remux,
18    /// Converted with something encoded, or a subtitle converted, burned
19    /// in or read as text.
20    Convert,
21    /// The client cannot play this selection: see `reasons`.
22    Unsupported,
23    /// A plan kind this build does not know.
24    Unknown,
25}
26
27/// The video that plays.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct VideoSummary {
30    pub codec: VideoCodec,
31    /// Into the output as it is: the file's own.
32    pub copied: bool,
33    /// Shown as Dolby Vision: a copied profile 5 or 8 stream.
34    pub dolby_vision: bool,
35    /// An encode's cap, bits per second; `None` for a copy, or the
36    /// encoder's own choice.
37    pub max_bitrate: Option<u64>,
38}
39
40/// The audio that plays.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct AudioSummary {
43    pub codec: AudioCodec,
44    /// The position of the track in the item's audio list.
45    pub index: u32,
46    /// Into the output (or played) as it is.
47    pub copied: bool,
48    /// An encode's channels; `None` for a copy, which keeps the file's.
49    pub channels: Option<u32>,
50    /// An encode's bits per second; `None` for a copy.
51    pub bitrate: Option<u64>,
52}
53
54/// How the picked subtitle is shown.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum SubtitleHow {
57    /// A stream of the file played as it is.
58    Embedded,
59    /// A separate file the client fetches whole.
60    External,
61    /// Into the output as it is.
62    Copy,
63    /// Converted to another text format into the output.
64    Convert,
65    /// A picture subtitle read as text, fetched whole.
66    Ocr,
67    /// Drawn into the video.
68    BurnIn,
69    /// A way this build does not know.
70    Unknown,
71}
72
73/// The subtitle that shows.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct SubtitleSummary {
76    /// The position of the track in the item's subtitle list.
77    pub index: u32,
78    pub how: SubtitleHow,
79    /// The format the client gets: the output's after a conversion or
80    /// a reading as text; the file's for a burn-in, which the client
81    /// never gets.
82    pub format: Option<SubtitleFormat>,
83}
84
85/// A plan, flat ([`PlaybackPlan::summary`]).
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct PlanSummary {
88    pub kind: PlanKind,
89    /// How a converted output is sent; `None` for the file as it is.
90    pub delivery: Option<Delivery>,
91    pub video: Option<VideoSummary>,
92    pub audio: Option<AudioSummary>,
93    pub subtitle: Option<SubtitleSummary>,
94    /// Why it is not played as it is, or why it cannot play.
95    pub reasons: Vec<String>,
96    /// The lines an encode outputs; `None` where the picture is the
97    /// file's own.
98    pub target_height: Option<u32>,
99    /// A ladder's heights, highest first; empty for one encode.
100    pub ladder_heights: Vec<u32>,
101    /// HDR mapped to SDR.
102    pub tone_mapped: bool,
103}
104
105impl PlaybackPlan {
106    /// The lines the server encodes the picture to, for a quality
107    /// picker's "Auto (720p)"; `None` where the picture is the file's
108    /// own (a direct play, a copied video) or there is none.
109    pub fn encoded_height(&self) -> Option<u32> {
110        match self {
111            PlaybackPlan::Converted {
112                video: Some(ConvertedVideo::Encode { height, .. }),
113                ..
114            } => Some(*height),
115            _ => None,
116        }
117    }
118
119    /// The plan as an info panel shows it. A remux is a converted plan
120    /// whose streams are all copied, as [`PlaybackPlan::Converted`]
121    /// says, with no encoded rung in its ladder.
122    pub fn summary(&self) -> PlanSummary {
123        match self {
124            PlaybackPlan::Direct {
125                video,
126                audio,
127                subtitle,
128                ..
129            } => PlanSummary {
130                kind: PlanKind::Direct,
131                delivery: None,
132                video: video.map(|codec| VideoSummary {
133                    codec,
134                    copied: true,
135                    dolby_vision: false,
136                    max_bitrate: None,
137                }),
138                audio: audio.map(|a| AudioSummary {
139                    codec: a.codec,
140                    index: a.index,
141                    copied: true,
142                    channels: None,
143                    bitrate: None,
144                }),
145                subtitle: subtitle.map(|s| direct_subtitle(&s)),
146                reasons: Vec::new(),
147                target_height: None,
148                ladder_heights: Vec::new(),
149                tone_mapped: false,
150            },
151            PlaybackPlan::Converted {
152                delivery,
153                video,
154                audio,
155                subtitle,
156                ladder,
157                reasons,
158                ..
159            } => {
160                let video_summary = video.and_then(|v| converted_video(&v));
161                let audio = audio.and_then(|a| match a.action {
162                    AudioAction::Copy { codec } => Some(AudioSummary {
163                        codec,
164                        index: a.index,
165                        copied: true,
166                        channels: None,
167                        bitrate: None,
168                    }),
169                    AudioAction::Encode {
170                        codec,
171                        channels,
172                        bitrate,
173                    } => Some(AudioSummary {
174                        codec,
175                        index: a.index,
176                        copied: false,
177                        channels: Some(channels),
178                        bitrate: Some(bitrate),
179                    }),
180                    AudioAction::Unknown => None,
181                });
182                let subtitle = subtitle.map(|s| {
183                    let (how, format) = match s.action {
184                        SubtitleAction::Copy { format } => (SubtitleHow::Copy, Some(format)),
185                        SubtitleAction::Convert { to, .. } => (SubtitleHow::Convert, Some(to)),
186                        SubtitleAction::BurnIn { format } => (SubtitleHow::BurnIn, Some(format)),
187                        SubtitleAction::Ocr { to, .. } => (SubtitleHow::Ocr, Some(to)),
188                        SubtitleAction::Unknown => (SubtitleHow::Unknown, None),
189                    };
190                    SubtitleSummary {
191                        index: s.index,
192                        how,
193                        format,
194                    }
195                });
196                let target_height = self.encoded_height();
197                let tone_mapped =
198                    matches!(video, Some(ConvertedVideo::Encode { tone_map: true, .. }));
199                let copies_video = video.is_none_or(|v| matches!(v, ConvertedVideo::Copy { .. }))
200                    && ladder
201                        .iter()
202                        .all(|r| !matches!(r.video, Some(ConvertedVideo::Encode { .. })));
203                let copies_audio = audio.is_none_or(|a| a.copied);
204                let copies_subtitle = subtitle.is_none_or(|s| s.how == SubtitleHow::Copy);
205                let kind = if copies_video && copies_audio && copies_subtitle {
206                    PlanKind::Remux
207                } else {
208                    PlanKind::Convert
209                };
210                PlanSummary {
211                    kind,
212                    delivery: Some(*delivery),
213                    video: video_summary,
214                    audio,
215                    subtitle,
216                    reasons: reasons.clone(),
217                    target_height,
218                    ladder_heights: ladder.iter().map(|r| r.height).collect(),
219                    tone_mapped,
220                }
221            }
222            PlaybackPlan::Unsupported { reasons } => PlanSummary {
223                reasons: reasons.clone(),
224                ..empty(PlanKind::Unsupported)
225            },
226            PlaybackPlan::Unknown => empty(PlanKind::Unknown),
227        }
228    }
229}
230
231fn empty(kind: PlanKind) -> PlanSummary {
232    PlanSummary {
233        kind,
234        delivery: None,
235        video: None,
236        audio: None,
237        subtitle: None,
238        reasons: Vec::new(),
239        target_height: None,
240        ladder_heights: Vec::new(),
241        tone_mapped: false,
242    }
243}
244
245fn direct_subtitle(s: &PlannedSubtitle) -> SubtitleSummary {
246    let how = match s.delivery {
247        SubtitleDelivery::Embedded => SubtitleHow::Embedded,
248        SubtitleDelivery::External => SubtitleHow::External,
249        SubtitleDelivery::Unknown => SubtitleHow::Unknown,
250    };
251    SubtitleSummary {
252        index: s.index,
253        how,
254        format: Some(s.format),
255    }
256}
257
258fn converted_video(v: &ConvertedVideo) -> Option<VideoSummary> {
259    match *v {
260        ConvertedVideo::Copy {
261            codec,
262            dolby_vision,
263        } => Some(VideoSummary {
264            codec,
265            copied: true,
266            dolby_vision,
267            max_bitrate: None,
268        }),
269        ConvertedVideo::Encode {
270            codec, max_bitrate, ..
271        } => Some(VideoSummary {
272            codec,
273            copied: false,
274            dolby_vision: false,
275            max_bitrate,
276        }),
277        ConvertedVideo::Unknown => None,
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use crate::playback::{ConvertedAudio, ConvertedSubtitle, PlannedAudio, Rung};
285    use spoolframe_types::Container;
286
287    fn copy_video() -> ConvertedVideo {
288        ConvertedVideo::Copy {
289            codec: VideoCodec::Hevc,
290            dolby_vision: true,
291        }
292    }
293
294    fn encode_video(height: u32, tone_map: bool) -> ConvertedVideo {
295        ConvertedVideo::Encode {
296            codec: VideoCodec::H264,
297            height,
298            max_bitrate: Some(8_000_000),
299            tone_map,
300        }
301    }
302
303    fn copy_audio() -> ConvertedAudio {
304        ConvertedAudio {
305            index: 1,
306            action: AudioAction::Copy {
307                codec: AudioCodec::Aac,
308            },
309        }
310    }
311
312    fn converted(
313        video: Option<ConvertedVideo>,
314        audio: Option<ConvertedAudio>,
315        subtitle: Option<SubtitleAction>,
316        ladder: Vec<Rung>,
317    ) -> PlaybackPlan {
318        PlaybackPlan::Converted {
319            delivery: Delivery::Hls,
320            container: Container::Mp4,
321            video,
322            audio,
323            subtitle: subtitle.map(|action| ConvertedSubtitle { index: 2, action }),
324            ladder,
325            reasons: vec!["audio 1: dts not supported".into()],
326            source_codec: None,
327        }
328    }
329
330    fn rung(height: u32, video: Option<ConvertedVideo>) -> Rung {
331        Rung {
332            height,
333            max_bitrate: 1_000_000,
334            video,
335        }
336    }
337
338    #[test]
339    fn a_direct_play_is_the_files_own_streams() {
340        let plan = PlaybackPlan::Direct {
341            container: Container::Matroska,
342            video: Some(VideoCodec::Hevc),
343            audio: Some(PlannedAudio {
344                index: 0,
345                codec: AudioCodec::Eac3,
346            }),
347            subtitle: Some(PlannedSubtitle {
348                index: 3,
349                format: SubtitleFormat::Srt,
350                delivery: SubtitleDelivery::External,
351            }),
352            source_codec: None,
353        };
354        let s = plan.summary();
355        assert_eq!(s.kind, PlanKind::Direct);
356        assert_eq!(s.delivery, None);
357        assert!(
358            s.video
359                .is_some_and(|v| v.copied && v.codec == VideoCodec::Hevc)
360        );
361        assert_eq!(
362            s.audio,
363            Some(AudioSummary {
364                codec: AudioCodec::Eac3,
365                index: 0,
366                copied: true,
367                channels: None,
368                bitrate: None,
369            })
370        );
371        assert_eq!(
372            s.subtitle,
373            Some(SubtitleSummary {
374                index: 3,
375                how: SubtitleHow::External,
376                format: Some(SubtitleFormat::Srt),
377            })
378        );
379    }
380
381    #[test]
382    fn every_stream_copied_is_a_remux() {
383        let plan = converted(
384            Some(copy_video()),
385            Some(copy_audio()),
386            Some(SubtitleAction::Copy {
387                format: SubtitleFormat::Srt,
388            }),
389            Vec::new(),
390        );
391        let s = plan.summary();
392        assert_eq!(s.kind, PlanKind::Remux);
393        assert_eq!(s.delivery, Some(Delivery::Hls));
394        assert!(s.video.is_some_and(|v| v.copied && v.dolby_vision));
395        assert_eq!(s.target_height, None);
396    }
397
398    #[test]
399    fn audio_encoded_makes_it_a_conversion_with_its_channels_and_bitrate() {
400        let audio = ConvertedAudio {
401            index: 1,
402            action: AudioAction::Encode {
403                codec: AudioCodec::Aac,
404                channels: 6,
405                bitrate: 384_000,
406            },
407        };
408        let s = converted(Some(copy_video()), Some(audio), None, Vec::new()).summary();
409        assert_eq!(s.kind, PlanKind::Convert);
410        assert_eq!(
411            s.audio.map(|a| (a.copied, a.channels, a.bitrate)),
412            Some((false, Some(6), Some(384_000)))
413        );
414    }
415
416    #[test]
417    fn an_encode_says_its_height_and_whether_it_maps_hdr() {
418        let s = converted(Some(encode_video(1080, true)), None, None, Vec::new()).summary();
419        assert_eq!(s.kind, PlanKind::Convert);
420        assert_eq!(s.target_height, Some(1080));
421        assert!(s.tone_mapped);
422        assert!(
423            s.video
424                .is_some_and(|v| !v.copied && v.max_bitrate == Some(8_000_000))
425        );
426    }
427
428    #[test]
429    fn only_an_encode_has_a_height_of_its_own() {
430        assert_eq!(
431            converted(Some(encode_video(540, false)), None, None, vec![]).encoded_height(),
432            Some(540)
433        );
434        assert_eq!(
435            converted(Some(copy_video()), None, None, vec![]).encoded_height(),
436            None
437        );
438        let direct = PlaybackPlan::Direct {
439            container: Container::Matroska,
440            video: Some(VideoCodec::Hevc),
441            audio: None,
442            subtitle: None,
443            source_codec: None,
444        };
445        assert_eq!(direct.encoded_height(), None);
446    }
447
448    #[test]
449    fn a_ladder_lists_its_heights_highest_first() {
450        let ladder = vec![rung(1080, None), rung(720, None), rung(480, None)];
451        let s = converted(Some(encode_video(1080, false)), None, None, ladder).summary();
452        assert_eq!(s.ladder_heights, [1080, 720, 480]);
453        assert!(!s.tone_mapped);
454    }
455
456    #[test]
457    fn a_copy_with_encoded_rungs_under_it_is_not_a_remux() {
458        let ladder = vec![
459            rung(2160, None),
460            rung(1080, Some(encode_video(1080, false))),
461        ];
462        let s = converted(Some(copy_video()), Some(copy_audio()), None, ladder).summary();
463        assert_eq!(s.kind, PlanKind::Convert);
464        assert_eq!(s.target_height, None);
465    }
466
467    #[test]
468    fn a_subtitle_says_how_it_shows_and_in_what_format() {
469        let cases = [
470            (
471                SubtitleAction::Convert {
472                    from: SubtitleFormat::Srt,
473                    to: SubtitleFormat::WebVtt,
474                },
475                SubtitleHow::Convert,
476                SubtitleFormat::WebVtt,
477            ),
478            (
479                SubtitleAction::Ocr {
480                    from: SubtitleFormat::Pgs,
481                    to: SubtitleFormat::Srt,
482                },
483                SubtitleHow::Ocr,
484                SubtitleFormat::Srt,
485            ),
486            (
487                SubtitleAction::BurnIn {
488                    format: SubtitleFormat::Pgs,
489                },
490                SubtitleHow::BurnIn,
491                SubtitleFormat::Pgs,
492            ),
493        ];
494        for (action, how, format) in cases {
495            let s = converted(Some(copy_video()), None, Some(action), Vec::new()).summary();
496            assert_eq!(
497                s.subtitle,
498                Some(SubtitleSummary {
499                    index: 2,
500                    how,
501                    format: Some(format),
502                })
503            );
504            // Anything but a copy is work on the server.
505            assert_eq!(s.kind, PlanKind::Convert, "{how:?}");
506        }
507    }
508
509    #[test]
510    fn a_conversion_keeps_its_reasons() {
511        let s = converted(None, Some(copy_audio()), None, Vec::new()).summary();
512        assert_eq!(s.reasons, ["audio 1: dts not supported"]);
513        assert_eq!(s.video, None);
514    }
515
516    #[test]
517    fn an_unsupported_plan_says_why() {
518        let plan = PlaybackPlan::Unsupported {
519            reasons: vec!["video: av1 not supported".into()],
520        };
521        let s = plan.summary();
522        assert_eq!(s.kind, PlanKind::Unsupported);
523        assert_eq!(s.reasons, ["video: av1 not supported"]);
524        assert_eq!(PlaybackPlan::Unknown.summary().kind, PlanKind::Unknown);
525    }
526}