rtci_rtp/codec/dependency_descriptor/selector.rs
1//! Forwarding by decode target.
2
3use std::collections::{HashMap, VecDeque};
4
5use super::{
6 DecodeTargetIndication, DependencyDescriptor, DependencyDescriptorReader,
7 FrameDependencyStructure,
8};
9
10/// How many frames back the selector remembers what it did with a frame.
11const HISTORY: usize = 1024;
12
13/// What the selector remembers of a frame it has seen.
14#[derive(Debug, Clone, Copy)]
15struct FrameRecord {
16 forwarded: bool,
17 /// Per chain (a bit each): the receiver was sent the previous frame of the chain, and all
18 /// of the chain before it.
19 chains_forwarded: u32,
20}
21
22/// Decides, in a forwarder, which frames of a stream to forward to one receiver, from the
23/// Dependency Descriptor alone (AV1 RTP specification A.1, A.5 to A.7).
24///
25/// The receiver's target is a spatial and a temporal layer; the selector maps it to the best
26/// active decode target of the structure in force and forwards the frames that are part of
27/// it. Give it every packet's descriptor in RTP sequence number order, after the
28/// [`DependencyDescriptorReader`] has read it.
29///
30/// * A frame is forwarded when it is part of the decode target in use (its indication is not
31/// "not present") and none of the frames it refers to was withheld from this receiver.
32/// * The decode target changes at a frame with a Switch indication for the wanted target, or
33/// at any frame of it when the chain that protects the wanted target is intact for this
34/// receiver, that is every frame of the chain was forwarded to it (A.7).
35/// * [`chain_intact`](Self::chain_intact) says whether the forwarder itself has received every
36/// frame of the chain that protects the target in use. When it has not, a frame the target
37/// needs was lost on the way in (A.6), and the forwarder asks for it (NACK) or for a key
38/// frame.
39#[derive(Debug, Clone)]
40pub struct DecodeTargetSelector {
41 target_spatial_id: u8,
42 target_temporal_id: u8,
43 /// The decode target forwarded at the moment.
44 current: Option<usize>,
45 /// The frames seen lately, by frame number, and the order they came in.
46 frames: HashMap<u16, FrameRecord>,
47 order: VecDeque<u16>,
48 /// Per chain: a frame of it that later frames point to and that has not been seen.
49 missing: Vec<Option<u16>>,
50 /// The first frame seen of the coded video sequence in progress: what is older was never
51 /// this selector's to see.
52 first_seen: Option<u16>,
53}
54
55impl DecodeTargetSelector {
56 /// A selector for a receiver that wants spatial layer `spatial_id` and the temporal layers
57 /// up to `temporal_id`.
58 pub fn new(spatial_id: u8, temporal_id: u8) -> Self {
59 Self {
60 target_spatial_id: spatial_id,
61 target_temporal_id: temporal_id,
62 current: None,
63 frames: HashMap::new(),
64 order: VecDeque::new(),
65 missing: vec![],
66 first_seen: None,
67 }
68 }
69
70 /// Changes the layers the receiver wants. It takes effect at the next frame the stream
71 /// allows a switch at.
72 pub fn set_target(&mut self, spatial_id: u8, temporal_id: u8) {
73 self.target_spatial_id = spatial_id;
74 self.target_temporal_id = temporal_id;
75 }
76
77 /// The layers the receiver wants.
78 pub fn target(&self) -> (u8, u8) {
79 (self.target_spatial_id, self.target_temporal_id)
80 }
81
82 /// The decode target being forwarded, once a frame has been.
83 pub fn current_decode_target(&self) -> Option<usize> {
84 self.current
85 }
86
87 /// The decode target the receiver's layers map to in `structure`, among those active in
88 /// `active_decode_targets`: the one of exactly these layers, or the best below them.
89 pub fn wanted_decode_target(
90 &self,
91 structure: &FrameDependencyStructure,
92 active_decode_targets: u32,
93 ) -> Option<usize> {
94 structure
95 .decode_target_layers()
96 .into_iter()
97 .enumerate()
98 .filter(|(dt, (s, t))| {
99 active_decode_targets.checked_shr(*dt as u32).unwrap_or(0) & 1 == 1
100 && *s <= self.target_spatial_id
101 && *t <= self.target_temporal_id
102 })
103 .max_by_key(|(dt, (s, t))| (*s, *t, std::cmp::Reverse(*dt)))
104 .map(|(dt, _)| dt)
105 }
106
107 /// Whether the decode target in use is not the wanted one: the stream has not offered a
108 /// switch point yet. A forwarder that cannot wait asks the sender for a key frame.
109 pub fn switch_pending(&self, reader: &DependencyDescriptorReader) -> bool {
110 let Some(structure) = reader.structure() else {
111 return true;
112 };
113 self.current != self.wanted_decode_target(structure, reader.active_decode_targets())
114 }
115
116 /// Whether every frame of the chain that protects the decode target in use has been seen
117 /// by this selector, as far as the descriptors seen so far tell. `false` after a loss on
118 /// the way in that the target cannot do without, until the missing frame arrives or the
119 /// chain starts again. `true` when the structure has no chains, or before anything was
120 /// forwarded.
121 pub fn chain_intact(&self, reader: &DependencyDescriptorReader) -> bool {
122 let (Some(structure), Some(current)) = (reader.structure(), self.current) else {
123 return true;
124 };
125 match structure.decode_target_protected_by.get(current) {
126 Some(chain) => self
127 .missing
128 .get(*chain as usize)
129 .is_none_or(|missing| missing.is_none()),
130 None => true,
131 }
132 }
133
134 /// Decides whether to forward the packet `descriptor` was read from. `reader` is the
135 /// reader that read it (for the structure in force and the active decode targets).
136 pub fn forward(
137 &mut self,
138 descriptor: &DependencyDescriptor,
139 reader: &DependencyDescriptorReader,
140 ) -> bool {
141 let frame_number = descriptor.frame_number;
142 // One decision per frame: the frame's other packets, and a repeated packet, get the
143 // one its first packet got.
144 if let Some(record) = self.frames.get(&frame_number) {
145 return record.forwarded;
146 }
147 let Some(structure) = reader.structure() else {
148 return false;
149 };
150 if descriptor.attached_structure.is_some() {
151 // A new coded video sequence: nothing before it matters any more.
152 self.frames.clear();
153 self.order.clear();
154 self.current = None;
155 self.missing.clear();
156 self.first_seen = None;
157 }
158 self.missing.resize(structure.num_chains, None);
159 let first_seen = *self.first_seen.get_or_insert(frame_number);
160
161 // What the receiver has of each chain, and what this forwarder has.
162 let mut chains_forwarded = 0u32;
163 // (A descriptor read with this reader's structure has one difference per chain; one
164 // from elsewhere is not trusted to.)
165 let chains = self.missing.len().min(32);
166 for (chain, chain_fdiff) in descriptor.chain_fdiffs.iter().enumerate().take(chains) {
167 if self.missing[chain] == Some(frame_number) {
168 self.missing[chain] = None;
169 }
170 if *chain_fdiff == 0 {
171 // "A value of 0 indicates no previous frames are needed for the Chain."
172 chains_forwarded |= 1 << chain;
173 self.missing[chain] = None;
174 continue;
175 }
176 let previous = descriptor.referred_frame_number(*chain_fdiff as u16);
177 match self.frames.get(&previous) {
178 Some(record) => {
179 if record.forwarded && (record.chains_forwarded >> chain) & 1 == 1 {
180 chains_forwarded |= 1 << chain;
181 }
182 }
183 // The previous frame of the chain should have come by now and did not. (One
184 // from before this selector started watching is not its loss to report.)
185 None => {
186 let watched = previous.wrapping_sub(first_seen) < 0x8000;
187 if watched && reader.chain_has_active_decode_target(chain) {
188 self.missing[chain] = Some(previous);
189 }
190 }
191 }
192 }
193
194 // A frame is decodable for this receiver unless a frame it refers to was withheld.
195 let decodable = descriptor.fdiffs.iter().all(|fdiff| {
196 self.frames
197 .get(&descriptor.referred_frame_number(*fdiff))
198 .is_none_or(|record| record.forwarded)
199 });
200 let dti = |dt: usize| {
201 descriptor
202 .dtis
203 .get(dt)
204 .copied()
205 .unwrap_or(DecodeTargetIndication::NotPresent)
206 };
207
208 // Switching (A.7).
209 let wanted = self.wanted_decode_target(structure, reader.active_decode_targets());
210 if let Some(wanted) = wanted
211 && self.current != Some(wanted)
212 && decodable
213 && dti(wanted).is_present()
214 {
215 let chain_intact = structure
216 .decode_target_protected_by
217 .get(wanted)
218 .is_some_and(|chain| {
219 chains_forwarded.checked_shr(*chain as u32).unwrap_or(0) & 1 == 1
220 });
221 if dti(wanted) == DecodeTargetIndication::Switch || chain_intact {
222 self.current = Some(wanted);
223 }
224 }
225 if wanted.is_none() {
226 // Nothing active fits the receiver's layers.
227 self.current = None;
228 }
229
230 let forward = decodable
231 && self
232 .current
233 .is_some_and(|current| dti(current).is_present());
234
235 if self.order.len() == HISTORY
236 && let Some(oldest) = self.order.pop_front()
237 {
238 self.frames.remove(&oldest);
239 }
240 if self
241 .frames
242 .insert(
243 frame_number,
244 FrameRecord {
245 forwarded: forward,
246 chains_forwarded,
247 },
248 )
249 .is_none()
250 {
251 self.order.push_back(frame_number);
252 }
253 forward
254 }
255}