Skip to main content

rtci_rtp/codec/dependency_descriptor/
mod.rs

1//! The Dependency Descriptor RTP header extension (AV1 RTP specification, appendix A).
2//!
3//! The descriptor tells a forwarder which frame a packet belongs to, which frames that frame
4//! depends on and which decode targets (a spatial and temporal fidelity) it is part of,
5//! without the forwarder reading the payload. It was designed for AV1 and is used with other
6//! codecs as well.
7//!
8//! * [`DependencyDescriptor`] is one descriptor: [`DependencyDescriptor::marshal`] writes the
9//!   extension's bytes, [`DependencyDescriptor::unmarshal`] reads them.
10//! * [`FrameDependencyStructure`] is the template dependency structure a key frame's first
11//!   packet carries, and every later descriptor refers to.
12//! * [`DependencyDescriptorWriter`] is the send side: it numbers frames, picks the template
13//!   that costs the fewest bits, attaches the structure where the specification requires it
14//!   and signals the active decode targets.
15//! * [`DependencyDescriptorReader`] is the receive side: it keeps the structure and the active
16//!   decode targets from packet to packet.
17//! * [`DecodeTargetSelector`] decides, in a forwarder, which frames to forward for a decode
18//!   target, and tells whether the chain that protects it is intact.
19//!
20//! The extension is negotiated with `a=extmap` and the URI [`DEPENDENCY_DESCRIPTOR_URI`]. Its
21//! bytes are the payload of an RTP header extension element: set them with
22//! `Header::set_extension` under the negotiated id. A descriptor that carries a structure is
23//! usually longer than 16 bytes, which needs the two-byte header form (RFC 8285).
24
25mod bits;
26#[cfg(test)]
27pub(crate) mod dependency_descriptor_test;
28mod selector;
29#[cfg(test)]
30mod selector_test;
31mod writer;
32#[cfg(test)]
33mod writer_test;
34
35pub use selector::DecodeTargetSelector;
36pub use writer::{DependencyDescriptorWriter, FrameDescriptor};
37
38use bits::{BitReader, BitWriter};
39use bytes::Bytes;
40use shared::error::{Error, Result};
41
42/// The `a=extmap` URI of the Dependency Descriptor (AV1 RTP specification A.9).
43pub const DEPENDENCY_DESCRIPTOR_URI: &str =
44    "https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";
45
46/// The most decode targets a structure can have (`dt_cnt_minus_one` is five bits).
47pub const MAX_DECODE_TARGETS: usize = 32;
48/// The most templates a structure can have (`frame_dependency_template_id` is six bits).
49pub const MAX_TEMPLATES: usize = 64;
50/// The largest frame difference a descriptor can carry (`fdiff_minus_one` is at most twelve
51/// bits).
52pub const MAX_FRAME_DIFF: u16 = 4096;
53/// The largest frame difference a template can carry (`fdiff_minus_one` is four bits there).
54pub const MAX_TEMPLATE_FRAME_DIFF: u16 = 16;
55/// The largest chain difference a template can carry (four bits).
56pub const MAX_TEMPLATE_CHAIN_DIFF: u8 = 15;
57
58fn invalid<T>(what: &str) -> Result<T> {
59    Err(Error::Other(format!("dependency descriptor: {what}")))
60}
61
62/// How a frame relates to a decode target (AV1 RTP specification, table A.1).
63#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
64#[repr(u8)]
65pub enum DecodeTargetIndication {
66    /// `-`: the frame is not part of the decode target.
67    #[default]
68    NotPresent = 0,
69    /// `D`: the frame is part of the decode target, and no frame of the target refers to it.
70    Discardable = 1,
71    /// `S`: the frame is part of the decode target, and when it is decodable every later frame
72    /// of the target is: a forwarder can switch a receiver to the target here.
73    Switch = 2,
74    /// `R`: the frame is part of the decode target, and neither of the above.
75    Required = 3,
76}
77
78impl DecodeTargetIndication {
79    fn from_bits(bits: u32) -> Self {
80        match bits & 0x3 {
81            0 => Self::NotPresent,
82            1 => Self::Discardable,
83            2 => Self::Switch,
84            _ => Self::Required,
85        }
86    }
87
88    /// The symbol the specification's tables use: `-`, `D`, `S` or `R`.
89    pub fn symbol(self) -> char {
90        match self {
91            Self::NotPresent => '-',
92            Self::Discardable => 'D',
93            Self::Switch => 'S',
94            Self::Required => 'R',
95        }
96    }
97
98    /// The indications a string of the specification's symbols stands for, one per decode
99    /// target (`"SD-"`). `None` if a character is not one of `-`, `D`, `S`, `R`.
100    pub fn from_symbols(symbols: &str) -> Option<Vec<Self>> {
101        symbols
102            .chars()
103            .map(|c| match c {
104                '-' => Some(Self::NotPresent),
105                'D' => Some(Self::Discardable),
106                'S' => Some(Self::Switch),
107                'R' => Some(Self::Required),
108                _ => None,
109            })
110            .collect()
111    }
112
113    /// Whether the frame is part of the decode target at all.
114    pub fn is_present(self) -> bool {
115        self != Self::NotPresent
116    }
117}
118
119/// A frame dependency template: what many frames of a stream have in common (AV1 RTP
120/// specification A.8.1).
121#[derive(Debug, Default, Clone, PartialEq, Eq)]
122pub struct FrameDependencyTemplate {
123    /// The spatial layer of the frames that use the template.
124    pub spatial_id: u8,
125    /// Their temporal layer.
126    pub temporal_id: u8,
127    /// `template_dti`: one indication per decode target.
128    pub dtis: Vec<DecodeTargetIndication>,
129    /// `TemplateFdiff`: for each frame referred to, how many frame numbers back it is (1 to
130    /// 16).
131    pub fdiffs: Vec<u16>,
132    /// `template_chain_fdiff`: for each chain, how many frame numbers back the previous frame
133    /// of the chain is (0 to 15; 0 when no earlier frame is needed).
134    pub chain_fdiffs: Vec<u8>,
135}
136
137/// The largest size the frames of a spatial layer are rendered at (`render_resolutions`).
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub struct RenderResolution {
140    /// Width in pixels, 1 to 65536.
141    pub width: u32,
142    /// Height in pixels, 1 to 65536.
143    pub height: u32,
144}
145
146/// The frame dependency structure of a coded video sequence (`template_dependency_structure`,
147/// AV1 RTP specification A.8.2): the decode targets, the templates and the chains.
148#[derive(Debug, Default, Clone, PartialEq, Eq)]
149pub struct FrameDependencyStructure {
150    /// `template_id_offset`: the `frame_dependency_template_id` of the first template (0 to
151    /// 63). A new structure SHOULD use ids the one before it did not.
152    pub template_id_offset: u8,
153    /// `DtCnt`: the number of decode targets, 1 to 32.
154    pub num_decode_targets: usize,
155    /// `chain_cnt`: the number of chains, 0 to `num_decode_targets`.
156    pub num_chains: usize,
157    /// `decode_target_protected_by`: for each decode target the chain that protects it. Empty
158    /// when there are no chains; otherwise one entry per decode target.
159    pub decode_target_protected_by: Vec<u8>,
160    /// `render_resolutions`: one per spatial layer, lowest first, or empty.
161    pub resolutions: Vec<RenderResolution>,
162    /// The templates, ordered by spatial then temporal layer (the syntax can only step a layer
163    /// up from one template to the next).
164    pub templates: Vec<FrameDependencyTemplate>,
165}
166
167impl FrameDependencyStructure {
168    /// Checks that the structure can be written: everything the syntax of A.8.2 can carry and
169    /// the rules of A.8.3 require.
170    pub fn validate(&self) -> Result<()> {
171        if self.template_id_offset as usize >= MAX_TEMPLATES {
172            return invalid("template_id_offset is six bits");
173        }
174        if self.num_decode_targets == 0 || self.num_decode_targets > MAX_DECODE_TARGETS {
175            return invalid("1 to 32 decode targets");
176        }
177        if self.templates.is_empty() || self.templates.len() > MAX_TEMPLATES {
178            return invalid("1 to 64 templates");
179        }
180        if self.num_chains > self.num_decode_targets {
181            return invalid("no more chains than decode targets");
182        }
183        if self.num_chains == 0 {
184            if !self.decode_target_protected_by.is_empty() {
185                return invalid("decode_target_protected_by without chains");
186            }
187        } else if self.decode_target_protected_by.len() != self.num_decode_targets
188            || self
189                .decode_target_protected_by
190                .iter()
191                .any(|c| *c as usize >= self.num_chains)
192        {
193            // "When chain_cnt > 0, each Decode target MUST be protected by exactly one Chain."
194            return invalid("each decode target is protected by one of the chains");
195        }
196
197        let mut previous = (0u8, 0u8);
198        for (i, template) in self.templates.iter().enumerate() {
199            let layer = (template.spatial_id, template.temporal_id);
200            // template_layers(): the first template is of layer (0, 0); the next one has the
201            // same layer, the next temporal layer, or temporal layer 0 of the next spatial one.
202            let reachable = if i == 0 {
203                layer == (0, 0)
204            } else {
205                layer == previous
206                    || layer == (previous.0, previous.1.wrapping_add(1))
207                    || (template.spatial_id == previous.0.wrapping_add(1)
208                        && template.temporal_id == 0)
209            };
210            if !reachable {
211                return invalid(
212                    "templates are ordered by spatial then temporal layer, without gaps",
213                );
214            }
215            previous = layer;
216
217            if template.dtis.len() != self.num_decode_targets {
218                return invalid("one decode target indication per decode target");
219            }
220            if template
221                .fdiffs
222                .iter()
223                .any(|d| *d == 0 || *d > MAX_TEMPLATE_FRAME_DIFF)
224            {
225                return invalid("a template's frame differences are 1 to 16");
226            }
227            if template.chain_fdiffs.len() != self.num_chains
228                || template
229                    .chain_fdiffs
230                    .iter()
231                    .any(|d| *d > MAX_TEMPLATE_CHAIN_DIFF)
232            {
233                return invalid("a template has one chain difference per chain, 0 to 15");
234            }
235        }
236
237        if !self.resolutions.is_empty() {
238            if self.resolutions.len() != self.max_spatial_id() as usize + 1 {
239                return invalid("one resolution per spatial layer, or none");
240            }
241            if self
242                .resolutions
243                .iter()
244                .any(|r| r.width == 0 || r.width > 65536 || r.height == 0 || r.height > 65536)
245            {
246                return invalid("a resolution is 1 to 65536 in each dimension");
247            }
248        }
249        Ok(())
250    }
251
252    /// `MaxSpatialId`: the highest spatial layer a template is of.
253    pub fn max_spatial_id(&self) -> u8 {
254        self.templates.last().map_or(0, |t| t.spatial_id)
255    }
256
257    /// `MaxTemporalId`: the highest temporal layer a template is of.
258    pub fn max_temporal_id(&self) -> u8 {
259        self.templates
260            .iter()
261            .map(|t| t.temporal_id)
262            .max()
263            .unwrap_or(0)
264    }
265
266    /// `decode_target_layers()`: for each decode target the highest spatial and temporal layer
267    /// of the frames that are part of it, which is the fidelity it stands for.
268    pub fn decode_target_layers(&self) -> Vec<(u8, u8)> {
269        (0..self.num_decode_targets.min(MAX_DECODE_TARGETS))
270            .map(|dt| {
271                let mut spatial_id = 0;
272                let mut temporal_id = 0;
273                for template in &self.templates {
274                    if template.dtis.get(dt).is_some_and(|dti| dti.is_present()) {
275                        spatial_id = spatial_id.max(template.spatial_id);
276                        temporal_id = temporal_id.max(template.temporal_id);
277                    }
278                }
279                (spatial_id, temporal_id)
280            })
281            .collect()
282    }
283
284    /// The decode target that stands for the given spatial and temporal layer: the one whose
285    /// layers are exactly those, or failing that the best one that does not exceed them.
286    pub fn decode_target_for(&self, spatial_id: u8, temporal_id: u8) -> Option<usize> {
287        self.decode_target_layers()
288            .into_iter()
289            .enumerate()
290            .filter(|(_, (s, t))| *s <= spatial_id && *t <= temporal_id)
291            .max_by_key(|(dt, (s, t))| (*s, *t, std::cmp::Reverse(*dt)))
292            .map(|(dt, _)| dt)
293    }
294
295    /// The index of the template a `frame_dependency_template_id` names, if it is one of this
296    /// structure's.
297    pub fn template_index(&self, template_id: u8) -> Option<usize> {
298        let index = (template_id as usize + MAX_TEMPLATES - self.template_id_offset as usize)
299            % MAX_TEMPLATES;
300        (index < self.templates.len()).then_some(index)
301    }
302
303    /// The `frame_dependency_template_id` of the template at `index`.
304    pub fn template_id(&self, index: usize) -> u8 {
305        ((self.template_id_offset as usize + index) % MAX_TEMPLATES) as u8
306    }
307
308    /// The bitmask with every decode target active.
309    pub fn all_decode_targets(&self) -> u32 {
310        if self.num_decode_targets >= 32 {
311            u32::MAX
312        } else {
313            (1u32 << self.num_decode_targets) - 1
314        }
315    }
316
317    /// A `template_id_offset` for a structure that replaces this one: the first id after this
318    /// structure's range, so the two do not overlap (A.8.3) as long as the new one has no
319    /// more than `64 - self.templates.len()` templates.
320    pub fn next_template_id_offset(&self) -> u8 {
321        self.template_id(self.templates.len())
322    }
323
324    /// `template_dependency_structure()`.
325    fn write(&self, w: &mut BitWriter) {
326        w.f(6, self.template_id_offset as u32);
327        w.f(5, self.num_decode_targets as u32 - 1);
328        // template_layers()
329        for (i, template) in self.templates.iter().enumerate() {
330            let next_layer_idc = match self.templates.get(i + 1) {
331                None => 3,
332                Some(next) if next.spatial_id != template.spatial_id => 2,
333                Some(next) if next.temporal_id != template.temporal_id => 1,
334                Some(_) => 0,
335            };
336            w.f(2, next_layer_idc);
337        }
338        // template_dtis()
339        for template in &self.templates {
340            for dti in &template.dtis {
341                w.f(2, *dti as u32);
342            }
343        }
344        // template_fdiffs()
345        for template in &self.templates {
346            for fdiff in &template.fdiffs {
347                w.flag(true); // fdiff_follows_flag
348                w.f(4, *fdiff as u32 - 1);
349            }
350            w.flag(false);
351        }
352        // template_chains()
353        w.ns(self.num_decode_targets as u32 + 1, self.num_chains as u32);
354        if self.num_chains > 0 {
355            for chain in &self.decode_target_protected_by {
356                w.ns(self.num_chains as u32, *chain as u32);
357            }
358            for template in &self.templates {
359                for chain_fdiff in &template.chain_fdiffs {
360                    w.f(4, *chain_fdiff as u32);
361                }
362            }
363        }
364        // resolutions_present_flag, render_resolutions()
365        w.flag(!self.resolutions.is_empty());
366        for resolution in &self.resolutions {
367            w.f(16, resolution.width - 1);
368            w.f(16, resolution.height - 1);
369        }
370    }
371
372    /// `template_dependency_structure()`.
373    fn read(r: &mut BitReader<'_>) -> Result<Self> {
374        let template_id_offset = r.f(6)? as u8;
375        let num_decode_targets = r.f(5)? as usize + 1;
376
377        // template_layers()
378        let mut templates: Vec<FrameDependencyTemplate> = vec![];
379        let (mut spatial_id, mut temporal_id) = (0u8, 0u8);
380        loop {
381            // A template id is six bits: a 65th template could never be named.
382            if templates.len() == MAX_TEMPLATES {
383                return invalid("more than 64 templates");
384            }
385            templates.push(FrameDependencyTemplate {
386                spatial_id,
387                temporal_id,
388                ..Default::default()
389            });
390            match r.f(2)? {
391                0 => {}
392                1 => temporal_id += 1,
393                2 => {
394                    temporal_id = 0;
395                    spatial_id += 1;
396                }
397                _ => break,
398            }
399        }
400        // template_dtis()
401        for template in &mut templates {
402            template.dtis.reserve_exact(num_decode_targets);
403            for _ in 0..num_decode_targets {
404                template
405                    .dtis
406                    .push(DecodeTargetIndication::from_bits(r.f(2)?));
407            }
408        }
409        // template_fdiffs()
410        for template in &mut templates {
411            while r.flag()? {
412                template.fdiffs.push(r.f(4)? as u16 + 1);
413            }
414        }
415        // template_chains()
416        let num_chains = r.ns(num_decode_targets as u32 + 1)? as usize;
417        let mut decode_target_protected_by = vec![];
418        if num_chains > 0 {
419            for _ in 0..num_decode_targets {
420                decode_target_protected_by.push(r.ns(num_chains as u32)? as u8);
421            }
422            for template in &mut templates {
423                for _ in 0..num_chains {
424                    template.chain_fdiffs.push(r.f(4)? as u8);
425                }
426            }
427        }
428        // resolutions_present_flag, render_resolutions()
429        let mut resolutions = vec![];
430        if r.flag()? {
431            for _ in 0..=spatial_id {
432                resolutions.push(RenderResolution {
433                    width: r.f(16)? + 1,
434                    height: r.f(16)? + 1,
435                });
436            }
437        }
438
439        Ok(Self {
440            template_id_offset,
441            num_decode_targets,
442            num_chains,
443            decode_target_protected_by,
444            resolutions,
445            templates,
446        })
447    }
448}
449
450/// One Dependency Descriptor: what one RTP packet says about its frame (AV1 RTP specification
451/// A.8).
452///
453/// The fields from `spatial_id` on are the frame dependency definition. On the wire they are
454/// taken from the template `template_id` names unless the descriptor overrides them; here
455/// they always hold the frame's own values, and [`DependencyDescriptor::marshal`] works out
456/// which of them need the custom fields.
457#[derive(Debug, Default, Clone, PartialEq, Eq)]
458pub struct DependencyDescriptor {
459    /// `start_of_frame`: the packet's payload begins a frame.
460    pub start_of_frame: bool,
461    /// `end_of_frame`: the packet is the last of its frame.
462    pub end_of_frame: bool,
463    /// `frame_number`: the same on every packet of a frame, one more for each frame in decode
464    /// order, wrapping after 65535.
465    pub frame_number: u16,
466    /// `frame_dependency_template_id`: the template the frame uses, the same on every packet
467    /// of the frame.
468    pub template_id: u8,
469    /// The structure this packet carries (`template_dependency_structure`): on the first
470    /// packet of a coded video sequence, and on no other.
471    pub attached_structure: Option<FrameDependencyStructure>,
472    /// `active_decode_targets_bitmask`, when the packet carries one: bit `i` is set when
473    /// decode target `i` is available. A packet with a structure and without a bitmask means
474    /// all of them are.
475    pub active_decode_targets_bitmask: Option<u32>,
476    /// The frame's spatial layer (`FrameSpatialId`).
477    pub spatial_id: u8,
478    /// The frame's temporal layer (`FrameTemporalId`).
479    pub temporal_id: u8,
480    /// `frame_dti`: the frame's indication for each decode target.
481    pub dtis: Vec<DecodeTargetIndication>,
482    /// `FrameFdiff`: for each frame this one refers to, how many frame numbers back it is (1
483    /// to 4096).
484    pub fdiffs: Vec<u16>,
485    /// `frame_chain_fdiff`: for each chain, how many frame numbers back the previous frame of
486    /// the chain is; 0 when no earlier frame is needed.
487    pub chain_fdiffs: Vec<u8>,
488    /// `FrameMaxWidth` / `FrameMaxHeight`, when the structure has resolutions. Derived when
489    /// reading; not written.
490    pub resolution: Option<RenderResolution>,
491}
492
493impl DependencyDescriptor {
494    /// A descriptor for a frame that uses the template at `template_index` of `structure`
495    /// exactly: the frame dependency definition is the template's.
496    pub fn from_template(
497        structure: &FrameDependencyStructure,
498        template_index: usize,
499        frame_number: u16,
500    ) -> Option<Self> {
501        let template = structure.templates.get(template_index)?;
502        Some(Self {
503            frame_number,
504            template_id: structure.template_id(template_index),
505            spatial_id: template.spatial_id,
506            temporal_id: template.temporal_id,
507            dtis: template.dtis.clone(),
508            fdiffs: template.fdiffs.clone(),
509            chain_fdiffs: template.chain_fdiffs.clone(),
510            resolution: structure
511                .resolutions
512                .get(template.spatial_id as usize)
513                .copied(),
514            ..Default::default()
515        })
516    }
517
518    /// The frame number of a frame this one refers to (`fdiff` is one of
519    /// [`fdiffs`](Self::fdiffs)) or of the previous frame of a chain (one of
520    /// [`chain_fdiffs`](Self::chain_fdiffs)): "the calculation is done modulo the size of the
521    /// frame_number field".
522    pub fn referred_frame_number(&self, fdiff: u16) -> u16 {
523        self.frame_number.wrapping_sub(fdiff)
524    }
525
526    /// Writes the descriptor: the payload of the header extension element.
527    ///
528    /// `structure` is the structure in force for the frame; when the descriptor attaches one
529    /// it is that one. The frame's indications, frame differences and chain differences are
530    /// compared with the template `template_id` names, and written as custom fields
531    /// (`frame_dtis`, `frame_fdiffs`, `frame_chain_fdiff`) only where they differ. A
532    /// descriptor with no structure, no bitmask and nothing custom is three bytes.
533    ///
534    /// # Errors
535    ///
536    /// What A.8.3 forbids or the syntax cannot carry: a `template_id` outside the structure's
537    /// range; a spatial or temporal layer other than the template's; a wrong number of
538    /// indications or chain differences; a frame difference outside 1 to 4096; a bitmask with
539    /// bits beyond the decode targets; an attached structure that is not `structure` or does
540    /// not [validate](FrameDependencyStructure::validate).
541    pub fn marshal(&self, structure: &FrameDependencyStructure) -> Result<Bytes> {
542        if let Some(attached) = &self.attached_structure {
543            if attached != structure {
544                return invalid("the attached structure is not the one in force");
545            }
546            attached.validate()?;
547        }
548        if structure.num_decode_targets == 0 || structure.num_decode_targets > MAX_DECODE_TARGETS {
549            return invalid("1 to 32 decode targets");
550        }
551        let Some(template_index) = structure.template_index(self.template_id) else {
552            // "MUST be in the range of template_id_offset to (template_id_offset +
553            // TemplateCnt - 1), inclusive."
554            return invalid("frame_dependency_template_id is not one of the structure's");
555        };
556        let template = &structure.templates[template_index];
557        if (template.spatial_id, template.temporal_id) != (self.spatial_id, self.temporal_id) {
558            return invalid("the frame's layer is not its template's");
559        }
560        if self.dtis.len() != structure.num_decode_targets {
561            return invalid("one decode target indication per decode target");
562        }
563        if self.chain_fdiffs.len() != structure.num_chains {
564            return invalid("one chain difference per chain");
565        }
566        if self.fdiffs.iter().any(|d| *d == 0 || *d > MAX_FRAME_DIFF) {
567            return invalid("a frame difference is 1 to 4096");
568        }
569        let all_active = structure.all_decode_targets();
570        if let Some(bitmask) = self.active_decode_targets_bitmask
571            && bitmask & !all_active != 0
572        {
573            return invalid("the bitmask names decode targets the structure does not have");
574        }
575
576        let custom_dtis = self.dtis != template.dtis;
577        let custom_fdiffs = self.fdiffs != template.fdiffs;
578        let custom_chains = self.chain_fdiffs != template.chain_fdiffs;
579        // A structure makes every decode target active; the bitmask is only needed to say
580        // otherwise.
581        let active_decode_targets = self
582            .active_decode_targets_bitmask
583            .filter(|bitmask| self.attached_structure.is_none() || *bitmask != all_active);
584
585        let mut w = BitWriter::default();
586        // mandatory_descriptor_fields()
587        w.flag(self.start_of_frame);
588        w.flag(self.end_of_frame);
589        w.f(6, self.template_id as u32);
590        w.f(16, self.frame_number as u32);
591
592        let extended = self.attached_structure.is_some()
593            || active_decode_targets.is_some()
594            || custom_dtis
595            || custom_fdiffs
596            || custom_chains;
597        if extended {
598            // extended_descriptor_fields(): present when the descriptor is longer than three
599            // bytes, which the five flags alone make it.
600            w.flag(self.attached_structure.is_some());
601            w.flag(active_decode_targets.is_some());
602            w.flag(custom_dtis);
603            w.flag(custom_fdiffs);
604            w.flag(custom_chains);
605            if let Some(attached) = &self.attached_structure {
606                attached.write(&mut w);
607            }
608            if let Some(bitmask) = active_decode_targets {
609                w.f(structure.num_decode_targets, bitmask);
610            }
611            // frame_dependency_definition()
612            if custom_dtis {
613                for dti in &self.dtis {
614                    w.f(2, *dti as u32);
615                }
616            }
617            if custom_fdiffs {
618                for fdiff in &self.fdiffs {
619                    let fdiff_minus_one = *fdiff as u32 - 1;
620                    let next_fdiff_size = match fdiff_minus_one {
621                        0..=0xF => 1,
622                        0x10..=0xFF => 2,
623                        _ => 3,
624                    };
625                    w.f(2, next_fdiff_size);
626                    w.f(4 * next_fdiff_size as usize, fdiff_minus_one);
627                }
628                w.f(2, 0);
629            }
630            if custom_chains {
631                for chain_fdiff in &self.chain_fdiffs {
632                    w.f(8, *chain_fdiff as u32);
633                }
634            }
635        }
636        // zero_padding: the writer leaves the rest of the last byte 0.
637        Ok(Bytes::from(w.finish()))
638    }
639
640    /// Reads the mandatory fields, which every descriptor has and which need no structure:
641    /// `(start_of_frame, end_of_frame, frame_dependency_template_id, frame_number)`.
642    ///
643    /// # Errors
644    ///
645    /// Fewer than three bytes.
646    pub fn unmarshal_mandatory(data: &[u8]) -> Result<(bool, bool, u8, u16)> {
647        let mut r = BitReader::new(data);
648        Ok((r.flag()?, r.flag()?, r.f(6)? as u8, r.f(16)? as u16))
649    }
650
651    /// Reads a descriptor: `data` is the payload of the header extension element and
652    /// `structure` the structure in force before this packet, if one is known.
653    ///
654    /// Returns `Ok(None)` when the descriptor cannot be interpreted because the structure it
655    /// refers to is not known: it carries none and `structure` is `None`, or its template id
656    /// is outside the known structure's range, which per A.8.3 means "a packet with the new
657    /// template dependency structure was lost or delayed". The mandatory fields of such a
658    /// packet are still readable with [`unmarshal_mandatory`](Self::unmarshal_mandatory).
659    ///
660    /// `zero_padding` is ignored, whatever it holds.
661    ///
662    /// # Errors
663    ///
664    /// A descriptor that ends before its fields do, or a structure with more than 64
665    /// templates.
666    pub fn unmarshal(
667        data: &[u8],
668        structure: Option<&FrameDependencyStructure>,
669    ) -> Result<Option<Self>> {
670        let mut r = BitReader::new(data);
671        // mandatory_descriptor_fields()
672        let mut descriptor = Self {
673            start_of_frame: r.flag()?,
674            end_of_frame: r.flag()?,
675            template_id: r.f(6)? as u8,
676            frame_number: r.f(16)? as u16,
677            ..Default::default()
678        };
679
680        let mut custom_dtis = false;
681        let mut custom_fdiffs = false;
682        let mut custom_chains = false;
683        let mut active_decode_targets_present = false;
684        if data.len() > 3 {
685            // extended_descriptor_fields()
686            let structure_present = r.flag()?;
687            active_decode_targets_present = r.flag()?;
688            custom_dtis = r.flag()?;
689            custom_fdiffs = r.flag()?;
690            custom_chains = r.flag()?;
691            if structure_present {
692                descriptor.attached_structure = Some(FrameDependencyStructure::read(&mut r)?);
693            }
694        }
695        let Some(structure) = descriptor.attached_structure.as_ref().or(structure) else {
696            return Ok(None);
697        };
698        if active_decode_targets_present {
699            descriptor.active_decode_targets_bitmask = Some(r.f(structure.num_decode_targets)?);
700        }
701
702        // frame_dependency_definition()
703        let Some(template_index) = structure.template_index(descriptor.template_id) else {
704            return Ok(None);
705        };
706        let template = &structure.templates[template_index];
707        descriptor.spatial_id = template.spatial_id;
708        descriptor.temporal_id = template.temporal_id;
709        if custom_dtis {
710            for _ in 0..structure.num_decode_targets {
711                descriptor
712                    .dtis
713                    .push(DecodeTargetIndication::from_bits(r.f(2)?));
714            }
715        } else {
716            descriptor.dtis = template.dtis.clone();
717        }
718        if custom_fdiffs {
719            loop {
720                let next_fdiff_size = r.f(2)? as usize;
721                if next_fdiff_size == 0 {
722                    break;
723                }
724                descriptor.fdiffs.push(r.f(4 * next_fdiff_size)? as u16 + 1);
725            }
726        } else {
727            descriptor.fdiffs = template.fdiffs.clone();
728        }
729        if custom_chains {
730            for _ in 0..structure.num_chains {
731                descriptor.chain_fdiffs.push(r.f(8)? as u8);
732            }
733        } else {
734            descriptor.chain_fdiffs = template.chain_fdiffs.clone();
735        }
736        descriptor.resolution = structure
737            .resolutions
738            .get(descriptor.spatial_id as usize)
739            .copied();
740        Ok(Some(descriptor))
741    }
742}
743
744/// The receive side of the Dependency Descriptor: reads the descriptors of one RTP stream,
745/// keeping the structure and the active decode targets from packet to packet (AV1 RTP
746/// specification A.4, A.8).
747///
748/// Give it the descriptors in RTP sequence number order: "when an update to the set of active
749/// decode targets is received it is valid until the next update in RTP packet sequence number
750/// order".
751#[derive(Debug, Default, Clone)]
752pub struct DependencyDescriptorReader {
753    structure: Option<FrameDependencyStructure>,
754    active_decode_targets: u32,
755}
756
757impl DependencyDescriptorReader {
758    /// A reader that has seen no structure yet.
759    pub fn new() -> Self {
760        Self::default()
761    }
762
763    /// Reads the next packet's descriptor. `Ok(None)` when it refers to a structure this
764    /// reader does not have (see [`DependencyDescriptor::unmarshal`]): the packet that carried
765    /// it was lost, and the stream cannot be interpreted until a new one arrives (a key
766    /// frame).
767    ///
768    /// # Errors
769    ///
770    /// A malformed descriptor.
771    pub fn read(&mut self, data: &[u8]) -> Result<Option<DependencyDescriptor>> {
772        let Some(descriptor) = DependencyDescriptor::unmarshal(data, self.structure.as_ref())?
773        else {
774            return Ok(None);
775        };
776        if let Some(structure) = &descriptor.attached_structure {
777            // "Implicitly ... in which case all Decode targets are active."
778            self.active_decode_targets = structure.all_decode_targets();
779            self.structure = Some(structure.clone());
780        }
781        if let Some(bitmask) = descriptor.active_decode_targets_bitmask {
782            self.active_decode_targets = bitmask;
783        }
784        Ok(Some(descriptor))
785    }
786
787    /// The structure in force: the last one a packet carried.
788    pub fn structure(&self) -> Option<&FrameDependencyStructure> {
789        self.structure.as_ref()
790    }
791
792    /// The decode targets available at the moment, as a bitmask (bit `i` for decode target
793    /// `i`): the last update received.
794    pub fn active_decode_targets(&self) -> u32 {
795        self.active_decode_targets
796    }
797
798    /// Whether a chain protects a decode target that is active (`ChainHasActiveDecodeTarget`
799    /// of A.6). "Chains protecting no active Decode targets MUST be ignored."
800    pub fn chain_has_active_decode_target(&self, chain: usize) -> bool {
801        chain_has_active_decode_target(self.structure.as_ref(), self.active_decode_targets, chain)
802    }
803
804    /// Whether the frame `descriptor` describes is part of an active chain
805    /// (`PartOfActiveChain` of A.6): when a packet of the frame is lost, the frame is one the
806    /// chain's decode targets cannot do without.
807    pub fn part_of_active_chain(&self, descriptor: &DependencyDescriptor, chain: usize) -> bool {
808        let Some(structure) = &self.structure else {
809            return false;
810        };
811        if !self.chain_has_active_decode_target(chain) {
812            return false;
813        }
814        structure
815            .decode_target_protected_by
816            .iter()
817            .enumerate()
818            .filter(|(_, protected_by)| **protected_by as usize == chain)
819            .all(|(dt, _)| {
820                !matches!(
821                    descriptor.dtis.get(dt),
822                    None | Some(
823                        DecodeTargetIndication::NotPresent | DecodeTargetIndication::Discardable
824                    )
825                )
826            })
827    }
828}
829
830/// `ChainHasActiveDecodeTarget` of A.6.
831fn chain_has_active_decode_target(
832    structure: Option<&FrameDependencyStructure>,
833    active_decode_targets: u32,
834    chain: usize,
835) -> bool {
836    structure.is_some_and(|structure| {
837        structure
838            .decode_target_protected_by
839            .iter()
840            .enumerate()
841            .any(|(dt, protected_by)| {
842                *protected_by as usize == chain
843                    && active_decode_targets.checked_shr(dt as u32).unwrap_or(0) & 1 == 1
844            })
845    })
846}