Skip to main content

rtci_rtp/codec/dependency_descriptor/
writer.rs

1//! The send side of the Dependency Descriptor.
2
3use std::sync::Arc;
4
5use bytes::Bytes;
6use shared::error::Result;
7
8use super::{DependencyDescriptor, FrameDependencyStructure, FrameDependencyTemplate, invalid};
9
10/// The send side of the Dependency Descriptor for one RTP stream (AV1 RTP specification A.4,
11/// A.8.3).
12///
13/// For each frame, in decode order, [`next_frame`](Self::next_frame) takes what the encoder
14/// says about it and returns a [`FrameDescriptor`], which writes the header extension of each
15/// of the frame's packets. The writer
16///
17/// * numbers the frames (`frame_number`, one more per frame, wrapping after 65535);
18/// * picks, among the structure's templates of the frame's layer, the one that needs the
19///   fewest custom bits (none, when the frame follows a template);
20/// * attaches the structure to the first packet of a coded video sequence and to no other;
21/// * signals the active decode targets when they change, on every packet until
22///   [`active_decode_targets_acknowledged`](Self::active_decode_targets_acknowledged) or a new
23///   coded video sequence with all of them active.
24#[derive(Debug, Clone)]
25pub struct DependencyDescriptorWriter {
26    structure: Arc<FrameDependencyStructure>,
27    /// The structure has not gone out yet: the next frame has to start a coded video sequence.
28    structure_pending: bool,
29    next_frame_number: u16,
30    active_decode_targets: u32,
31    /// The receiver may not know the active decode targets.
32    signal_active_decode_targets: bool,
33}
34
35impl DependencyDescriptorWriter {
36    /// A writer for a stream with this structure. `initial_frame_number` is the first frame's
37    /// number, which "MAY start on a random number".
38    ///
39    /// # Errors
40    ///
41    /// A structure that does not [validate](FrameDependencyStructure::validate).
42    pub fn new(structure: FrameDependencyStructure, initial_frame_number: u16) -> Result<Self> {
43        structure.validate()?;
44        let active_decode_targets = structure.all_decode_targets();
45        Ok(Self {
46            structure: Arc::new(structure),
47            structure_pending: true,
48            next_frame_number: initial_frame_number,
49            active_decode_targets,
50            signal_active_decode_targets: false,
51        })
52    }
53
54    /// The structure in force.
55    pub fn structure(&self) -> &FrameDependencyStructure {
56        &self.structure
57    }
58
59    /// The number the next frame gets.
60    pub fn next_frame_number(&self) -> u16 {
61        self.next_frame_number
62    }
63
64    /// Replaces the structure, for the coded video sequence the next frame starts. All decode
65    /// targets of the new structure are active.
66    ///
67    /// Its `template_id_offset` SHOULD keep its template ids clear of the current structure's
68    /// ([`FrameDependencyStructure::next_template_id_offset`] gives one that does), so that a
69    /// receiver that missed the new structure does not read the old templates into the new
70    /// ids.
71    ///
72    /// # Errors
73    ///
74    /// A structure that does not validate, or one with the current `template_id_offset` and
75    /// anything else different: "when template_id_offset of a new
76    /// template_dependency_structure is the same as in the existing
77    /// template_dependency_structure, all fields in both template_dependency_structures MUST
78    /// have identical values".
79    pub fn set_structure(&mut self, structure: FrameDependencyStructure) -> Result<()> {
80        structure.validate()?;
81        if structure.template_id_offset == self.structure.template_id_offset
82            && structure != *self.structure
83        {
84            return invalid("a different structure needs a different template_id_offset");
85        }
86        self.active_decode_targets = structure.all_decode_targets();
87        self.signal_active_decode_targets = false;
88        self.structure = Arc::new(structure);
89        self.structure_pending = true;
90        Ok(())
91    }
92
93    /// The active decode targets, as a bitmask.
94    pub fn active_decode_targets(&self) -> u32 {
95        self.active_decode_targets
96    }
97
98    /// Changes the set of active decode targets (bit `i` for decode target `i`), for example
99    /// when the encoder stops producing a spatial layer. "Whenever the set of active Decode
100    /// targets changes, the sender MUST signal the new set": from the next packet on every
101    /// descriptor carries the bitmask.
102    ///
103    /// # Errors
104    ///
105    /// A bitmask with bits beyond the structure's decode targets.
106    pub fn set_active_decode_targets(&mut self, bitmask: u32) -> Result<()> {
107        if bitmask & !self.structure.all_decode_targets() != 0 {
108            return invalid("the bitmask names decode targets the structure does not have");
109        }
110        if bitmask != self.active_decode_targets {
111            self.active_decode_targets = bitmask;
112            self.signal_active_decode_targets = true;
113        }
114        Ok(())
115    }
116
117    /// Stops repeating the bitmask: the receiver is known to have a packet that carried it
118    /// (a receiver report acknowledged one). One of the techniques A.4 names.
119    pub fn active_decode_targets_acknowledged(&mut self) {
120        self.signal_active_decode_targets = false;
121    }
122
123    /// Describes the next frame in decode order.
124    ///
125    /// `frame` holds the frame's own layer, decode target indications, frame differences
126    /// (how many frames back each frame it refers to is, in the frames given to this writer)
127    /// and chain differences. `starts_coded_video_sequence` is set for the first frame of a
128    /// coded video sequence (a key frame the stream can be joined at): its first packet
129    /// carries the structure.
130    ///
131    /// # Errors
132    ///
133    /// The stream's first frame, or the first after [`set_structure`](Self::set_structure),
134    /// does not start a coded video sequence (the receiver would never get the structure); the
135    /// structure has no template of the frame's layer; or the frame's values are ones
136    /// [`DependencyDescriptor::marshal`] refuses.
137    pub fn next_frame(
138        &mut self,
139        frame: &FrameDependencyTemplate,
140        starts_coded_video_sequence: bool,
141    ) -> Result<FrameDescriptor> {
142        if self.structure_pending && !starts_coded_video_sequence {
143            return invalid(
144                "the structure has to go out on a frame that starts a coded video sequence",
145            );
146        }
147        let structure = &self.structure;
148        // The template of the frame's layer that costs the fewest bits to correct.
149        let best = structure
150            .templates
151            .iter()
152            .enumerate()
153            .filter(|(_, t)| (t.spatial_id, t.temporal_id) == (frame.spatial_id, frame.temporal_id))
154            .min_by_key(|(_, t)| {
155                let mut bits = 0;
156                if t.dtis != frame.dtis {
157                    bits += 2 * structure.num_decode_targets;
158                }
159                if t.fdiffs != frame.fdiffs {
160                    bits += 2 + frame
161                        .fdiffs
162                        .iter()
163                        .map(|d| match d.saturating_sub(1) {
164                            0..=0xF => 6,
165                            0x10..=0xFF => 10,
166                            _ => 14,
167                        })
168                        .sum::<usize>();
169                }
170                if t.chain_fdiffs != frame.chain_fdiffs {
171                    bits += 8 * structure.num_chains;
172                }
173                bits
174            });
175        let Some((template_index, _)) = best else {
176            return invalid("the structure has no template of the frame's layer");
177        };
178
179        if starts_coded_video_sequence
180            && self.active_decode_targets == structure.all_decode_targets()
181        {
182            // The structure says all decode targets are active.
183            self.signal_active_decode_targets = false;
184        }
185        let descriptor = DependencyDescriptor {
186            frame_number: self.next_frame_number,
187            template_id: structure.template_id(template_index),
188            active_decode_targets_bitmask: self
189                .signal_active_decode_targets
190                .then_some(self.active_decode_targets),
191            spatial_id: frame.spatial_id,
192            temporal_id: frame.temporal_id,
193            dtis: frame.dtis.clone(),
194            fdiffs: frame.fdiffs.clone(),
195            chain_fdiffs: frame.chain_fdiffs.clone(),
196            resolution: structure
197                .resolutions
198                .get(frame.spatial_id as usize)
199                .copied(),
200            ..Default::default()
201        };
202        // Refuse now what no packet of the frame could carry.
203        descriptor.marshal(structure)?;
204
205        self.next_frame_number = self.next_frame_number.wrapping_add(1);
206        self.structure_pending = false;
207        Ok(FrameDescriptor {
208            descriptor,
209            structure: Arc::clone(&self.structure),
210            attach_structure: starts_coded_video_sequence,
211        })
212    }
213}
214
215/// The Dependency Descriptor of one frame, ready to be written on each of its packets.
216#[derive(Debug, Clone)]
217pub struct FrameDescriptor {
218    descriptor: DependencyDescriptor,
219    structure: Arc<FrameDependencyStructure>,
220    attach_structure: bool,
221}
222
223impl FrameDescriptor {
224    /// The frame's number.
225    pub fn frame_number(&self) -> u16 {
226        self.descriptor.frame_number
227    }
228
229    /// The frame's descriptor, without the per-packet fields (`start_of_frame`,
230    /// `end_of_frame`, the attached structure).
231    pub fn descriptor(&self) -> &DependencyDescriptor {
232        &self.descriptor
233    }
234
235    /// Whether the frame starts a coded video sequence, so that its first packet carries the
236    /// structure.
237    pub fn starts_coded_video_sequence(&self) -> bool {
238        self.attach_structure
239    }
240
241    /// The header extension payload for one packet of the frame: `first` for the packet whose
242    /// payload begins the frame (`start_of_frame`), `last` for the frame's final packet
243    /// (`end_of_frame`). Every packet has the frame's `frame_number` and template id; the
244    /// structure is on the first packet of a frame that starts a coded video sequence only.
245    pub fn packet(&self, first: bool, last: bool) -> Result<Bytes> {
246        let mut descriptor = self.descriptor.clone();
247        descriptor.start_of_frame = first;
248        descriptor.end_of_frame = last;
249        if first && self.attach_structure {
250            descriptor.attached_structure = Some((*self.structure).clone());
251        }
252        descriptor.marshal(&self.structure)
253    }
254}