mediadecode_ffmpeg/limits.rs
1//! Resource ceilings — the finite budgets every copy across the FFmpeg
2//! boundary is checked against **before** it allocates.
3//!
4//! These seats are tier one and tier two of the [resource governance
5//! contract][gov]: what this crate allocates itself, and the FFmpeg
6//! knobs it sets on the caller's behalf. The contract also states what
7//! they do **not** bound, and what a deployment needing a hard memory
8//! bound puts underneath them — read it before sizing these for a
9//! hostile-input service.
10//!
11//! # Why these exist
12//!
13//! 0.9 made every exit copy (see [the amputation contract][law]). A copy
14//! is a decision to allocate whatever the file asks for, and a container
15//! is untrusted input: a header claiming 100000×100000 pixels, a packet
16//! claiming a gigabyte, a Matroska with a thousand attached "fonts" all
17//! cost nothing to write and everything to honour. Through 0.8 the
18//! frame and packet payloads were *views*, so an absurd claim cost a
19//! refcount; from 0.9 it costs memory, and the claim has to be judged
20//! before it is paid.
21//!
22//! Every seat here is a **finite default**, not an `Option`. There is no
23//! "unlimited" spelling on purpose: the shape that lets a caller ask for
24//! no ceiling is the shape a caller reaches for once, in a hurry, and
25//! never revisits. A caller who needs more says how much more.
26//!
27//! # Two layers, one number
28//!
29//! [`FrameLimits::max_pixels`] is enforced twice: once here, against the
30//! frame this crate is about to copy, and once inside libavcodec, by
31//! writing the same number to `AVCodecContext.max_pixels` when a decoder
32//! is opened. The second is the one that matters most — it makes the
33//! decoder refuse before allocating *its* huge frame, which this crate
34//! would otherwise only get to reject after FFmpeg had already paid for
35//! it.
36//!
37//! # The house shape
38//!
39//! `DEFAULT_*` consts, `Copy` options structs with `new` / getters /
40//! `with_*` / `set_*`, and a `with_*` seat on each session — the same
41//! shape [`crate::VideoDecoder::with_max_probe_pending_bytes`] and its
42//! [`DEFAULT_MAX_PROBE_PENDING_BYTES`](crate::decoder::DEFAULT_MAX_PROBE_PENDING_BYTES)
43//! already established for the probe-replay budget.
44//!
45//! [law]: mediadecode::adapter#the-d-seat-amputation-contract
46//! [gov]: mediadecode::adapter#the-resource-governance-contract
47
48/// Default ceiling on a decoded frame's pixel count — 256 mebipixels.
49///
50/// **Why this number.** The largest picture anything ships is 8K UHD
51/// (7680×4320 ≈ 33 Mpx); 16K×16K, which nothing does, is 268 Mpx. This
52/// default sits exactly there: every real frame passes, and the
53/// hand-written header claiming 100000×100000 (10 Gpx) is refused
54/// before a byte is allocated — by libavcodec first, since the same
55/// number is written to `AVCodecContext.max_pixels`, and by this crate
56/// second.
57///
58/// FFmpeg's own default for that option is `INT_MAX`, i.e. no ceiling
59/// worth the name. Overriding it is the point.
60pub const DEFAULT_MAX_PIXELS: u64 = 256 * 1024 * 1024;
61
62/// Default ceiling on the bytes one decoded frame may export — 512 MiB.
63///
64/// **Why this number.** Pixels alone do not bound the copy: bit depth,
65/// plane count and stride padding all multiply it. The widest realistic
66/// frame is 8K 4:4:4 16-bit with alpha (7680×4320×8 bytes ≈ 253 MiB);
67/// 8K P010 is ~96 MiB and 4K P010 ~24 MiB. 512 MiB clears the worst of
68/// those by 2× and still bounds a single frame to something a process
69/// can survive.
70///
71/// Checked against the sum of what the planes will actually export —
72/// after the stride decision, so it is the number this crate is about
73/// to allocate rather than an estimate of it.
74pub const DEFAULT_MAX_FRAME_BYTES: usize = 512 * 1024 * 1024;
75
76/// Default ceiling on one packet's payload — 1 GiB.
77///
78/// **Why this number.** Deliberately ceiling-class rather than tuned:
79/// `AVPacket.size` is a `c_int`, so 2 GiB is the structural maximum and
80/// this halves it. Real packets are nowhere near — an intra-only 8K
81/// ProRes 4444 XQ frame is ~10 MB, an uncompressed v210 8K frame ~88
82/// MB, and a whole-file attachment (the largest packet shape that
83/// exists) is bounded far below by
84/// [`DEFAULT_MAX_ATTACHMENT_BYTES`]. The job here is to refuse the
85/// forged `size` field, not to second-guess a codec.
86pub const DEFAULT_MAX_PACKET_BYTES: usize = 1024 * 1024 * 1024;
87
88/// Default ceiling on one attachment's payload — 64 MiB.
89///
90/// **Why this number.** An attachment is a whole file: cover art or a
91/// font. A generous cover is a 4000×4000 PNG at ~20 MB; the largest
92/// fonts in circulation are CJK families at ~30 MB. 64 MiB clears both
93/// and is two orders of magnitude under the packet ceiling, which is
94/// right — an attachment is the one payload captured *eagerly*, at
95/// open, before a caller has asked for anything.
96pub const DEFAULT_MAX_ATTACHMENT_BYTES: usize = 64 * 1024 * 1024;
97
98/// Default ceiling on **all** attachments in one file, together — 256
99/// MiB.
100///
101/// **Why this number, and why it is separate.** The per-attachment
102/// ceiling bounds one payload; nothing in it bounds a container that
103/// attaches four hundred of them. A subtitled release with a full ASS
104/// font set attaches perhaps ten to thirty fonts of a few MB each —
105/// call it 100 MB at the high end. 256 MiB clears that and refuses the
106/// file whose attachment table is the attack.
107///
108/// This budget is spent at **open**, because that is when this crate
109/// captures every attachment (the demux tier's "exactly one packet,
110/// before any timed packet" contract is kept by construction, and the
111/// construction is eager). A file that exhausts it fails to open, with
112/// the arm naming which track ran the total past the line.
113pub const DEFAULT_MAX_TOTAL_ATTACHMENT_BYTES: usize = 256 * 1024 * 1024;
114
115/// Default ceiling on one stream's codec-parameter heap — 16 MiB.
116///
117/// **What it bounds.** `AVCodecParameters` has three heap seats and all
118/// three come from the file: `extradata`, every entry of
119/// `coded_side_data`, and a custom `ch_layout` channel map. A track
120/// row's codec ticket mirrors all three, and rebuilding one for a
121/// decoder allocates all three again.
122///
123/// **Why this number.** The honest end of the range is small — H.264
124/// SPS/PPS extradata is tens of bytes, HEVC's a few hundred, FLAC and
125/// ALAC headers a couple of kilobytes. What sets the ceiling is
126/// `coded_side_data`: a MOV `prof` atom carries an **ICC profile**, and
127/// those are legitimately large — a few kilobytes for sRGB, half a
128/// megabyte to two megabytes for a real camera or display profile, and
129/// the largest device-link profiles in circulation reach roughly ten.
130/// 16 MiB clears all of that and still refuses the forged atom.
131pub const DEFAULT_MAX_CODEC_PARAMETER_BYTES: usize = 16 * 1024 * 1024;
132
133/// Default ceiling on **every** stream's codec-parameter heap in one
134/// file, together — 64 MiB.
135///
136/// **Why this number, and why it is separate.** The per-stream ceiling
137/// bounds one track's parameters; nothing in it bounds a container that
138/// declares two hundred tracks each carrying a two-megabyte profile.
139/// Four tracks with a large ICC profile apiece is the realistic high
140/// end, so 64 MiB clears it and refuses the stream table that is the
141/// attack.
142///
143/// Charged over **all** streams, not just the ones a caller will
144/// decode: the track table is built eagerly at open, so every stream's
145/// parameters are mirrored whether or not anybody asks for them.
146pub const DEFAULT_MAX_TOTAL_CODEC_PARAMETER_BYTES: usize = 64 * 1024 * 1024;
147
148/// The defaults have to hold together, and these say how — at compile
149/// time, because every term is a constant and a fact a build can check
150/// is a fact no test run has to.
151///
152/// Each clause is a claim the doc comments above make in prose:
153/// - every ceiling is finite and non-zero (a zero ceiling refuses
154/// everything, which is the opposite failure and just as bad);
155/// - 8K UHD, and the widest realistic frame, pass;
156/// - the 100000×100000 header does not;
157/// - a whole-file attachment budget below the per-attachment one, or a
158/// per-packet ceiling below the per-attachment one, would be
159/// incoherent — the narrower seat could never fire;
160/// - a per-packet ceiling above `c_int::MAX` could never fire either,
161/// since `AVPacket.size` cannot express it.
162const _: () = {
163 assert!(DEFAULT_MAX_PIXELS > 0 && DEFAULT_MAX_PIXELS < u64::MAX);
164 assert!(DEFAULT_MAX_FRAME_BYTES > 0 && DEFAULT_MAX_FRAME_BYTES < usize::MAX);
165 assert!(DEFAULT_MAX_PACKET_BYTES > 0 && DEFAULT_MAX_PACKET_BYTES < usize::MAX);
166 assert!(DEFAULT_MAX_ATTACHMENT_BYTES > 0);
167 assert!(DEFAULT_MAX_TOTAL_ATTACHMENT_BYTES > 0);
168
169 // 8K UHD — the largest picture anything ships — must decode.
170 assert!(7680 * 4320 < DEFAULT_MAX_PIXELS);
171 // And the widest realistic frame: 8K 4:4:4 16-bit with alpha.
172 assert!(7680 * 4320 * 8 < DEFAULT_MAX_FRAME_BYTES);
173
174 // **8K must decode in the widest format that exists, not just the
175 // widest realistic one.** The byte ceiling is pushed into libavcodec
176 // as a pixel ceiling priced at the worst per-pixel cost any format
177 // this build can emit — 16 bytes, reached by `rgbaf32` and its seven
178 // siblings — because a container's declared format is not an upper
179 // bound on what its decoder produces. That makes the effective pixel
180 // ceiling `max_frame_bytes / 16`, and this is the assertion that
181 // keeps 8K inside it: at 33.18 Mpx and 16 bytes an 8K `rgbaf32` frame
182 // is 506 MiB, which 512 MiB clears with about 1% to spare.
183 //
184 // If `DEFAULT_MAX_FRAME_BYTES` is ever lowered, or a future FFmpeg
185 // adds a format wider than 16 bytes per pixel, this fails the build
186 // rather than quietly refusing 8K at run time.
187 assert!(7680 * 4320 * 16 < DEFAULT_MAX_FRAME_BYTES);
188 // The header a fuzzer writes must not.
189 assert!(100_000 * 100_000 > DEFAULT_MAX_PIXELS);
190
191 assert!(DEFAULT_MAX_TOTAL_ATTACHMENT_BYTES >= DEFAULT_MAX_ATTACHMENT_BYTES);
192 assert!(DEFAULT_MAX_PACKET_BYTES >= DEFAULT_MAX_ATTACHMENT_BYTES);
193 assert!(DEFAULT_MAX_PACKET_BYTES <= i32::MAX as usize);
194
195 assert!(DEFAULT_MAX_CODEC_PARAMETER_BYTES > 0);
196 assert!(DEFAULT_MAX_TOTAL_CODEC_PARAMETER_BYTES >= DEFAULT_MAX_CODEC_PARAMETER_BYTES);
197 // A ten-megabyte device-link ICC profile is real media and must pass.
198 assert!(10 * 1024 * 1024 < DEFAULT_MAX_CODEC_PARAMETER_BYTES);
199
200 // **The two ICC policies agree, and this is what keeps them agreeing.**
201 // The same profile can arrive as a track parameter (`coded_side_data`)
202 // or as a decoded still's frame side data, and a ceiling that admits
203 // it on one road and drops it on the other is not a policy, it is an
204 // accident of which road the file took.
205 assert!(DEFAULT_MAX_IMAGE_SIDE_DATA_BYTES >= DEFAULT_MAX_CODEC_PARAMETER_BYTES);
206};
207
208/// What one decoded frame may cost.
209///
210/// Carried by every session that decodes frames and handed to the
211/// conversion that copies them. See the [module docs](self) for why the
212/// seats are finite and how [`Self::max_pixels`] reaches libavcodec as
213/// well as this crate.
214#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
215pub struct FrameLimits {
216 max_pixels: u64,
217 max_frame_bytes: usize,
218 max_image_side_data_bytes: usize,
219}
220
221impl Default for FrameLimits {
222 #[inline]
223 fn default() -> Self {
224 Self::new()
225 }
226}
227
228impl FrameLimits {
229 /// The defaults: [`DEFAULT_MAX_PIXELS`] and
230 /// [`DEFAULT_MAX_FRAME_BYTES`].
231 #[cfg_attr(not(tarpaulin), inline(always))]
232 pub const fn new() -> Self {
233 Self {
234 max_pixels: DEFAULT_MAX_PIXELS,
235 max_frame_bytes: DEFAULT_MAX_FRAME_BYTES,
236 max_image_side_data_bytes: DEFAULT_MAX_IMAGE_SIDE_DATA_BYTES,
237 }
238 }
239
240 /// Most pixels one decoded frame may have.
241 ///
242 /// Also written to `AVCodecContext.max_pixels` when a decoder is
243 /// opened from these limits, so libavcodec refuses an oversized
244 /// picture before allocating it.
245 #[cfg_attr(not(tarpaulin), inline(always))]
246 pub const fn max_pixels(&self) -> u64 {
247 self.max_pixels
248 }
249 /// Most bytes one decoded frame's planes may export, together.
250 #[cfg_attr(not(tarpaulin), inline(always))]
251 pub const fn max_frame_bytes(&self) -> usize {
252 self.max_frame_bytes
253 }
254 /// The ceiling on side data one decoded **still** may carry.
255 #[cfg_attr(not(tarpaulin), inline(always))]
256 pub const fn max_image_side_data_bytes(&self) -> usize {
257 self.max_image_side_data_bytes
258 }
259
260 /// Sets the pixel ceiling (consuming builder).
261 #[cfg_attr(not(tarpaulin), inline(always))]
262 #[must_use]
263 pub const fn with_max_pixels(mut self, value: u64) -> Self {
264 self.max_pixels = value;
265 self
266 }
267 /// Sets the per-frame byte ceiling (consuming builder).
268 #[cfg_attr(not(tarpaulin), inline(always))]
269 #[must_use]
270 pub const fn with_max_frame_bytes(mut self, value: usize) -> Self {
271 self.max_frame_bytes = value;
272 self
273 }
274 /// Sets the decoded-still side-data ceiling (consuming builder).
275 #[cfg_attr(not(tarpaulin), inline(always))]
276 #[must_use]
277 pub const fn with_max_image_side_data_bytes(mut self, value: usize) -> Self {
278 self.max_image_side_data_bytes = value;
279 self
280 }
281
282 /// Sets the pixel ceiling in place.
283 #[cfg_attr(not(tarpaulin), inline(always))]
284 pub const fn set_max_pixels(&mut self, value: u64) -> &mut Self {
285 self.max_pixels = value;
286 self
287 }
288 /// Sets the per-frame byte ceiling in place.
289 #[cfg_attr(not(tarpaulin), inline(always))]
290 pub const fn set_max_frame_bytes(&mut self, value: usize) -> &mut Self {
291 self.max_frame_bytes = value;
292 self
293 }
294 /// Sets the decoded-still side-data ceiling in place.
295 #[cfg_attr(not(tarpaulin), inline(always))]
296 pub const fn set_max_image_side_data_bytes(&mut self, value: usize) -> &mut Self {
297 self.max_image_side_data_bytes = value;
298 self
299 }
300}
301
302/// Default ceiling on the bytes libavformat may **read** while probing
303/// and analysing a container — 5 MiB, which is FFmpeg's own
304/// `probesize` default.
305///
306/// **What this seat is for, and what it is not.** Every other budget in
307/// this crate bounds a copy *this crate* makes. This one bounds work
308/// **libavformat does before this crate is handed anything**:
309/// `avformat_open_input` and `avformat_find_stream_info` build the
310/// attached-picture, extradata and coded-side-data buffers themselves,
311/// so the attachment budgets — which measure this crate's copies —
312/// arrive after the original allocation has already happened.
313///
314/// A parser cannot allocate from bytes it was never given, so bounding
315/// the read is the instrument that reaches furthest back. See
316/// [`DemuxLimits::max_probe_bytes`] for how far it actually reaches and
317/// what it does not.
318pub const DEFAULT_MAX_PROBE_BYTES: u64 = 5 * 1024 * 1024;
319
320/// Default ceiling on the number of streams a container may declare —
321/// FFmpeg's own `max_streams` default.
322///
323/// Each declared stream costs an `AVStream` and its `AVCodecParameters`
324/// inside libavformat, before this crate sees a track table, so a
325/// header claiming a hundred thousand streams is an allocation this
326/// crate's per-track budgets are downstream of.
327pub const DEFAULT_MAX_STREAMS: u32 = 1000;
328
329/// Default ceiling on the side data one decoded **still** may carry —
330/// the same 16 MiB as [`DEFAULT_MAX_CODEC_PARAMETER_BYTES`], and the
331/// same reason.
332///
333/// **Why the still road needs its own number.** The shared stream
334/// collector caps frame side data at 256 KiB in total and *silently
335/// drops* whatever does not fit. On a video stream that is defensible:
336/// side data there is small, per-frame, and repeated. On a still it is
337/// wrong twice over. A decoded image's side data is dominated by the
338/// one thing that is legitimately megabytes — an **ICC profile** — and
339/// the parameter budget next door already admits those up to 16 MiB, so
340/// the same profile was admitted as a track parameter and swallowed as
341/// a frame annotation. Worse, the drop is positional: entries after the
342/// cap are skipped, and `AV_FRAME_DATA_DISPLAYMATRIX` — the orientation
343/// this crate reads off a still — is a small entry that a large ICC
344/// profile ahead of it pushed out. A picture came back silently rotated
345/// wrong.
346///
347/// So the still road gets a seat sized to what it actually carries, and
348/// over-budget is a **named refusal** rather than a quiet truncation:
349/// side data that cannot be carried whole is a fact about the picture,
350/// not a detail to drop.
351pub const DEFAULT_MAX_IMAGE_SIDE_DATA_BYTES: usize = DEFAULT_MAX_CODEC_PARAMETER_BYTES;
352
353/// Default ceiling on the compressed bytes one **image** decode may be
354/// handed — 64 MiB, the attachment family.
355///
356/// **Why the attachment family and not the packet one.** What
357/// [`crate::FfmpegImageDecoder`] decodes *is* an attachment: a whole
358/// file a container handed over eagerly. When it arrives through the
359/// demuxer it has already been charged against
360/// [`DEFAULT_MAX_ATTACHMENT_BYTES`], and this seat is what keeps the
361/// same ceiling in force when a caller builds the packet itself — the
362/// one road that skips the demux tier entirely. A 1 GiB packet ceiling
363/// here would mean the direct road was a gigabyte more permissive than
364/// the demuxed one for the same bytes.
365pub const DEFAULT_MAX_IMAGE_INPUT_BYTES: usize = DEFAULT_MAX_ATTACHMENT_BYTES;
366
367/// What one packet's payload may cost.
368///
369/// Carried by the boundary conversions and by an open demux session.
370#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
371pub struct PacketLimits {
372 max_packet_bytes: usize,
373}
374
375impl Default for PacketLimits {
376 #[inline]
377 fn default() -> Self {
378 Self::new()
379 }
380}
381
382impl PacketLimits {
383 /// The default: [`DEFAULT_MAX_PACKET_BYTES`].
384 #[cfg_attr(not(tarpaulin), inline(always))]
385 pub const fn new() -> Self {
386 Self {
387 max_packet_bytes: DEFAULT_MAX_PACKET_BYTES,
388 }
389 }
390
391 /// Most bytes one packet's payload may carry.
392 #[cfg_attr(not(tarpaulin), inline(always))]
393 pub const fn max_packet_bytes(&self) -> usize {
394 self.max_packet_bytes
395 }
396
397 /// Sets the per-packet ceiling (consuming builder).
398 #[cfg_attr(not(tarpaulin), inline(always))]
399 #[must_use]
400 pub const fn with_max_packet_bytes(mut self, value: usize) -> Self {
401 self.max_packet_bytes = value;
402 self
403 }
404 /// Sets the per-packet ceiling in place.
405 #[cfg_attr(not(tarpaulin), inline(always))]
406 pub const fn set_max_packet_bytes(&mut self, value: usize) -> &mut Self {
407 self.max_packet_bytes = value;
408 self
409 }
410}
411
412/// What opening and running one **decoder** may spend.
413///
414/// Composes [`FrameLimits`] — what the frames it produces may cost —
415/// with the two things a decoder spends before it has produced
416/// anything: copying the caller's codec parameters into an
417/// `AVCodecContext`, and copying the caller's compressed bytes into an
418/// `AVPacket`.
419///
420/// Taken at `open` by every decoder session in this crate, for the
421/// reason [`FrameLimits`] gives: half of it is written into an
422/// `AVCodecContext` whose ceilings cannot move after `avcodec_open2`.
423#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
424pub struct DecoderLimits {
425 frame: FrameLimits,
426 max_codec_parameter_bytes: usize,
427 max_packet_bytes: usize,
428 max_image_input_bytes: usize,
429}
430
431impl Default for DecoderLimits {
432 #[inline]
433 fn default() -> Self {
434 Self::new()
435 }
436}
437
438impl DecoderLimits {
439 /// The defaults: [`FrameLimits::new`],
440 /// [`DEFAULT_MAX_CODEC_PARAMETER_BYTES`], [`DEFAULT_MAX_PACKET_BYTES`]
441 /// and [`DEFAULT_MAX_IMAGE_INPUT_BYTES`].
442 #[cfg_attr(not(tarpaulin), inline(always))]
443 pub const fn new() -> Self {
444 Self {
445 frame: FrameLimits::new(),
446 max_codec_parameter_bytes: DEFAULT_MAX_CODEC_PARAMETER_BYTES,
447 max_packet_bytes: DEFAULT_MAX_PACKET_BYTES,
448 max_image_input_bytes: DEFAULT_MAX_IMAGE_INPUT_BYTES,
449 }
450 }
451
452 /// What one decoded frame may cost.
453 #[cfg_attr(not(tarpaulin), inline(always))]
454 pub const fn frame(&self) -> FrameLimits {
455 self.frame
456 }
457 /// Most heap bytes the codec parameters this decoder is opened from
458 /// may hold.
459 ///
460 /// Enforced at the choke point every road into libavcodec passes
461 /// through, so a decoder cannot be opened over parameters nobody
462 /// measured.
463 #[cfg_attr(not(tarpaulin), inline(always))]
464 pub const fn max_codec_parameter_bytes(&self) -> usize {
465 self.max_codec_parameter_bytes
466 }
467 /// Most compressed bytes one packet handed to a **stream** decoder
468 /// may carry.
469 #[cfg_attr(not(tarpaulin), inline(always))]
470 pub const fn max_packet_bytes(&self) -> usize {
471 self.max_packet_bytes
472 }
473
474 /// [`Self::max_packet_bytes`] as the [`PacketLimits`] the boundary
475 /// conversions take, so the send leg and the receive leg are handed
476 /// the same seat rather than two numbers that could drift.
477 #[cfg_attr(not(tarpaulin), inline(always))]
478 pub const fn packet_limits(&self) -> PacketLimits {
479 PacketLimits::new().with_max_packet_bytes(self.max_packet_bytes)
480 }
481 /// Most compressed bytes one **image** decode may be handed. See
482 /// [`DEFAULT_MAX_IMAGE_INPUT_BYTES`] for why this is its own seat.
483 #[cfg_attr(not(tarpaulin), inline(always))]
484 pub const fn max_image_input_bytes(&self) -> usize {
485 self.max_image_input_bytes
486 }
487
488 /// Sets the frame ceilings (consuming builder).
489 #[cfg_attr(not(tarpaulin), inline(always))]
490 #[must_use]
491 pub const fn with_frame(mut self, value: FrameLimits) -> Self {
492 self.frame = value;
493 self
494 }
495 /// Sets the codec-parameter ceiling (consuming builder).
496 #[cfg_attr(not(tarpaulin), inline(always))]
497 #[must_use]
498 pub const fn with_max_codec_parameter_bytes(mut self, value: usize) -> Self {
499 self.max_codec_parameter_bytes = value;
500 self
501 }
502 /// Sets the per-packet ceiling (consuming builder).
503 #[cfg_attr(not(tarpaulin), inline(always))]
504 #[must_use]
505 pub const fn with_max_packet_bytes(mut self, value: usize) -> Self {
506 self.max_packet_bytes = value;
507 self
508 }
509 /// Sets the image-input ceiling (consuming builder).
510 #[cfg_attr(not(tarpaulin), inline(always))]
511 #[must_use]
512 pub const fn with_max_image_input_bytes(mut self, value: usize) -> Self {
513 self.max_image_input_bytes = value;
514 self
515 }
516
517 /// Sets the frame ceilings in place.
518 #[cfg_attr(not(tarpaulin), inline(always))]
519 pub const fn set_frame(&mut self, value: FrameLimits) -> &mut Self {
520 self.frame = value;
521 self
522 }
523 /// Sets the codec-parameter ceiling in place.
524 #[cfg_attr(not(tarpaulin), inline(always))]
525 pub const fn set_max_codec_parameter_bytes(&mut self, value: usize) -> &mut Self {
526 self.max_codec_parameter_bytes = value;
527 self
528 }
529 /// Sets the per-packet ceiling in place.
530 #[cfg_attr(not(tarpaulin), inline(always))]
531 pub const fn set_max_packet_bytes(&mut self, value: usize) -> &mut Self {
532 self.max_packet_bytes = value;
533 self
534 }
535 /// Sets the image-input ceiling in place.
536 #[cfg_attr(not(tarpaulin), inline(always))]
537 pub const fn set_max_image_input_bytes(&mut self, value: usize) -> &mut Self {
538 self.max_image_input_bytes = value;
539 self
540 }
541}
542
543/// What one demux session may spend: on any single packet, on any
544/// single attachment, and on every attachment in the file together.
545///
546/// Handed to [`FfmpegDemuxer::open_with`](crate::FfmpegDemuxer::open_with)
547/// rather than set afterwards, because the attachment budget is spent
548/// *during* the open — every attachment payload is captured before the
549/// first timed packet is read, which is what makes the demux tier's
550/// delivery contract true by construction.
551#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
552pub struct DemuxLimits {
553 packet: PacketLimits,
554 max_attachment_bytes: usize,
555 max_total_attachment_bytes: usize,
556 max_codec_parameter_bytes: usize,
557 max_total_codec_parameter_bytes: usize,
558 max_probe_bytes: u64,
559 max_streams: u32,
560}
561
562impl Default for DemuxLimits {
563 #[inline]
564 fn default() -> Self {
565 Self::new()
566 }
567}
568
569impl DemuxLimits {
570 /// The defaults: [`PacketLimits::new`],
571 /// [`DEFAULT_MAX_ATTACHMENT_BYTES`] and
572 /// [`DEFAULT_MAX_TOTAL_ATTACHMENT_BYTES`].
573 #[cfg_attr(not(tarpaulin), inline(always))]
574 pub const fn new() -> Self {
575 Self {
576 packet: PacketLimits::new(),
577 max_attachment_bytes: DEFAULT_MAX_ATTACHMENT_BYTES,
578 max_total_attachment_bytes: DEFAULT_MAX_TOTAL_ATTACHMENT_BYTES,
579 max_codec_parameter_bytes: DEFAULT_MAX_CODEC_PARAMETER_BYTES,
580 max_total_codec_parameter_bytes: DEFAULT_MAX_TOTAL_CODEC_PARAMETER_BYTES,
581 max_probe_bytes: DEFAULT_MAX_PROBE_BYTES,
582 max_streams: DEFAULT_MAX_STREAMS,
583 }
584 }
585
586 /// The ceiling on bytes libavformat may read while probing and
587 /// analysing a container.
588 ///
589 /// # What this bounds, and what it does not
590 ///
591 /// **Bounded:** the total bytes libavformat is handed during
592 /// `avformat_open_input` and `avformat_find_stream_info`. It reaches
593 /// two ways — as `probesize` and `formatprobesize`, which every
594 /// entrypoint sets before the open, and, on the reader entrypoint, as
595 /// a hard byte meter on the `AVIOContext` itself: past the budget the
596 /// reader answers an I/O error, so the parser gets nothing more
597 /// whatever it asks for.
598 ///
599 /// **Not bounded:** allocation *amplification* inside a parser. A
600 /// container can describe, in a handful of bytes, a structure whose
601 /// in-memory form is much larger, and nothing outside libavformat can
602 /// see that happen. What this seat guarantees is that the input to
603 /// that amplification is finite and small; bounding its output is the
604 /// substrate's own hardening territory, and FFmpeg has its own
605 /// `max_streams` / `max_index_size` / `max_picture_buffer` seats for
606 /// exactly that — [`Self::max_streams`] sets the first of them.
607 ///
608 /// **Not bounded on the path entrypoint:** the byte meter needs an
609 /// `AVIOContext` this crate owns, and a path is opened by
610 /// libavformat's own protocol layer. `probesize` and
611 /// `formatprobesize` still apply there; the hard meter does not.
612 /// A caller who wants the meter on a file can open it as a reader.
613 #[cfg_attr(not(tarpaulin), inline(always))]
614 pub const fn max_probe_bytes(&self) -> u64 {
615 self.max_probe_bytes
616 }
617 /// The ceiling on streams a container may declare. See
618 /// [`Self::max_probe_bytes`] for why a seat inside libavformat is
619 /// worth setting at all.
620 #[cfg_attr(not(tarpaulin), inline(always))]
621 pub const fn max_streams(&self) -> u32 {
622 self.max_streams
623 }
624 /// Sets the probe-read ceiling (consuming builder).
625 #[cfg_attr(not(tarpaulin), inline(always))]
626 #[must_use]
627 pub const fn with_max_probe_bytes(mut self, value: u64) -> Self {
628 self.max_probe_bytes = value;
629 self
630 }
631 /// Sets the declared-stream ceiling (consuming builder).
632 #[cfg_attr(not(tarpaulin), inline(always))]
633 #[must_use]
634 pub const fn with_max_streams(mut self, value: u32) -> Self {
635 self.max_streams = value;
636 self
637 }
638
639 /// The per-packet budget timed packets are checked against.
640 #[cfg_attr(not(tarpaulin), inline(always))]
641 pub const fn packet(&self) -> PacketLimits {
642 self.packet
643 }
644 /// Most bytes one attachment may carry.
645 #[cfg_attr(not(tarpaulin), inline(always))]
646 pub const fn max_attachment_bytes(&self) -> usize {
647 self.max_attachment_bytes
648 }
649 /// Most bytes every attachment in the file may carry together.
650 #[cfg_attr(not(tarpaulin), inline(always))]
651 pub const fn max_total_attachment_bytes(&self) -> usize {
652 self.max_total_attachment_bytes
653 }
654 /// Most heap bytes one stream's codec parameters may hold —
655 /// `extradata`, `coded_side_data` and a custom channel map together.
656 #[cfg_attr(not(tarpaulin), inline(always))]
657 pub const fn max_codec_parameter_bytes(&self) -> usize {
658 self.max_codec_parameter_bytes
659 }
660 /// Most heap bytes every stream's codec parameters may hold together.
661 #[cfg_attr(not(tarpaulin), inline(always))]
662 pub const fn max_total_codec_parameter_bytes(&self) -> usize {
663 self.max_total_codec_parameter_bytes
664 }
665
666 /// Sets the per-packet budget (consuming builder).
667 #[cfg_attr(not(tarpaulin), inline(always))]
668 #[must_use]
669 pub const fn with_packet(mut self, value: PacketLimits) -> Self {
670 self.packet = value;
671 self
672 }
673 /// Sets the per-attachment ceiling (consuming builder).
674 #[cfg_attr(not(tarpaulin), inline(always))]
675 #[must_use]
676 pub const fn with_max_attachment_bytes(mut self, value: usize) -> Self {
677 self.max_attachment_bytes = value;
678 self
679 }
680 /// Sets the whole-file attachment budget (consuming builder).
681 #[cfg_attr(not(tarpaulin), inline(always))]
682 #[must_use]
683 pub const fn with_max_total_attachment_bytes(mut self, value: usize) -> Self {
684 self.max_total_attachment_bytes = value;
685 self
686 }
687 /// Sets the per-stream codec-parameter ceiling (consuming builder).
688 #[cfg_attr(not(tarpaulin), inline(always))]
689 #[must_use]
690 pub const fn with_max_codec_parameter_bytes(mut self, value: usize) -> Self {
691 self.max_codec_parameter_bytes = value;
692 self
693 }
694 /// Sets the whole-file codec-parameter budget (consuming builder).
695 #[cfg_attr(not(tarpaulin), inline(always))]
696 #[must_use]
697 pub const fn with_max_total_codec_parameter_bytes(mut self, value: usize) -> Self {
698 self.max_total_codec_parameter_bytes = value;
699 self
700 }
701
702 /// Sets the per-packet budget in place.
703 #[cfg_attr(not(tarpaulin), inline(always))]
704 pub const fn set_packet(&mut self, value: PacketLimits) -> &mut Self {
705 self.packet = value;
706 self
707 }
708 /// Sets the per-attachment ceiling in place.
709 #[cfg_attr(not(tarpaulin), inline(always))]
710 pub const fn set_max_attachment_bytes(&mut self, value: usize) -> &mut Self {
711 self.max_attachment_bytes = value;
712 self
713 }
714 /// Sets the whole-file attachment budget in place.
715 #[cfg_attr(not(tarpaulin), inline(always))]
716 pub const fn set_max_total_attachment_bytes(&mut self, value: usize) -> &mut Self {
717 self.max_total_attachment_bytes = value;
718 self
719 }
720 /// Sets the per-stream codec-parameter ceiling in place.
721 #[cfg_attr(not(tarpaulin), inline(always))]
722 pub const fn set_max_codec_parameter_bytes(&mut self, value: usize) -> &mut Self {
723 self.max_codec_parameter_bytes = value;
724 self
725 }
726 /// Sets the whole-file codec-parameter budget in place.
727 #[cfg_attr(not(tarpaulin), inline(always))]
728 pub const fn set_max_total_codec_parameter_bytes(&mut self, value: usize) -> &mut Self {
729 self.max_total_codec_parameter_bytes = value;
730 self
731 }
732}
733
734#[cfg(test)]
735mod tests;