1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::sync::atomic::{AtomicBool, Ordering};
use crate::data::Data;
use crate::error::TealdustError;
use crate::internal::DecoderContext;
use crate::obu;
use crate::picture::{Picture, ThreadPicture};
pub const MAX_THREADS: u32 = 256;
pub const MAX_FRAME_DELAY: u32 = 256;
/// Default untrusted-data frame-size cap. 4096x2304 keeps normal 4K/2.5MP
/// fuzz/bench clips inside the default decoder, while avoiding repeated huge
/// allocations from tiny malformed headers. Set `Settings::frame_size_limit = 0`
/// explicitly for trusted streams that may exceed this.
pub const DEFAULT_FRAME_SIZE_LIMIT: u32 = 4096 * 2304;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
/// Which in-loop filters to apply during decoding.
#[non_exhaustive]
#[derive(Default)]
pub enum InloopFilterType {
None = 0,
Deblock = 1,
Cdef = 2,
Ccso = 4,
Wiener = 8,
Gdf = 16,
#[default]
All = 31,
}
impl InloopFilterType {
/// (DEBLOCK=1<<0, CDEF=1<<1, CCSO=1<<2, WIENER=1<<3, GDF=1<<4). The enum's
/// numeric repr already matches these C bits; bit 2 is published as
pub(crate) fn to_flags(self) -> u32 {
self as u8 as u32
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
/// Which frame types to decode.
#[non_exhaustive]
#[derive(Default)]
pub enum DecodeFrameType {
#[default]
All = 0,
Reference = 1,
Intra = 2,
Key = 3,
}
/// Decoder configuration. Use `Settings::default()` for sensible defaults.
#[derive(Debug, Clone)]
pub struct Settings {
/// Number of worker threads (tile-row parallel decode). 0 = single-threaded.
pub n_threads: u32,
/// Maximum frame delay for pipelining. 0 = auto based on thread count.
pub max_frame_delay: u32,
/// Apply film grain synthesis to decoded output.
pub apply_grain: bool,
/// Scalability operating point index (0–31).
pub operating_point: u32,
/// Output all temporal/spatial layers.
pub all_layers: bool,
/// Maximum frame size in pixels (width × height).
///
/// `Settings::default()` uses [`DEFAULT_FRAME_SIZE_LIMIT`] as an
/// untrusted-data safety cap. Set this to `0` explicitly to decode trusted
/// streams without a pixel-count cap.
pub frame_size_limit: u32,
/// Abort on spec-violating bitstreams instead of best-effort.
pub strict_std_compliance: bool,
/// Output frames not marked for display.
pub output_invisible_frames: bool,
/// Which in-loop filters to apply.
pub inloop_filters: InloopFilterType,
/// Which frame types to decode.
pub decode_frame_type: DecodeFrameType,
/// Bring-up gate: actually run reconstruction (intra only so far) and emit
/// pictures. Default off while recon/filters are incomplete; enabled by the
/// conformance harness. Will become unconditional once decode is complete.
pub run_decode: bool,
}
impl Default for Settings {
fn default() -> Self {
Self {
n_threads: 0,
max_frame_delay: 0,
apply_grain: true,
operating_point: 0,
all_layers: true,
frame_size_limit: DEFAULT_FRAME_SIZE_LIMIT,
strict_std_compliance: false,
output_invisible_frames: false,
inloop_filters: InloopFilterType::All,
decode_frame_type: DecodeFrameType::All,
run_decode: false,
}
}
}
fn get_num_threads(s: &Settings) -> (u32, u32) {
#[rustfmt::skip]
static FC_LUT: [u8; 49] = [
1,
2, 2, 2,
3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
];
let n_tc = s.n_threads.clamp(1, MAX_THREADS);
let n_fc = if s.max_frame_delay > 0 {
s.max_frame_delay.min(n_tc)
} else if n_tc < 50 {
FC_LUT[(n_tc - 1) as usize] as u32
} else {
8
};
(n_tc, n_fc)
}
pub fn get_frame_delay(s: &Settings) -> Result<u32, TealdustError> {
if s.n_threads > MAX_THREADS || s.max_frame_delay > MAX_FRAME_DELAY {
return Err(TealdustError::InvalidParam);
}
let (_, n_fc) = get_num_threads(s);
Ok(n_fc)
}
struct OutputQueue {
pic: ThreadPicture,
}
/// AV2 bitstream decoder.
///
/// Feed compressed OBU data with [`send_data`](Self::send_data), then
/// pull decoded frames with [`get_picture`](Self::get_picture).
pub struct Decoder {
n_tc: u32,
n_fc: u32,
ctx: DecoderContext,
input: Data,
drain: bool,
flush: AtomicBool,
dpb: Vec<OutputQueue>,
dpb_in: usize,
dpb_out: usize,
dpb_sz: usize,
}
impl Decoder {
/// Create a new decoder with the given settings.
pub fn open(s: &Settings) -> Result<Self, TealdustError> {
if s.n_threads > MAX_THREADS || s.max_frame_delay > MAX_FRAME_DELAY {
return Err(TealdustError::InvalidParam);
}
if s.operating_point > 31 {
return Err(TealdustError::InvalidParam);
}
let (n_tc, n_fc) = get_num_threads(s);
let dpb_sz = n_fc as usize + 16;
let mut dpb = Vec::with_capacity(dpb_sz);
for _ in 0..dpb_sz {
dpb.push(OutputQueue {
pic: ThreadPicture::new(),
});
}
let exec = crate::exec_context::ExecContext::new();
let ctx = DecoderContext {
exec: exec.clone(),
seq_hdr: None,
frame_hdr: None,
tile: Vec::new(),
n_tile_data: 0,
n_tiles: 0,
refs: Default::default(),
content_light: None,
mastering_display: None,
ci: None,
fgm: Default::default(),
apply_grain: s.apply_grain,
operating_point_idc: 0,
max_spatial_id: 0,
frame_size_limit: s.frame_size_limit,
strict_std_compliance: s.strict_std_compliance,
inloop_filters: s.inloop_filters.to_flags(),
run_decode: s.run_decode,
frame_out: Vec::new(),
n_tc,
pool: if n_tc >= 2 {
Some(crate::mtpool::ThreadPool::new((n_tc - 1) as usize))
} else {
None
},
pic_allocator: std::sync::Arc::new(crate::picture::PoolPicAllocator::new()),
fc: crate::internal::FrameContext {
exec,
..crate::internal::FrameContext::default()
},
};
Ok(Self {
n_tc,
n_fc,
ctx,
input: Data::new(),
drain: false,
flush: AtomicBool::new(false),
dpb,
dpb_in: 0,
dpb_out: 0,
dpb_sz,
})
}
/// Feed compressed data to the decoder. Pass `None` to signal end-of-stream.
///
/// Returns `Err(Again)` if the decoder hasn't consumed previous data yet;
/// call `get_picture` to drain output before sending more.
pub fn send_data(&mut self, data: Option<Data>) -> Result<(), TealdustError> {
match data {
None => {
self.drain = true;
Ok(())
}
Some(d) => {
if self.drain {
return Err(TealdustError::Eof);
}
if d.is_empty() || d.len() > usize::MAX / 2 {
return Err(TealdustError::InvalidParam);
}
if self.input.has_data() {
return Err(TealdustError::Again);
}
self.input = d;
Ok(())
}
}
}
/// Retrieve a decoded picture from the output queue.
///
/// Returns `Err(Again)` when no picture is available yet (send more data).
/// Returns `Err(Eof)` when the stream has been fully drained.
pub fn get_picture(&mut self) -> Result<Picture, TealdustError> {
self.gen_picture()?;
if self.drain {
crate::output_order::flush_remaining(&mut self.ctx);
self.enqueue_frame_out();
}
self.output_image()
}
fn output_picture_ready(&self) -> bool {
self.dpb_out != self.dpb_in
}
fn gen_picture(&mut self) -> Result<(), TealdustError> {
if self.output_picture_ready() {
return Ok(());
}
while !self.input.is_empty() {
let data = match self.input.data() {
Some(d) => d,
None => break,
};
match obu::parse_obus(&mut self.ctx, data) {
Ok(consumed) => {
if consumed > self.input.len() {
self.input.unref();
return Err(TealdustError::InvalidObu);
}
self.input.consume(consumed);
if self.input.is_empty() {
self.input.unref();
}
// Frames output during parsing (a single parse_obus call may
// output several), in output order.
self.enqueue_frame_out();
}
Err(e) => {
// A malformed OBU can force large transient frame/tile/scratch
// allocations before the parser eventually rejects it. Do not
// keep those capacities around for the next fuzz iteration or
// next untrusted packet on the same decoder.
self.flush();
return Err(e);
}
}
if self.output_picture_ready() {
break;
}
}
Ok(())
}
fn output_image(&mut self) -> Result<Picture, TealdustError> {
if self.dpb_in == self.dpb_out {
if !self.drain {
return Err(TealdustError::Again);
}
self.drain = false;
return Err(TealdustError::Eof);
}
let q = &mut self.dpb[self.dpb_out];
let mut pic = Picture::new();
std::mem::swap(&mut pic, &mut q.pic.p);
q.pic.unref();
self.dpb_out += 1;
if self.dpb_out == self.dpb_sz {
self.dpb_out = 0;
}
// Film grain is display-only: it must not feed inter prediction, so it is
// applied to a fresh output copy here (the DPB/reference copy stays
// The grain synthesis + base copy are parallelised across `n_tc` threads
// (`n_tc == 1` keeps the byte-identical sequential path).
if self.ctx.apply_grain && crate::decode::picture_has_grain(&pic) {
let grained = crate::decode::apply_grain_to_picture_mt(
&pic,
self.n_tc,
self.ctx.pool.as_ref(),
self.ctx.pic_allocator.clone(),
);
pic.unref();
return Ok(grained);
}
Ok(pic)
}
/// Moves the frames output by the parser into the output ring.
fn enqueue_frame_out(&mut self) {
for pic in self.ctx.frame_out.drain(..) {
self.dpb[self.dpb_in].pic.p = pic;
self.dpb_in += 1;
if self.dpb_in == self.dpb_sz {
self.dpb_in = 0;
}
}
}
/// Reset the decoder state, discarding all buffered data and references.
pub fn flush(&mut self) {
self.input.unref();
for q in &mut self.dpb {
if q.pic.p.has_data() {
q.pic.unref();
}
}
self.dpb_in = 0;
self.dpb_out = 0;
self.drain = false;
for r in &mut self.ctx.refs {
r.segmap = None;
r.refmvs = None;
r.ccsomap = None;
r.p.showable = false;
r.p.frame_hdr = None;
r.p.pic = None;
r.refpoc = [0; 7];
}
self.ctx.frame_hdr = None;
self.ctx.seq_hdr = None;
self.ctx.tile.clear();
self.ctx.tile.shrink_to_fit();
self.ctx.n_tile_data = 0;
self.ctx.n_tiles = 0;
self.ctx.frame_out.clear();
self.ctx.frame_out.shrink_to_fit();
// `FrameContext` is intentionally reusable during normal decode, but a
// public flush/error reset should not retain attacker-sized allocation
// capacities. Drop it back to the zero-allocation default.
self.ctx.fc = crate::internal::FrameContext {
exec: self.ctx.exec.clone(),
..crate::internal::FrameContext::default()
};
self.ctx.pic_allocator.clear_pool();
crate::decode::clear_thread_local_decode_scratch();
self.flush.store(false, Ordering::Release);
}
pub fn n_threads(&self) -> u32 {
self.n_tc
}
pub fn n_frame_contexts(&self) -> u32 {
self.n_fc
}
}
impl Drop for Decoder {
fn drop(&mut self) {
self.flush();
}
}
pub fn version() -> &'static str {
"0.1.0"
}
pub fn version_api() -> u32 {
1 << 8
}