Skip to main content

rtci_rtp/codec/svc/
mod.rs

1//! Scalable video coding: the scalability modes of the W3C "Scalable Video Coding (SVC)
2//! Extension for WebRTC" and the layer structure of each.
3//!
4//! * [`ScalabilityMode`] is the `scalabilityMode` of an encoding: every identifier of the
5//!   specification's table (section 5), with its number of spatial and temporal layers, its
6//!   resolution ratio and its kind of inter-layer dependency, and which codecs can carry it.
7//! * [`ScalabilityPattern`] is the dependency structure of a mode (the diagrams of section 9)
8//!   as a generator: for each picture it gives one [`LayerFrame`] per spatial layer, saying
9//!   what the frame depends on and which decode targets it is part of. An encoder that
10//!   follows the pattern is described on the wire by handing each `LayerFrame` to the
11//!   codec's payloader:
12//!   [`Vp8Payloader::payload_frame`](crate::codec::vp8::Vp8Payloader::payload_frame) with
13//!   [`LayerFrame::vp8_info`],
14//!   [`Vp9Payloader::payload_layer_frame`](crate::codec::vp9::Vp9Payloader::payload_layer_frame)
15//!   with [`LayerFrame::vp9_info`], and for AV1 (or any codec, next to its payload format) the
16//!   Dependency Descriptor: [`ScalabilityPattern::dependency_structure`] and
17//!   [`LayerFrame::dependencies`] into a
18//!   [`DependencyDescriptorWriter`](crate::codec::dependency_descriptor::DependencyDescriptorWriter).
19//!
20//! An encoder with a structure of its own does not need the pattern: the payloaders take the
21//! same per-frame information from anywhere.
22//!
23//! The receive side, for a forwarder, is one type per signalling:
24//! [`Vp8TemporalLayerFilter`](crate::codec::vp8::Vp8TemporalLayerFilter),
25//! [`Vp9LayerFilter`](crate::codec::vp9::Vp9LayerFilter) and
26//! [`DecodeTargetSelector`](crate::codec::dependency_descriptor::DecodeTargetSelector).
27
28#[cfg(test)]
29mod svc_mode_test;
30#[cfg(test)]
31mod svc_pattern_test;
32
33use std::fmt;
34use std::str::FromStr;
35
36use shared::error::{Error, Result};
37
38use crate::codec::dependency_descriptor::{
39    DecodeTargetIndication, FrameDependencyStructure, FrameDependencyTemplate, RenderResolution,
40};
41use crate::codec::vp8::{Vp8FrameInfo, Vp8TemporalLayer};
42use crate::codec::vp9::{Vp9FrameInfo, Vp9PictureGroupEntry, Vp9ScalabilityStructure};
43
44/// How the spatial layers of a mode depend on each other (the "Inter-layer dependency" column
45/// of the specification's table, and its `_KEY` suffix).
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47#[non_exhaustive]
48pub enum InterLayerPrediction {
49    /// `LxTy`: every frame of a spatial layer predicts from the frame of the layer below in
50    /// the same picture. A single spatial layer is this case too.
51    Full,
52    /// `LxTy_KEY` (K-SVC): spatial layers depend on lower ones at a key frame only.
53    KeyPicture,
54    /// `SxTy`: none. The spatial layers are simulcast encodings carried in one RTP stream.
55    None,
56}
57
58/// The ratio between the resolutions of two neighbouring spatial layers.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60#[non_exhaustive]
61pub enum ResolutionRatio {
62    /// 2:1, the default.
63    TwoToOne,
64    /// 1.5:1, the modes whose name ends in `h`.
65    OneAndAHalfToOne,
66}
67
68macro_rules! scalability_modes {
69    ($(($variant:ident, $name:literal, $spatial:literal, $temporal:literal, $prediction:ident, $ratio:ident, $shift:literal)),* $(,)?) => {
70        /// A scalability mode: a value of `RTCRtpEncodingParameters.scalabilityMode` (W3C
71        /// webrtc-svc, section 5). The identifiers are case sensitive and limited to the
72        /// specification's table; [`FromStr`] accepts exactly those.
73        ///
74        /// The table can grow (section 5.1 says how a mode is added), so the enum is
75        /// non-exhaustive.
76        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
77        #[allow(non_camel_case_types)]
78        #[non_exhaustive]
79        pub enum ScalabilityMode {
80            $(
81                #[doc = concat!("`\"", $name, "\"`.")]
82                $variant,
83            )*
84        }
85
86        impl ScalabilityMode {
87            /// Every mode of the specification's table, in its order.
88            pub const ALL: &'static [ScalabilityMode] = &[$(ScalabilityMode::$variant,)*];
89
90            /// The mode's identifier, as it is written in `scalabilityMode`.
91            pub fn as_str(&self) -> &'static str {
92                match self {
93                    $(ScalabilityMode::$variant => $name,)*
94                }
95            }
96
97            /// (spatial layers, temporal layers, inter-layer prediction, 1.5:1 ratio,
98            /// temporal shift)
99            fn properties(&self) -> (u8, u8, InterLayerPrediction, ResolutionRatio, bool) {
100                match self {
101                    $(ScalabilityMode::$variant => (
102                        $spatial,
103                        $temporal,
104                        InterLayerPrediction::$prediction,
105                        ResolutionRatio::$ratio,
106                        $shift,
107                    ),)*
108                }
109            }
110        }
111    };
112}
113
114scalability_modes![
115    (L1T1, "L1T1", 1, 1, Full, TwoToOne, false),
116    (L1T2, "L1T2", 1, 2, Full, TwoToOne, false),
117    (L1T3, "L1T3", 1, 3, Full, TwoToOne, false),
118    (L2T1, "L2T1", 2, 1, Full, TwoToOne, false),
119    (L2T2, "L2T2", 2, 2, Full, TwoToOne, false),
120    (L2T3, "L2T3", 2, 3, Full, TwoToOne, false),
121    (L3T1, "L3T1", 3, 1, Full, TwoToOne, false),
122    (L3T2, "L3T2", 3, 2, Full, TwoToOne, false),
123    (L3T3, "L3T3", 3, 3, Full, TwoToOne, false),
124    (L2T1h, "L2T1h", 2, 1, Full, OneAndAHalfToOne, false),
125    (L2T2h, "L2T2h", 2, 2, Full, OneAndAHalfToOne, false),
126    (L2T3h, "L2T3h", 2, 3, Full, OneAndAHalfToOne, false),
127    (L3T1h, "L3T1h", 3, 1, Full, OneAndAHalfToOne, false),
128    (L3T2h, "L3T2h", 3, 2, Full, OneAndAHalfToOne, false),
129    (L3T3h, "L3T3h", 3, 3, Full, OneAndAHalfToOne, false),
130    (S2T1, "S2T1", 2, 1, None, TwoToOne, false),
131    (S2T2, "S2T2", 2, 2, None, TwoToOne, false),
132    (S2T3, "S2T3", 2, 3, None, TwoToOne, false),
133    (S2T1h, "S2T1h", 2, 1, None, OneAndAHalfToOne, false),
134    (S2T2h, "S2T2h", 2, 2, None, OneAndAHalfToOne, false),
135    (S2T3h, "S2T3h", 2, 3, None, OneAndAHalfToOne, false),
136    (S3T1, "S3T1", 3, 1, None, TwoToOne, false),
137    (S3T2, "S3T2", 3, 2, None, TwoToOne, false),
138    (S3T3, "S3T3", 3, 3, None, TwoToOne, false),
139    (S3T1h, "S3T1h", 3, 1, None, OneAndAHalfToOne, false),
140    (S3T2h, "S3T2h", 3, 2, None, OneAndAHalfToOne, false),
141    (S3T3h, "S3T3h", 3, 3, None, OneAndAHalfToOne, false),
142    (L2T2_KEY, "L2T2_KEY", 2, 2, KeyPicture, TwoToOne, false),
143    (
144        L2T2_KEY_SHIFT,
145        "L2T2_KEY_SHIFT",
146        2,
147        2,
148        KeyPicture,
149        TwoToOne,
150        true
151    ),
152    (L2T3_KEY, "L2T3_KEY", 2, 3, KeyPicture, TwoToOne, false),
153    (
154        L2T3_KEY_SHIFT,
155        "L2T3_KEY_SHIFT",
156        2,
157        3,
158        KeyPicture,
159        TwoToOne,
160        true
161    ),
162    (L3T1_KEY, "L3T1_KEY", 3, 1, KeyPicture, TwoToOne, false),
163    (L3T2_KEY, "L3T2_KEY", 3, 2, KeyPicture, TwoToOne, false),
164    (
165        L3T2_KEY_SHIFT,
166        "L3T2_KEY_SHIFT",
167        3,
168        2,
169        KeyPicture,
170        TwoToOne,
171        true
172    ),
173    (L3T3_KEY, "L3T3_KEY", 3, 3, KeyPicture, TwoToOne, false),
174    (
175        L3T3_KEY_SHIFT,
176        "L3T3_KEY_SHIFT",
177        3,
178        3,
179        KeyPicture,
180        TwoToOne,
181        true
182    ),
183];
184
185impl ScalabilityMode {
186    /// The number of spatial layers (for an "S" mode, of simulcast encodings).
187    pub fn spatial_layers(&self) -> u8 {
188        self.properties().0
189    }
190
191    /// The number of temporal layers.
192    pub fn temporal_layers(&self) -> u8 {
193        self.properties().1
194    }
195
196    /// How the spatial layers depend on each other.
197    pub fn inter_layer_prediction(&self) -> InterLayerPrediction {
198        self.properties().2
199    }
200
201    /// The ratio between neighbouring spatial layers' resolutions; `None` for a mode with one
202    /// spatial layer.
203    pub fn resolution_ratio(&self) -> Option<ResolutionRatio> {
204        (self.spatial_layers() > 1).then_some(self.properties().3)
205    }
206
207    /// Whether the temporal layers of the spatial layers are shifted against each other (the
208    /// `_SHIFT` modes), so that the frames of one picture are of different temporal layers.
209    pub fn has_temporal_shift(&self) -> bool {
210        self.properties().4
211    }
212
213    /// Whether this is an "S" mode: simulcast encodings transported in one RTP stream. The
214    /// specification allows no more than one active encoding next to an active "S" mode
215    /// encoding (sections 3.2.1 and 3.2.2).
216    pub fn is_simulcast(&self) -> bool {
217        self.inter_layer_prediction() == InterLayerPrediction::None
218    }
219
220    /// Whether the mode turns scalable coding off: `"L1T1"` (section 3.2.2).
221    pub fn is_single_layer(&self) -> bool {
222        self.spatial_layers() == 1 && self.temporal_layers() == 1
223    }
224
225    /// Whether a codec can carry the mode, by its MIME type (`"video/VP9"`, compared without
226    /// regard to case). Section 5: AV1 and VP9 support every mode of the table; VP8, H.264
227    /// and H.265 "only support temporal scalability" and "only permit transport of simulcast
228    /// on distinct SSRCs". For any other codec only `"L1T1"`, which is no scalability.
229    pub fn supported_by(&self, mime_type: &str) -> bool {
230        let codec = mime_type.to_ascii_lowercase();
231        match codec.as_str() {
232            "video/av1" | "video/vp9" => true,
233            "video/vp8" | "video/h264" | "video/h265" => self.spatial_layers() == 1,
234            other => other.starts_with("video/") && self.is_single_layer(),
235        }
236    }
237
238    /// The modes a codec can carry, in the table's order: what a capability report lists as
239    /// the codec's `scalabilityModes`.
240    pub fn supported_modes(mime_type: &str) -> Vec<ScalabilityMode> {
241        Self::ALL
242            .iter()
243            .copied()
244            .filter(|mode| mode.supported_by(mime_type))
245            .collect()
246    }
247
248    /// The resolution of spatial layer `spatial_id` when the highest layer is `width` by
249    /// `height`: each layer below is smaller by the mode's ratio.
250    pub fn layer_resolution(&self, spatial_id: u8, width: u32, height: u32) -> (u32, u32) {
251        let steps = (self.spatial_layers() - 1).saturating_sub(spatial_id) as u32;
252        let (numerator, denominator) = match self.properties().3 {
253            ResolutionRatio::TwoToOne => (1u64, 2u64.pow(steps)),
254            ResolutionRatio::OneAndAHalfToOne => (2u64.pow(steps), 3u64.pow(steps)),
255        };
256        let scale = |v: u32| ((v as u64 * numerator / denominator).max(1)) as u32;
257        (scale(width), scale(height))
258    }
259}
260
261impl fmt::Display for ScalabilityMode {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        f.write_str(self.as_str())
264    }
265}
266
267impl FromStr for ScalabilityMode {
268    type Err = Error;
269
270    /// Parses a `scalabilityMode` value. The identifiers are case sensitive, and only those
271    /// of the specification's table are modes.
272    fn from_str(s: &str) -> Result<Self> {
273        Self::ALL
274            .iter()
275            .copied()
276            .find(|mode| mode.as_str() == s)
277            .ok_or_else(|| Error::Other(format!("\"{s}\" is not a scalability mode")))
278    }
279}
280
281/// The most spatial layers a mode has.
282const MAX_SPATIAL: usize = 3;
283/// The most temporal layers a mode has.
284const MAX_TEMPORAL: usize = 3;
285
286/// One frame of a picture of a [`ScalabilityPattern`]: one spatial layer's frame, with what
287/// it depends on and how it relates to each decode target.
288#[derive(Debug, Clone, PartialEq, Eq)]
289pub struct LayerFrame {
290    /// The frame's spatial layer.
291    pub spatial_id: u8,
292    /// The frame's temporal layer.
293    pub temporal_id: u8,
294    /// The frame is of a key picture: the picture a coded video sequence starts with.
295    pub key_picture: bool,
296    /// The frame depends on no other frame: a key frame.
297    pub key_frame: bool,
298    /// How many pictures back the frame of the same spatial layer this one predicts from is;
299    /// `None` when it predicts from no earlier picture.
300    pub temporal_reference: Option<u8>,
301    /// The frame predicts from the frame of the spatial layer below in the same picture.
302    pub inter_layer_dependency: bool,
303    /// A frame of a spatial layer above, in this picture or a later one, depends on this
304    /// frame.
305    pub referenced_by_upper_layers: bool,
306    /// No other frame depends on this one.
307    pub discardable: bool,
308    /// The frame depends on frames of temporal layer 0 only (and is not of that layer): a
309    /// receiver can start its temporal layer here (VP8's layer sync).
310    pub layer_sync: bool,
311    /// How many frames back, in the order the pattern gives them, each frame this one depends
312    /// on is: the Dependency Descriptor's frame differences.
313    pub fdiffs: Vec<u16>,
314    /// The frame's indication for each decode target (see
315    /// [`ScalabilityPattern::decode_target_layers`] for their order).
316    pub dtis: Vec<DecodeTargetIndication>,
317    /// For each chain (one per spatial layer), how many frames back the previous frame of
318    /// the chain is; 0 when there is none.
319    pub chain_fdiffs: Vec<u8>,
320    /// The frame is its picture's last.
321    pub end_of_picture: bool,
322}
323
324impl LayerFrame {
325    /// Whether the frame starts a coded video sequence: the first frame of a key picture. Its
326    /// first packet carries the Dependency Descriptor's structure, and VP9's scalability
327    /// structure.
328    pub fn starts_coded_video_sequence(&self) -> bool {
329        self.key_picture && self.spatial_id == 0
330    }
331
332    /// The frame as the Dependency Descriptor describes it, for
333    /// [`DependencyDescriptorWriter::next_frame`](crate::codec::dependency_descriptor::DependencyDescriptorWriter::next_frame).
334    pub fn dependencies(&self) -> FrameDependencyTemplate {
335        FrameDependencyTemplate {
336            spatial_id: self.spatial_id,
337            temporal_id: self.temporal_id,
338            dtis: self.dtis.clone(),
339            fdiffs: self.fdiffs.clone(),
340            chain_fdiffs: self.chain_fdiffs.clone(),
341        }
342    }
343
344    /// The frame as the VP8 payload descriptor describes it (RFC 7741 section 4.2), for
345    /// [`Vp8Payloader::payload_frame`](crate::codec::vp8::Vp8Payloader::payload_frame). VP8
346    /// has temporal layers only; `mode` says whether there is more than one.
347    pub fn vp8_info(&self, mode: ScalabilityMode) -> Vp8FrameInfo {
348        Vp8FrameInfo {
349            non_reference: self.discardable,
350            temporal: (mode.temporal_layers() > 1).then_some(Vp8TemporalLayer {
351                tid: self.temporal_id,
352                layer_sync: self.layer_sync,
353            }),
354            key_idx: None,
355        }
356    }
357
358    /// The frame as the VP9 payload descriptor describes it (RFC 9628 section 4.2), for
359    /// [`Vp9Payloader::payload_layer_frame`](crate::codec::vp9::Vp9Payloader::payload_layer_frame).
360    /// The pattern is the authority on the frame's dependencies, so they are stated rather
361    /// than left to the frame's header (which an end-to-end encrypted frame hides).
362    pub fn vp9_info(&self) -> Vp9FrameInfo {
363        Vp9FrameInfo {
364            temporal_id: self.temporal_id,
365            spatial_id: self.spatial_id,
366            // In these patterns a frame never predicts from one of its own temporal layer or
367            // a higher one, except in temporal layer 0.
368            switching_up_point: true,
369            inter_layer_dependency: self.inter_layer_dependency,
370            not_reference_for_upper_layers: !self.referenced_by_upper_layers,
371            end_of_picture: self.end_of_picture,
372            key_frame: Some(self.key_frame),
373            inter_picture_predicted: Some(self.temporal_reference.is_some()),
374            reference_diffs: self.temporal_reference.into_iter().collect(),
375        }
376    }
377}
378
379/// The dependency structure of a [`ScalabilityMode`], as a generator of pictures.
380///
381/// The structure is the one of the specification's dependency diagrams (webrtc-svc section 9)
382/// and of the AV1 RTP specification's examples (A.10.2), which give the same structures as
383/// tables:
384///
385/// * temporal layers: with two, pictures alternate between layers 0 and 1; with three, the
386///   layers go 0, 2, 1, 2. A frame predicts from the latest frame of its spatial layer in a
387///   lower temporal layer (in layer 0: the latest of layer 0);
388/// * `LxTy`: in addition every frame predicts from the frame of the spatial layer below in
389///   its picture;
390/// * `LxTy_KEY`: it does so in the key picture only;
391/// * `LxTy_KEY_SHIFT`: as `_KEY`, and after the key picture the temporal pattern of spatial
392///   layer `s` of `S` starts `(s + 1) mod S` pictures late, so the layers' base layer frames
393///   fall in different pictures;
394/// * `SxTy`: the spatial layers are independent, each with its own key frame.
395///
396/// Decode targets are one per spatial and temporal layer, highest spatial layer first and
397/// within it highest temporal layer first (the order of the AV1 RTP specification's tables).
398/// There is one chain per spatial layer, protecting that layer's decode targets.
399#[derive(Debug, Clone)]
400pub struct ScalabilityPattern {
401    mode: ScalabilityMode,
402    /// Pictures since the key picture; `None` before the first picture.
403    picture: Option<u64>,
404    /// Frames given out so far.
405    frames: u64,
406    /// Per spatial and temporal layer: the latest frame (its number and its picture).
407    latest: [[Option<(u64, u64)>; MAX_TEMPORAL]; MAX_SPATIAL],
408    /// Per chain: its latest frame.
409    chain_latest: [Option<u64>; MAX_SPATIAL],
410}
411
412impl ScalabilityPattern {
413    /// The pattern of `mode`, before its first picture.
414    pub fn new(mode: ScalabilityMode) -> Self {
415        Self {
416            mode,
417            picture: None,
418            frames: 0,
419            latest: [[None; MAX_TEMPORAL]; MAX_SPATIAL],
420            chain_latest: [None; MAX_SPATIAL],
421        }
422    }
423
424    /// The mode.
425    pub fn mode(&self) -> ScalabilityMode {
426        self.mode
427    }
428
429    /// The spatial and temporal layer each decode target stands for, in decode target order.
430    pub fn decode_target_layers(&self) -> Vec<(u8, u8)> {
431        let (spatial, temporal) = (self.mode.spatial_layers(), self.mode.temporal_layers());
432        (0..spatial)
433            .rev()
434            .flat_map(|s| (0..temporal).rev().map(move |t| (s, t)))
435            .collect()
436    }
437
438    /// The temporal layer of spatial layer `s` in the picture `picture` pictures after the
439    /// key picture.
440    fn temporal_id(&self, s: u8, picture: u64) -> u8 {
441        if picture == 0 {
442            return 0;
443        }
444        let sequence: &[u8] = match self.mode.temporal_layers() {
445            1 => &[0],
446            2 => &[0, 1],
447            _ => &[0, 2, 1, 2],
448        };
449        let shift = if self.mode.has_temporal_shift() {
450            ((s + 1) % self.mode.spatial_layers()) as i64
451        } else {
452            0
453        };
454        sequence[(picture as i64 - shift).rem_euclid(sequence.len() as i64) as usize]
455    }
456
457    /// The frames of the next picture, lowest spatial layer first. `key_picture` starts a new
458    /// coded video sequence (the first picture always does): ask for one when a receiver
459    /// asks for a key frame.
460    pub fn next_picture(&mut self, key_picture: bool) -> Vec<LayerFrame> {
461        let picture = match self.picture {
462            Some(picture) if !key_picture => picture + 1,
463            _ => {
464                self.latest = [[None; MAX_TEMPORAL]; MAX_SPATIAL];
465                self.chain_latest = [None; MAX_SPATIAL];
466                0
467            }
468        };
469        self.picture = Some(picture);
470        let key_picture = picture == 0;
471        let mode = self.mode;
472        let prediction = mode.inter_layer_prediction();
473        let (spatial, temporal) = (mode.spatial_layers(), mode.temporal_layers());
474
475        let mut frames = Vec::with_capacity(spatial as usize);
476        for s in 0..spatial {
477            let t = self.temporal_id(s, picture);
478            let number = self.frames;
479
480            // The frame of this spatial layer it predicts from: the latest one of a lower
481            // temporal layer, or in temporal layer 0 the latest of that layer.
482            let candidates = if t == 0 { 0..1 } else { 0..t as usize };
483            let temporal_reference = self.latest[s as usize][candidates]
484                .iter()
485                .flatten()
486                .max_by_key(|(_, picture)| *picture)
487                .copied();
488            let inter_layer_dependency = s > 0
489                && match prediction {
490                    InterLayerPrediction::Full => true,
491                    InterLayerPrediction::KeyPicture => key_picture,
492                    InterLayerPrediction::None => false,
493                };
494            let mut fdiffs = vec![];
495            if let Some((reference, _)) = temporal_reference {
496                fdiffs.push((number - reference) as u16);
497            }
498            if inter_layer_dependency {
499                // The frame given out just before this one.
500                fdiffs.push(1);
501            }
502
503            let referenced_by_upper_layers = s + 1 < spatial
504                && match prediction {
505                    InterLayerPrediction::Full => true,
506                    InterLayerPrediction::KeyPicture => key_picture,
507                    InterLayerPrediction::None => false,
508                };
509            // A frame of the highest temporal layer is no reference within its spatial layer.
510            let discardable = temporal > 1 && t == temporal - 1 && !referenced_by_upper_layers;
511            let layer_sync = t > 0
512                && temporal_reference.is_some_and(|(reference, _)| {
513                    self.latest[s as usize][0].is_some_and(|(base, _)| base == reference)
514                });
515
516            // The indication for each decode target (ds, dt).
517            let dtis = self
518                .decode_target_layers()
519                .into_iter()
520                .map(|(ds, dt)| {
521                    let own_layer = if t > dt {
522                        DecodeTargetIndication::NotPresent
523                    } else if t == dt && t > 0 {
524                        DecodeTargetIndication::Discardable
525                    } else {
526                        DecodeTargetIndication::Switch
527                    };
528                    match prediction {
529                        InterLayerPrediction::Full if s > ds || t > dt => {
530                            DecodeTargetIndication::NotPresent
531                        }
532                        InterLayerPrediction::Full if s == ds => own_layer,
533                        // A lower layer's frame is needed by the target; at a key picture
534                        // the target can be joined.
535                        InterLayerPrediction::Full if key_picture => DecodeTargetIndication::Switch,
536                        InterLayerPrediction::Full => DecodeTargetIndication::Required,
537                        InterLayerPrediction::KeyPicture if key_picture => {
538                            if s <= ds {
539                                DecodeTargetIndication::Switch
540                            } else {
541                                DecodeTargetIndication::NotPresent
542                            }
543                        }
544                        InterLayerPrediction::KeyPicture | InterLayerPrediction::None => {
545                            if s == ds {
546                                own_layer
547                            } else {
548                                DecodeTargetIndication::NotPresent
549                            }
550                        }
551                    }
552                })
553                .collect();
554
555            // Chain c is the frames spatial layer c cannot do without: its temporal layer 0
556            // frames, and the frames of the layers below that those depend on.
557            let mut chain_fdiffs = Vec::with_capacity(spatial as usize);
558            for chain in 0..spatial {
559                chain_fdiffs.push(
560                    self.chain_latest[chain as usize]
561                        .map_or(0, |latest| (number - latest).min(u8::MAX as u64) as u8),
562                );
563                let in_chain = match prediction {
564                    InterLayerPrediction::Full => t == 0 && s <= chain,
565                    InterLayerPrediction::KeyPicture if key_picture => s <= chain,
566                    InterLayerPrediction::KeyPicture | InterLayerPrediction::None => {
567                        t == 0 && s == chain
568                    }
569                };
570                if in_chain {
571                    self.chain_latest[chain as usize] = Some(number);
572                }
573            }
574
575            frames.push(LayerFrame {
576                spatial_id: s,
577                temporal_id: t,
578                key_picture,
579                key_frame: fdiffs.is_empty(),
580                temporal_reference: temporal_reference
581                    .map(|(_, reference_picture)| (picture - reference_picture) as u8),
582                inter_layer_dependency,
583                referenced_by_upper_layers,
584                discardable,
585                layer_sync,
586                fdiffs,
587                dtis,
588                chain_fdiffs,
589                end_of_picture: s + 1 == spatial,
590            });
591            self.latest[s as usize][t as usize] = Some((number, picture));
592            self.frames += 1;
593        }
594        frames
595    }
596
597    /// The mode's frame dependency structure for the Dependency Descriptor (AV1 RTP
598    /// specification A.8): one template for every kind of frame the pattern produces, so that
599    /// each frame's descriptor is three bytes. `resolution` is the highest spatial layer's
600    /// width and height, when the structure should carry the layers' resolutions.
601    ///
602    /// For `"L1T3"`, `"L3T3"` and `"L3T3_KEY_SHIFT"` this is the structure the specification
603    /// gives as an example (A.10.2.1 to A.10.2.3), template for template.
604    pub fn dependency_structure(
605        mode: ScalabilityMode,
606        resolution: Option<(u32, u32)>,
607    ) -> FrameDependencyStructure {
608        // Run the pattern until it repeats and keep each distinct frame once, in the order
609        // the syntax needs: by spatial layer, then temporal layer, then first appearance.
610        let mut pattern = Self::new(mode);
611        let mut templates: Vec<FrameDependencyTemplate> = vec![];
612        for _ in 0..=4 * 4 {
613            for frame in pattern.next_picture(false) {
614                let template = frame.dependencies();
615                if !templates.contains(&template) {
616                    templates.push(template);
617                }
618            }
619        }
620        templates.sort_by_key(|t| (t.spatial_id, t.temporal_id));
621
622        let spatial = mode.spatial_layers();
623        FrameDependencyStructure {
624            template_id_offset: 0,
625            num_decode_targets: spatial as usize * mode.temporal_layers() as usize,
626            num_chains: spatial as usize,
627            decode_target_protected_by: pattern
628                .decode_target_layers()
629                .into_iter()
630                .map(|(s, _)| s)
631                .collect(),
632            resolutions: resolution
633                .map(|(width, height)| {
634                    (0..spatial)
635                        .map(|s| {
636                            let (width, height) = mode.layer_resolution(s, width, height);
637                            RenderResolution { width, height }
638                        })
639                        .collect()
640                })
641                .unwrap_or_default(),
642            templates,
643        }
644    }
645
646    /// The mode's VP9 scalability structure (RFC 9628 section 4.2.1), for
647    /// [`Vp9Payloader::set_scalability_structure`](crate::codec::vp9::Vp9Payloader::set_scalability_structure).
648    /// `resolution` is the highest spatial layer's width and height, when the SS should carry
649    /// the layers' resolutions.
650    ///
651    /// For non-flexible mode (`flexible_mode` false) it has the picture group that declares
652    /// the temporal structure; in flexible mode each packet carries its own references and
653    /// the SS has none.
654    ///
655    /// # Errors
656    ///
657    /// Non-flexible mode for a mode with shifted temporal layers: there "all frames follow the
658    /// same inter-picture dependency structure" (RFC 9628 section 4.2.1), which a shifted
659    /// pattern does not; and a resolution that does not fit 16 bits.
660    pub fn vp9_scalability_structure(
661        mode: ScalabilityMode,
662        resolution: Option<(u32, u32)>,
663        flexible_mode: bool,
664    ) -> Result<Vp9ScalabilityStructure> {
665        let mut resolutions = vec![];
666        if let Some((width, height)) = resolution {
667            for s in 0..mode.spatial_layers() {
668                let (width, height) = mode.layer_resolution(s, width, height);
669                match (u16::try_from(width), u16::try_from(height)) {
670                    (Ok(width), Ok(height)) => resolutions.push((width, height)),
671                    _ => {
672                        return Err(Error::Other(format!(
673                            "VP9 scalability structure: {width}x{height} does not fit 16 bits"
674                        )));
675                    }
676                }
677            }
678        }
679        let mut picture_group = vec![];
680        if !flexible_mode {
681            if mode.has_temporal_shift() {
682                return Err(Error::Other(format!(
683                    "VP9 non-flexible mode cannot carry {mode}: its spatial layers have different temporal structures"
684                )));
685            }
686            // (TID, P_DIFF) of each picture of one period, from the key picture on.
687            let group: &[(u8, u8)] = match mode.temporal_layers() {
688                1 => &[(0, 1)],
689                2 => &[(0, 2), (1, 1)],
690                _ => &[(0, 4), (2, 1), (1, 2), (2, 1)],
691            };
692            picture_group = group
693                .iter()
694                .map(|(temporal_id, reference_diff)| Vp9PictureGroupEntry {
695                    temporal_id: *temporal_id,
696                    switching_up_point: true,
697                    reference_diffs: vec![*reference_diff],
698                })
699                .collect();
700        }
701        Ok(Vp9ScalabilityStructure {
702            spatial_layers: mode.spatial_layers(),
703            resolutions,
704            picture_group,
705        })
706    }
707}