mediadecode_ffmpeg/convert/mod.rs
1//! Conversion helpers from FFmpeg `AVFrame` / `AVPacket` to the
2//! `mediadecode` types parameterized by [`crate::Ffmpeg`] and
3//! `FfmpegBytes`.
4//!
5//! Every plane is **copied once**, here, out of FFmpeg's
6//! `AVBufferRef` and into Rust-owned memory — the
7//! [D-seat amputation contract][law]. Through 0.8 the video path
8//! exported a refcounted *view* into libavcodec's own allocation
9//! whenever the stride happened to be tight, and copied only when it
10//! was padded; a consumer therefore inherited an FFmpeg lifetime it
11//! could not see, on some frames and not others. 0.9 copies both
12//! branches. What is unchanged is the *shape* each branch produces —
13//! a tight plane keeps the decoder's `linesize` as its stride, a
14//! padded one is compacted to `row_bytes` — because that geometry is
15//! what consumers read, and the amputation is about ownership, not
16//! about relaying out the picture.
17//!
18//! # Header fields: the validation-order census
19//!
20//! Every number in this module comes out of an `AVFrame` a file chose
21//! the contents of, and each one is answerable to two questions —
22//! *what judges it*, and *what reads it first*. When the second
23//! precedes the first, the judgement is being made against a value its
24//! own consumer has already laundered, which is not a judgement. That
25//! is not hypothetical: it is how a declared `-1` channel count reached
26//! a ceiling as a legitimate-looking `0`, having been floored by the
27//! very helper the ceiling was supposed to run before.
28//!
29//! So the order is censused rather than assumed. Every raw header field
30//! these three paths read, with its validator and its first consumer:
31//!
32//! | path | field | validator | first consumer | order |
33//! |---|---|---|---|---|
34//! | audio | `nb_samples` | `< 0` → [`InvalidSampleCount`] | the byte product | validator first |
35//! | audio | `ch_layout.nb_channels` | `< 0`, `> 255`, `== 0` with samples → [`UnsupportedChannelCount`] | `channel_layout_description_from_raw_ptr` | **was inverted — hoisted** |
36//! | audio | `format` | `bytes_per_sample()` → [`UnsupportedSampleFormat`] | `is_planar()`, for the plane count | validator first |
37//! | audio | `linesize[0]` | `< 0`, and `== 0` with samples → [`InvalidPlaneLayout`] | `allocated_per_plane` | validator first |
38//! | audio | `sample_rate` | none — censused metadata | `AudioFrame::new` | no geometry rides it |
39//! | audio | `data[i]` | null check, then the backing-buffer proof | the copy | validator first |
40//! | picture | `width` / `height` | `< 0` → [`InvalidDimensions`] | `copy_out_planes`' pixel ceiling | **was inverted — hoisted** |
41//! | picture | `format` | `is_deliverable` → unsupported-format | `plane_geometry` | validator first |
42//! | picture | `linesize[i]` | `<= 0` **and** `< row_bytes[i]` → [`InvalidPlaneLayout`] | its own pass, after the budget and before any copy | validator first |
43//! | picture | `crop_*` | `checked_add` per pair, then `sum < extent` | the rect | validator first |
44//! | picture | `nb_side_data`, entry `size` (still road) | the entry cap and [`FrameLimits::max_image_side_data_bytes`](crate::FrameLimits::max_image_side_data_bytes) | the plane copy, then the side-data copy | **was inverted — hoisted ahead of `copy_out_planes`** |
45//! | picture | colour enums, `pict_type` | the raw `i32` fold, which is total | the fold's own output | the fold *is* the validator |
46//! | packet | `flags` (`AV_PKT_FLAG_TRUSTED`) | [`crate::buffer::TrustedPayload`], both legs | the payload copy | validator first |
47//!
48//! # The open-C-enum sweep, including this crate's own code
49//!
50//! The same discipline, applied to *entry points* rather than fields: a
51//! value read out of FFmpeg memory as a closed Rust enum is undefined
52//! behaviour before any comparison on it can run, and FFmpeg extends
53//! these enums in ABI-compatible releases.
54//!
55//! | caller | entry point | enum | closed by |
56//! |---|---|---|---|
57//! | image / video / audio / subtitle open | `Decoder::{video,audio,subtitle}()` | `AVCodecID`, `AVMediaType` | `find_decoder` (raw `u32`) + `ensure_codec_type` (raw `i32`) |
58//! | track build, attachment classify, resampler spec, `Debug` | `Parameters::medium()` | `AVMediaType` | `boundary::media_kind_of`, a total fold |
59//! | **the pixel-format census** | `av_pix_fmt_desc_get_id` | `AVPixelFormat` | local `c_int` shim |
60//! | **the pixel-format census** | `av_image_get_buffer_size` | `AVPixelFormat` | local `c_int` shim |
61//! | **the sample-format census** | `av_get_bytes_per_sample` | `AVSampleFormat` | local `c_int` shim |
62//! | HW format negotiation | `get_format` callback list | `AVPixelFormat` | walked as `*const i32` |
63//!
64//! # The dimension-vocabulary sweep
65//!
66//! A frame has more than one extent, and a judge that reads the wrong
67//! one is not a judge. `AVFrame.width`/`.height` are the **display**
68//! dims; what gets *allocated* is the **coded** extent on the software
69//! road and the **frames-context pool** on the hardware one. On a
70//! cropped stream they diverge without limit — measured on this build,
71//! an h264 clip carrying SPS cropping shows 32x32 display over a
72//! 1920x1088 coded surface, a 2040x gap.
73//!
74//! Every site that reads a dimension, and which vocabulary it needs:
75//!
76//! | site | reads | sizes what | verdict |
77//! |---|---|---|---|
78//! | `judge_buffer` | `AVFrame.width/height` at `get_buffer2` | the software allocation's **cost** | **correct**: measured, libavcodec hands this hook the frame at *coded* extent (1920x1088, aligned 1920x1090, 2,092,831 bytes), and the footprint prices those aligned dims against `max_frame_bytes`. Logical extent is not this seat's question — `max_pixels` is enforced by `ff_set_dimensions` against the **raw** dims, which is the semantics it has |
79//! | `get_hw_format` | `AVCodecContext.coded_width/height` | the hardware pool | **correct, and new**: the display dims `max_pixels` was checked against are blind to it |
80//! | `judge_hw_transfer` | the frames-context pool dims | the transfer's CPU destination | **was display — repriced** |
81//! | `estimate_transfer_bytes` | the frames-context pool dims | the probe's pending budget | correct already, and its doc named this trap first |
82//! | `drain_into_pending` (two sites) | `AVFrame.width/height` | **nothing** — log fields only | benign |
83//! | `VideoDecoder::width/height` | the decoder's display dims | nothing; a public accessor | correct — display is what a caller is asking for |
84//! | `copy_out_planes` | the converted frame's own extent | the plane copy | correct — a decoded CPU frame's extent *is* its allocation |
85//!
86//! The pattern worth keeping: **the extent to judge is the one the
87//! allocator will use, and it is never assumed — it is read from
88//! whatever structure the allocation is sized from.** Where that
89//! structure cannot be read, the judge fails closed, because an
90//! unprovable extent is not a small one.
91//!
92//! And the capstone the whole series arrives at, which generalises both
93//! tables above:
94//!
95//! > **A judge must dominate the allocator's arithmetic, not the
96//! > payload's.**
97//!
98//! Every ceiling here answers "may this be allocated?", so the number
99//! it compares has to be what the *allocator* will take — not what the
100//! bytes nominally weigh, not what a tight layout would cost, and not
101//! what the header displays. The two differ by under one percent on
102//! ordinary frames, which is precisely why every under-pricing defect
103//! in this release hid behind a shape big enough for the slack not to
104//! show: `nv12` 16x16 is 384 bytes of pixels and a 1,792-byte
105//! allocation, a one-sample eight-channel planar frame is 16 bytes of
106//! samples and 768 allocated, and `yuv420p` 1920x1080 is 3,110,400
107//! against 3,133,696. See [`crate::footprint`], where the pricing lives
108//! and where the estimates are verified against real allocations rather
109//! than argued.
110//!
111//! The last three rows of the enum table above are the class **inside
112//! this crate's own new code**, and the census rows are its sharpest instance: that code
113//! exists precisely to price formats this build's bindings may not
114//! name, and the binding it called handed those ids back as a closed
115//! `AVPixelFormat`. Every future format would have become an invalid
116//! enum value on the way into the pricing meant to handle it — the
117//! census would have been undefined behaviour on exactly its reason for
118//! existing. Writing the discipline down was not enough; it had to be
119//! re-applied to the code that enforces it.
120//!
121//! The still road's side-data judgement is the same lesson one level
122//! up, about passes rather than fields: it was correct, and it ran
123//! after `copy_out_planes`, so an over-budget still had already bought
124//! up to `max_frame_bytes` of plane copies before its annotations were
125//! totalled. It reads only header fields and allocates nothing, so it
126//! now runs with the other free judgements. **Everything a conversion
127//! can refuse is refused before anything it can allocate is
128//! allocated.**
129//!
130//! The picture road's byte ceiling is now judged from the **geometry
131//! alone** — the format's row width times its row count, which no
132//! number the frame chose can influence — so it runs before any stride
133//! is so much as read. Then every stride is judged, in its own pass,
134//! before a single plane is bought: a layout fault is a property of the
135//! frame, knowable before any of it is paid for, and discovering it
136//! three plane allocations in was how a refused frame still cost three
137//! allocations.
138//!
139//! The colour row is the shape to copy: a fold that cannot fail and
140//! maps everything unknown onto a named "not stated" leaves nothing for
141//! an order to get wrong.
142//!
143//! [law]: mediadecode::adapter#the-d-seat-amputation-contract
144use core::ptr::{addr_of, read_unaligned};
145
146use derive_more::{IsVariant, TryUnwrap, Unwrap};
147use ffmpeg_next::ffi::{
148 AV_NOPTS_VALUE, AVChromaLocation, AVColorPrimaries, AVColorRange, AVColorSpace,
149 AVColorTransferCharacteristic, AVFrame, AVFrameSideDataType, AVPictureType, AVSubtitleType,
150};
151use mediadecode::{
152 PixelFormat, Timebase, Timestamp,
153 color::{ChromaLocation, ColorInfo, ColorMatrix, ColorPrimaries, ColorRange, ColorTransfer},
154 frame::{AudioFrame, Dimensions, ImageFrame, Plane, Rect, SubtitleFrame, VideoFrame},
155 subtitle::{Bitmap as SubtitleBitmap, SubtitlePayload, Text as SubtitleText},
156};
157use mediaframe::audio::ChannelLayoutDescription;
158use smol_str::SmolStr;
159
160use crate::{
161 boundary,
162 buffer::FfmpegBytes,
163 extras::{
164 AudioFrameExtra, ContentLightLevel, ImageFrameExtra, ImageOrientation, MasteringDisplay,
165 PictureType, SideDataEntry, SubtitleFrameExtra, VideoFrameExtra,
166 },
167 limits::FrameLimits,
168 pixdesc,
169 sample_format::SampleFormat,
170};
171
172/// Payload for [`ConvertError::UnsupportedPixelFormat`].
173///
174/// The frame's pixel format isn't in the closed CPU-format set this
175/// crate supports for safe per-plane access.
176#[derive(Debug, Clone)]
177pub struct UnsupportedPixelFormat {
178 format: PixelFormat,
179 raw: i32,
180 name: Option<SmolStr>,
181}
182
183impl UnsupportedPixelFormat {
184 /// Constructs an `UnsupportedPixelFormat` payload.
185 #[inline]
186 pub const fn new(format: PixelFormat, raw: i32, name: Option<SmolStr>) -> Self {
187 Self { format, raw, name }
188 }
189
190 /// The unified vocabulary's answer for [`Self::raw`].
191 ///
192 /// [`PixelFormat::None`] whenever the raw integer has no mapping — a
193 /// hardware surface, a Bayer mosaic, a format FFmpeg gained after
194 /// this build. That is a *value*, not a failed lookup, and it is
195 /// deliberately not made to carry the integer: [`Self::raw`] and
196 /// [`Self::name`] are where the identity survives.
197 #[inline]
198 pub const fn format(&self) -> &PixelFormat {
199 &self.format
200 }
201 /// The raw `AVFrame.format` integer, exactly as FFmpeg wrote it.
202 ///
203 /// Present at every tier — it costs one `i32` — because it is the
204 /// only field that is always available and always precise. Without
205 /// it the message for the fall-through case says `None` and names
206 /// nothing at all.
207 #[inline]
208 pub const fn raw(&self) -> i32 {
209 self.raw
210 }
211 /// FFmpeg's own name for [`Self::raw`] (`av_get_pix_fmt_name`), when
212 /// libavutil has one.
213 ///
214 /// `None` for an integer libavutil does not describe — a corrupt
215 /// read, or a format from a newer library than the one linked.
216 #[inline]
217 pub fn name(&self) -> Option<&str> {
218 self.name.as_deref()
219 }
220}
221
222impl core::fmt::Display for UnsupportedPixelFormat {
223 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
224 match &self.name {
225 Some(name) => write!(
226 f,
227 "convert: unsupported pixel format {:?} (AVPixelFormat {} = {name:?})",
228 self.format, self.raw
229 ),
230 None => write!(
231 f,
232 "convert: unsupported pixel format {:?} (AVPixelFormat {}, unnamed by libavutil)",
233 self.format, self.raw
234 ),
235 }
236 }
237}
238
239/// Payload for [`ConvertError::InvalidPlaneLayout`].
240///
241/// A plane reported `linesize <= 0` or otherwise inconsistent layout.
242#[derive(Debug, Clone, Copy)]
243pub struct InvalidPlaneLayout {
244 plane: usize,
245}
246
247impl InvalidPlaneLayout {
248 /// Constructs an `InvalidPlaneLayout` payload.
249 #[inline]
250 pub const fn new(plane: usize) -> Self {
251 Self { plane }
252 }
253 /// Plane index.
254 #[inline]
255 pub const fn plane(&self) -> usize {
256 self.plane
257 }
258}
259
260impl core::fmt::Display for InvalidPlaneLayout {
261 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
262 write!(f, "convert: invalid layout on plane {}", self.plane)
263 }
264}
265
266/// Payload for [`ConvertError::BufferAcquireFailed`].
267///
268/// A plane's `data[i]` does not lie inside any of the frame's own
269/// `buf[]` allocations, so its extent cannot be proved and nothing may
270/// be read from it.
271///
272/// **A fact about the frame, not about the moment.** An exhausted
273/// allocator is [`CarrierAllocFailed`] — the two were one arm once, and
274/// telling them apart is what lets a decoder park a frame worth
275/// re-attempting without parking one that will never convert.
276#[derive(Debug, Clone, Copy)]
277pub struct BufferAcquireFailed {
278 plane: usize,
279}
280
281impl BufferAcquireFailed {
282 /// Constructs a `BufferAcquireFailed` payload.
283 #[inline]
284 pub const fn new(plane: usize) -> Self {
285 Self { plane }
286 }
287 /// Plane index whose buffer couldn't be acquired.
288 #[inline]
289 pub const fn plane(&self) -> usize {
290 self.plane
291 }
292}
293
294/// Payload for [`ConvertError::CarrierAllocFailed`].
295///
296/// The plane's extent was proved and the carrier still could not be
297/// made: a refcount the view lane could not take, a gather or copy the
298/// allocator refused.
299///
300/// **A fact about the moment, not about the frame.** The same frame may
301/// convert perfectly a moment later, which is why the decode roads park
302/// it and re-attempt rather than letting it go.
303#[derive(Debug, Clone, Copy)]
304pub struct CarrierAllocFailed {
305 plane: usize,
306}
307
308impl CarrierAllocFailed {
309 /// Constructs a `CarrierAllocFailed` payload.
310 #[inline]
311 #[must_use]
312 pub const fn new(plane: usize) -> Self {
313 Self { plane }
314 }
315
316 /// Plane index whose carrier could not be allocated.
317 #[inline]
318 #[must_use]
319 pub const fn plane(&self) -> usize {
320 self.plane
321 }
322}
323
324impl core::fmt::Display for CarrierAllocFailed {
325 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
326 write!(
327 f,
328 "convert: could not allocate a carrier for plane {}",
329 self.plane
330 )
331 }
332}
333
334impl std::error::Error for CarrierAllocFailed {}
335
336impl core::fmt::Display for BufferAcquireFailed {
337 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
338 write!(
339 f,
340 "convert: could not acquire buffer ref for plane {}",
341 self.plane
342 )
343 }
344}
345
346/// Payload for [`ConvertError::TooManyPixels`].
347///
348/// A frame declares more pixels than the session's
349/// [`FrameLimits::max_pixels`] allows.
350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
351pub struct TooManyPixels {
352 pixels: u64,
353 limit: u64,
354}
355
356impl TooManyPixels {
357 /// Constructs a `TooManyPixels` payload.
358 #[inline]
359 pub const fn new(pixels: u64, limit: u64) -> Self {
360 Self { pixels, limit }
361 }
362 /// The pixel count the frame declared.
363 #[inline]
364 pub const fn pixels(&self) -> u64 {
365 self.pixels
366 }
367 /// The ceiling in force.
368 #[inline]
369 pub const fn limit(&self) -> u64 {
370 self.limit
371 }
372}
373
374impl core::fmt::Display for TooManyPixels {
375 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
376 write!(
377 f,
378 "convert: a {}-pixel frame exceeds the {}-pixel ceiling",
379 self.pixels, self.limit
380 )
381 }
382}
383
384/// Payload for [`ConvertError::FrameTooLarge`].
385///
386/// A frame's planes would export more bytes than the session's
387/// [`FrameLimits::max_frame_bytes`] allows.
388#[derive(Debug, Clone, Copy, PartialEq, Eq)]
389pub struct FrameTooLarge {
390 bytes: usize,
391 limit: usize,
392}
393
394impl FrameTooLarge {
395 /// Constructs a `FrameTooLarge` payload.
396 #[inline]
397 pub const fn new(bytes: usize, limit: usize) -> Self {
398 Self { bytes, limit }
399 }
400 /// The bytes the frame's planes would have exported.
401 #[inline]
402 pub const fn bytes(&self) -> usize {
403 self.bytes
404 }
405 /// The ceiling in force.
406 #[inline]
407 pub const fn limit(&self) -> usize {
408 self.limit
409 }
410}
411
412impl core::fmt::Display for FrameTooLarge {
413 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
414 write!(
415 f,
416 "convert: a frame exporting {} bytes exceeds the {}-byte ceiling",
417 self.bytes, self.limit
418 )
419 }
420}
421
422/// Payload for [`ConvertError::InvalidSampleCount`].
423///
424/// An audio frame declares a negative `nb_samples`.
425///
426/// Refused rather than floored to zero. A negative count is not an
427/// empty frame — it is a header that cannot be read — and clamping it
428/// turned a malformed frame into a well-formed empty one that a
429/// consumer would have gone on decoding past.
430#[derive(Debug, Clone, Copy, PartialEq, Eq)]
431pub struct InvalidSampleCount {
432 count: i32,
433}
434
435impl InvalidSampleCount {
436 /// Constructs an `InvalidSampleCount` payload.
437 #[inline]
438 pub const fn new(count: i32) -> Self {
439 Self { count }
440 }
441 /// The count the frame declared.
442 #[inline]
443 pub const fn count(&self) -> i32 {
444 self.count
445 }
446}
447
448impl core::fmt::Display for InvalidSampleCount {
449 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
450 write!(f, "convert: {} is not a sample count", self.count)
451 }
452}
453
454/// Payload for [`ConvertError::UnsupportedSampleFormat`].
455///
456/// The frame's sample format has no byte width — `AV_SAMPLE_FMT_NONE`,
457/// or a format newer than this build names.
458///
459/// Checked **before** the zero-sample shortcut, because a frame with no
460/// readable format is malformed whether or not it carries samples.
461/// Letting an empty one through returned an `AudioFrame` advertising a
462/// format nothing can interpret.
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
464pub struct UnsupportedSampleFormat {
465 raw: i32,
466}
467
468impl UnsupportedSampleFormat {
469 /// Constructs an `UnsupportedSampleFormat` payload.
470 #[inline]
471 pub const fn new(raw: i32) -> Self {
472 Self { raw }
473 }
474 /// The raw `AVFrame.format` integer, exactly as FFmpeg wrote it.
475 #[inline]
476 pub const fn raw(&self) -> i32 {
477 self.raw
478 }
479}
480
481impl core::fmt::Display for UnsupportedSampleFormat {
482 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
483 write!(
484 f,
485 "convert: AVSampleFormat {} has no byte width this build can use",
486 self.raw
487 )
488 }
489}
490
491/// Payload for [`ConvertError::UnsupportedChannelCount`].
492///
493/// A channel count this crate will not carry: more than
494/// [`u8::MAX`], which the portable `AudioFrame` seat cannot hold, or
495/// none at all on a frame that claims samples.
496///
497/// **Refused, never clamped.** Clamping to 255 was silent truncation of
498/// exactly the kind this boundary exists to refuse: a 256-channel
499/// packed frame then computed its byte product from the clipped count
500/// and copied 510 of its 512 bytes, delivering a short buffer that
501/// advertised 255 channels. A short read is not a smaller frame; it is
502/// a wrong one.
503///
504/// The count is carried **signed**, as `AVChannelLayout.nb_channels`
505/// declares it. It has to be: a negative count is one of the things
506/// this arm refuses, and the first version of this refusal read the
507/// count off a materialised layout description that had already
508/// floored it to zero — so `nb_channels == -1` arrived looking like a
509/// legitimate zero-channel frame and was never seen by the guard meant
510/// to catch it.
511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
512pub struct UnsupportedChannelCount {
513 channels: i32,
514}
515
516impl UnsupportedChannelCount {
517 /// Constructs an `UnsupportedChannelCount` payload.
518 #[inline]
519 pub const fn new(channels: i32) -> Self {
520 Self { channels }
521 }
522 /// The count the frame's layout declared, exactly as it read.
523 #[inline]
524 pub const fn channels(&self) -> i32 {
525 self.channels
526 }
527}
528
529impl core::fmt::Display for UnsupportedChannelCount {
530 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
531 write!(
532 f,
533 "convert: {} channels cannot be carried (1..={} on a frame with samples)",
534 self.channels,
535 u8::MAX,
536 )
537 }
538}
539
540/// Payload for [`ConvertError::InvalidDimensions`].
541///
542/// A picture frame declaring a negative width or height.
543///
544/// The sibling of [`InvalidSampleCount`] on the picture road, and found
545/// by auditing for it: `width` and `height` were floored with `.max(0)`
546/// before anything judged them, so a declared `-1` became `0` and then
547/// sailed through the pixel ceiling (zero pixels is under every
548/// ceiling) to produce a real `VideoFrame` of zero extent. A refusal
549/// delivered as a successful decode, which is the one outcome worse
550/// than an error.
551///
552/// Zero itself is **not** refused here: it is what an unset dimension
553/// reads as, the ceilings and the plane geometry both handle it, and
554/// inventing a refusal for it would be policy this audit has no
555/// evidence for. Only the negative — which cannot be a dimension under
556/// any reading — is named.
557#[derive(Debug, Clone, Copy, PartialEq, Eq)]
558pub struct InvalidDimensions {
559 width: i32,
560 height: i32,
561}
562
563impl InvalidDimensions {
564 /// Constructs an `InvalidDimensions` payload.
565 #[inline]
566 pub const fn new(width: i32, height: i32) -> Self {
567 Self { width, height }
568 }
569 /// The width the frame declared, exactly as it read.
570 #[inline]
571 pub const fn width(&self) -> i32 {
572 self.width
573 }
574 /// The height the frame declared, exactly as it read.
575 #[inline]
576 pub const fn height(&self) -> i32 {
577 self.height
578 }
579}
580
581impl core::fmt::Display for InvalidDimensions {
582 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
583 write!(
584 f,
585 "convert: frame declares dimensions {}x{}, which are not a picture",
586 self.width, self.height,
587 )
588 }
589}
590
591/// Payload for [`ConvertError::ImageSideDataTooLarge`].
592///
593/// A decoded still whose side data exceeds
594/// [`FrameLimits::max_image_side_data_bytes`](crate::FrameLimits::max_image_side_data_bytes).
595///
596/// Refused rather than truncated. The shared stream collector drops
597/// what does not fit and logs it, which on a still is the wrong answer
598/// twice: an ICC profile is the entry most likely to be large and the
599/// one whose loss silently changes the colours, and the drop is
600/// positional, so a big profile pushes the display matrix off the end
601/// and the picture comes back rotated wrong with nothing to say so.
602#[derive(Debug, Clone, Copy, PartialEq, Eq)]
603pub struct ImageSideDataTooLarge {
604 bytes: usize,
605 limit: usize,
606}
607
608impl ImageSideDataTooLarge {
609 /// Constructs an `ImageSideDataTooLarge` payload.
610 #[inline]
611 pub const fn new(bytes: usize, limit: usize) -> Self {
612 Self { bytes, limit }
613 }
614 /// Bytes the still's side data reached.
615 #[inline]
616 pub const fn bytes(&self) -> usize {
617 self.bytes
618 }
619 /// The ceiling in force.
620 #[inline]
621 pub const fn limit(&self) -> usize {
622 self.limit
623 }
624}
625
626impl core::fmt::Display for ImageSideDataTooLarge {
627 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
628 write!(
629 f,
630 "convert: still side data reaches {} bytes over a ceiling of {}",
631 self.bytes, self.limit,
632 )
633 }
634}
635
636/// Payload for [`ConvertError::ImageSideDataEntries`].
637///
638/// A decoded still declaring more side-data entries than this crate
639/// will walk. The count sibling of [`ImageSideDataTooLarge`], and
640/// refused for the same reason: truncating the list is how the
641/// orientation goes missing.
642#[derive(Debug, Clone, Copy, PartialEq, Eq)]
643pub struct ImageSideDataEntries {
644 count: usize,
645 limit: usize,
646}
647
648impl ImageSideDataEntries {
649 /// Constructs an `ImageSideDataEntries` payload.
650 #[inline]
651 pub const fn new(count: usize, limit: usize) -> Self {
652 Self { count, limit }
653 }
654 /// Entries the still declared.
655 #[inline]
656 pub const fn count(&self) -> usize {
657 self.count
658 }
659 /// The cap in force.
660 #[inline]
661 pub const fn limit(&self) -> usize {
662 self.limit
663 }
664}
665
666impl core::fmt::Display for ImageSideDataEntries {
667 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
668 write!(
669 f,
670 "convert: still declares {} side-data entries over a cap of {}",
671 self.count, self.limit,
672 )
673 }
674}
675
676/// Errors from [`av_frame_to_video_frame`].
677#[derive(Debug, Clone, IsVariant, Unwrap, TryUnwrap)]
678#[non_exhaustive]
679#[unwrap(ref, ref_mut)]
680#[try_unwrap(ref, ref_mut)]
681pub enum ConvertError {
682 /// `av_frame` was null.
683 NullFrame,
684 /// The frame declares more pixels than the ceiling allows. Refused
685 /// **before** any plane is allocated.
686 TooManyPixels(TooManyPixels),
687 /// The frame's planes would export more bytes than the ceiling
688 /// allows. Refused **before** any plane is allocated.
689 FrameTooLarge(FrameTooLarge),
690 /// An audio frame declares a negative sample count.
691 InvalidSampleCount(InvalidSampleCount),
692 /// A picture frame declares a negative width or height.
693 InvalidDimensions(InvalidDimensions),
694 /// A decoded still's side data is larger than the ceiling allows.
695 ImageSideDataTooLarge(ImageSideDataTooLarge),
696 /// A decoded still declares more side-data entries than this crate
697 /// will walk.
698 ImageSideDataEntries(ImageSideDataEntries),
699 /// An audio frame's sample format has no byte width.
700 UnsupportedSampleFormat(UnsupportedSampleFormat),
701 /// An audio frame's channel count is one this crate will not carry.
702 UnsupportedChannelCount(UnsupportedChannelCount),
703 /// The frame's pixel format isn't in the closed CPU-format set this
704 /// crate supports for safe per-plane access.
705 UnsupportedPixelFormat(UnsupportedPixelFormat),
706 /// A plane reported `linesize <= 0` or otherwise inconsistent layout.
707 InvalidPlaneLayout(InvalidPlaneLayout),
708 /// A plane's `data[i]` does not lie inside any of the frame's own
709 /// `buf[]` allocations, so its extent cannot be proved.
710 BufferAcquireFailed(BufferAcquireFailed),
711 /// The plane's extent was proved and the carrier still could not be
712 /// made. See [`CarrierAllocFailed`].
713 CarrierAllocFailed(CarrierAllocFailed),
714}
715
716impl ConvertError {
717 /// Whether a decode session should **park** the frame this refusal
718 /// came from and re-attempt it before receiving another.
719 ///
720 /// The same shape as the demux seat, for the same reason: a decoder's
721 /// `receive_frame` advances libavcodec, so a conversion that then
722 /// fails on an allocation would lose a frame nothing can ask for
723 /// again. Only an allocation qualifies — every other arm here is a
724 /// fact about the frame (a format nothing can carry, a layout that
725 /// does not add up, a plane outside its own buffers), and re-offering
726 /// one of those would answer every later receive with the same error.
727 #[inline]
728 pub(crate) const fn parks_in_decode(&self) -> bool {
729 matches!(self, Self::CarrierAllocFailed(_))
730 }
731}
732
733impl core::fmt::Display for ConvertError {
734 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
735 match self {
736 Self::NullFrame => write!(f, "convert: AVFrame pointer was null"),
737 Self::TooManyPixels(p) => core::fmt::Display::fmt(p, f),
738 Self::FrameTooLarge(p) => core::fmt::Display::fmt(p, f),
739 Self::InvalidSampleCount(p) => core::fmt::Display::fmt(p, f),
740 Self::InvalidDimensions(p) => core::fmt::Display::fmt(p, f),
741 Self::ImageSideDataTooLarge(p) => core::fmt::Display::fmt(p, f),
742 Self::ImageSideDataEntries(p) => core::fmt::Display::fmt(p, f),
743 Self::UnsupportedSampleFormat(p) => core::fmt::Display::fmt(p, f),
744 Self::UnsupportedChannelCount(p) => core::fmt::Display::fmt(p, f),
745 Self::UnsupportedPixelFormat(p) => core::fmt::Display::fmt(p, f),
746 Self::InvalidPlaneLayout(p) => core::fmt::Display::fmt(p, f),
747 Self::BufferAcquireFailed(p) => core::fmt::Display::fmt(p, f),
748 Self::CarrierAllocFailed(p) => core::fmt::Display::fmt(p, f),
749 }
750 }
751}
752
753impl core::error::Error for ConvertError {}
754
755/// Builds [`ConvertError::UnsupportedPixelFormat`] for a frame whose raw
756/// format integer this crate will not deliver.
757///
758/// Both refusal sites go through here so the raw id and the name are
759/// never gathered at one of them and forgotten at the other.
760fn unsupported_pixel_format(format: PixelFormat, raw: i32) -> ConvertError {
761 ConvertError::UnsupportedPixelFormat(UnsupportedPixelFormat::new(
762 format,
763 raw,
764 crate::ffi::pix_fmt_name(raw),
765 ))
766}
767
768/// Safe wrapper around [`av_frame_to_video_frame`] taking a borrowed
769/// [`ffmpeg::Frame`](ffmpeg_next::Frame). Recommended entry point for
770/// most callers — equivalent to passing `frame.as_ptr()` to the
771/// unsafe variant, but the FFmpeg side keeps the frame alive for the
772/// duration of the call so the safety contract is satisfied
773/// internally.
774///
775/// **Borrowed source, owned lane.** This road copies, on purpose and
776/// without a lane to choose. `ffmpeg_next`'s frame wrappers lend
777/// `&mut [u8]` through `data_mut` and share their buffers by refcount
778/// with no copy-on-write, so a caller who still holds the frame holds a
779/// mutable alias of every byte a view would read — and both sides are
780/// `Send`, so the two halves need not even be on one thread. No safe
781/// signature that borrows a frame can hand out a window onto it.
782///
783/// The view lane reaches frames the way it is meant to: through a
784/// decoder, which owns the `AVFrame` it decoded into and never lends it
785/// out. A caller holding an `AVFrame` of their own can use the `unsafe`
786/// entry point below, whose contract names the obligation this
787/// signature cannot express.
788/// The lane is not a parameter here, and asking for one does not
789/// compile:
790///
791/// ```compile_fail,E0107
792/// use mediadecode_ffmpeg::{FrameLimits, View, convert::video_frame_from};
793/// let frame = ffmpeg_next::frame::Video::new(ffmpeg_next::format::Pixel::GRAY8, 64, 4);
794/// let _ = video_frame_from::<View>(&frame, mediadecode::Timebase::default(), FrameLimits::default());
795/// ```
796pub fn video_frame_from(
797 frame: &ffmpeg_next::Frame,
798 time_base: Timebase,
799 limits: FrameLimits,
800) -> Result<VideoFrame<mediadecode::PixelFormat, VideoFrameExtra, FfmpegBytes>, ConvertError> {
801 // SAFETY: `&frame` keeps the AVFrame alive for the duration of this
802 // call; the unsafe convert just reads through the pointer, and the
803 // owned lane copies every byte it reads, so nothing outlives the
804 // borrow.
805 unsafe { av_frame_to_video_frame_as::<crate::Owned>(frame.as_ptr(), time_base, limits) }
806}
807
808/// Safe wrapper around [`av_frame_to_audio_frame`] taking a borrowed
809/// [`ffmpeg::frame::Audio`](ffmpeg_next::frame::Audio).
810///
811/// **Borrowed source, owned lane.** This road copies, on purpose and
812/// without a lane to choose. `ffmpeg_next`'s frame wrappers lend
813/// `&mut [u8]` through `data_mut` and share their buffers by refcount
814/// with no copy-on-write, so a caller who still holds the frame holds a
815/// mutable alias of every byte a view would read — and both sides are
816/// `Send`, so the two halves need not even be on one thread. No safe
817/// signature that borrows a frame can hand out a window onto it.
818///
819/// The view lane reaches frames the way it is meant to: through a
820/// decoder, which owns the `AVFrame` it decoded into and never lends it
821/// out. A caller holding an `AVFrame` of their own can use the `unsafe`
822/// entry point below, whose contract names the obligation this
823/// signature cannot express.
824pub fn audio_frame_from(
825 frame: &ffmpeg_next::frame::Audio,
826 time_base: Timebase,
827 limits: FrameLimits,
828) -> Result<
829 AudioFrame<SampleFormat, ChannelLayoutDescription, AudioFrameExtra, FfmpegBytes>,
830 ConvertError,
831> {
832 // SAFETY: `&frame` keeps the AVFrame alive for the duration of this
833 // call, and the owned lane copies what it reads.
834 unsafe { av_frame_to_audio_frame_as::<crate::Owned>(frame.as_ptr(), time_base, limits) }
835}
836
837/// Safe wrapper around [`av_subtitle_to_subtitle_frame`] taking a
838/// borrowed [`ffmpeg::Subtitle`](ffmpeg_next::Subtitle).
839///
840/// Owned-lane, like its siblings — though a subtitle rect is copied on
841/// both lanes anyway (`AVSubtitleRect` has no refcounted buffer), so
842/// here the restriction costs a caller nothing at all.
843pub fn subtitle_frame_from(
844 subtitle: &ffmpeg_next::Subtitle,
845 time_base: Timebase,
846) -> Result<SubtitleFrame<SubtitleFrameExtra, FfmpegBytes>, ConvertError> {
847 // SAFETY: `&subtitle` keeps the AVSubtitle alive for the duration
848 // of this call.
849 unsafe { av_subtitle_to_subtitle_frame_as::<crate::Owned>(subtitle.as_ptr(), time_base) }
850}
851
852/// Converts an FFmpeg `AVFrame` (CPU-side, post-`av_hwframe_transfer_data`
853/// or from a software decoder) into a `mediadecode::VideoFrame`
854/// parameterized by [`crate::Ffmpeg`] / `FfmpegBytes`.
855///
856/// `time_base` is the source stream's time base, used to label
857/// `pts`/`duration` as mediatime [`Timestamp`]s.
858///
859/// # Safety
860///
861/// `av_frame` must be a live `*const AVFrame` for the duration of this
862/// call. The frame's buffers are neither consumed nor referenced —
863/// every byte the produced `VideoFrame` carries is a copy, so the
864/// source frame may be unreffed, reused or dropped the moment this
865/// returns.
866/// * no handle capable of **mutating** the frame's buffers may
867/// outlive this call while the returned carriers do. On the view
868/// lane a plane is a window into `frame`'s own allocation, and
869/// `ffmpeg_next`'s wrappers lend `&mut [u8]` by refcount with no
870/// copy-on-write — so keeping the source frame and writing through
871/// it would race a carrier a consumer is reading. Consume the
872/// frame, or use the owned lane, or use the safe borrowed wrapper
873/// (which is the owned lane for exactly this reason).
874pub(crate) unsafe fn av_frame_to_video_frame_as<C: crate::FfmpegCarrier + crate::CarrierOps>(
875 av_frame: *const AVFrame,
876 time_base: Timebase,
877 limits: FrameLimits,
878) -> Result<VideoFrame<mediadecode::PixelFormat, VideoFrameExtra, C::Buffer>, ConvertError> {
879 if av_frame.is_null() {
880 return Err(ConvertError::NullFrame);
881 }
882 // We deliberately never form `&*av_frame` — `AVFrame` contains
883 // bindgen-enum fields (`pict_type`, `color_primaries`, `colorspace`,
884 // `color_trc`, `color_range`, `chroma_location`, and an embedded
885 // `AVChannelLayout` whose `order` is also enum-typed). If FFmpeg
886 // (or a hostile decoder) writes a value outside our bindgen's
887 // discriminant set, the `&AVFrame` reference itself would be
888 // immediate UB before any field access. Working through the raw
889 // pointer with field-by-field reads (and `addr_of!` for the
890 // enum-typed fields) sidesteps this whole class.
891
892 // Non-enum primitives are safe to read via `(*av_frame).field`
893 // because validity for `i32`/`i64`/pointer types is just
894 // "initialized bytes"; the surrounding struct's enum fields don't
895 // contaminate this read.
896 let format_raw = unsafe { (*av_frame).format };
897 let width_raw = unsafe { (*av_frame).width };
898 let height_raw = unsafe { (*av_frame).height };
899 let pts_raw = unsafe { (*av_frame).pts };
900 let duration_raw = unsafe { (*av_frame).duration };
901 // **Judged before anything consumes them.** These were floored with
902 // `.max(0)`, which turned a declared `-1` into `0` — and zero pixels
903 // is under every ceiling, so the frame was built rather than refused.
904 // The same order bug the audio road had with its channel count: the
905 // field's first consumer ran ahead of the field's validator.
906 if width_raw < 0 || height_raw < 0 {
907 return Err(ConvertError::InvalidDimensions(InvalidDimensions::new(
908 width_raw, height_raw,
909 )));
910 }
911 let width = width_raw as u32;
912 let height = height_raw as u32;
913 let pix_fmt = boundary::from_av_pixel_format(format_raw);
914
915 // SAFETY: caller upholds `av_frame`'s liveness for the whole call.
916 let (planes_out, plane_count) = unsafe {
917 copy_out_planes::<C>(
918 av_frame,
919 &pix_fmt,
920 format_raw,
921 width,
922 height,
923 limits,
924 PlaneRoad::Video,
925 )
926 }?;
927
928 // pts / duration / time_base
929 let pts = if pts_raw != AV_NOPTS_VALUE {
930 Some(Timestamp::new(pts_raw, time_base))
931 } else {
932 None
933 };
934 let duration = if duration_raw > 0 {
935 Some(Timestamp::new(duration_raw, time_base))
936 } else {
937 None
938 };
939
940 // Visible rect (FFmpeg crop).
941 let visible_rect = unsafe { build_visible_rect(av_frame, width, height) };
942
943 // Color metadata (the universal cross-backend bits). We read each
944 // bindgen enum-typed field through a raw `i32` window — even
945 // referencing an out-of-range enum value is UB before any cast can
946 // run, so we never let Rust assume the field actually inhabits the
947 // enum's discriminant set. FFmpeg version skew or a buggy decoder
948 // can put unknown values into these fields.
949
950 // SAFETY: `av_frame` points at a live AVFrame; `addr_of!` computes
951 // the address without forming a reference, and `read_unaligned::<i32>`
952 // is sound because each of these enum types has the layout of
953 // `c_int` (i32) per FFmpeg's bindgen output.
954 let color_primaries_raw =
955 unsafe { read_unaligned(addr_of!((*av_frame).color_primaries) as *const i32) };
956 let color_trc_raw = unsafe { read_unaligned(addr_of!((*av_frame).color_trc) as *const i32) };
957 let colorspace_raw = unsafe { read_unaligned(addr_of!((*av_frame).colorspace) as *const i32) };
958 let color_range_raw = unsafe { read_unaligned(addr_of!((*av_frame).color_range) as *const i32) };
959 let chroma_location_raw =
960 unsafe { read_unaligned(addr_of!((*av_frame).chroma_location) as *const i32) };
961 let color = ColorInfo::UNSPECIFIED
962 .with_primaries(map_primaries(color_primaries_raw))
963 .with_transfer(map_transfer(color_trc_raw))
964 .with_matrix(map_matrix(colorspace_raw))
965 .with_range(map_range_for(&pix_fmt, color_range_raw))
966 .with_chroma_location(map_chroma_loc(chroma_location_raw));
967
968 // Backend-specific extras.
969 let extra = unsafe { build_video_frame_extra(av_frame) };
970
971 // pix_fmt is already mediadecode::PixelFormat thanks to the boundary
972 // function above, so we just pass it through.
973 let mut out = VideoFrame::new(
974 Dimensions::new(width, height),
975 pix_fmt,
976 planes_out,
977 plane_count,
978 extra,
979 )
980 .with_pts(pts)
981 .with_duration(duration)
982 .with_color(color);
983 if let Some(r) = visible_rect {
984 out = out.with_visible_rect(Some(r));
985 }
986 Ok(out)
987}
988
989/// Safe wrapper around [`av_frame_to_image_frame`] taking a borrowed
990/// [`ffmpeg::Frame`](ffmpeg_next::Frame).
991///
992/// Owned-lane, for the reason [`video_frame_from`] states: a borrowed
993/// frame cannot be safely viewed.
994pub fn image_frame_from(
995 frame: &ffmpeg_next::Frame,
996 limits: FrameLimits,
997) -> Result<ImageFrame<mediadecode::PixelFormat, ImageFrameExtra, FfmpegBytes>, ConvertError> {
998 // SAFETY: `&frame` keeps the AVFrame alive for the duration of this
999 // call, and the owned lane copies what it reads.
1000 unsafe { av_frame_to_image_frame_as::<crate::Owned>(frame.as_ptr(), limits) }
1001}
1002
1003/// Converts an FFmpeg `AVFrame` holding a decoded **still** into a
1004/// [`mediadecode::frame::ImageFrame`].
1005///
1006/// The same picture geometry as [`av_frame_to_video_frame`] — one
1007/// plane-extraction rule, shared — and none of its timeline. There is
1008/// no `time_base` parameter because there is nothing to label with it:
1009/// a still is not on the timeline, so `ImageFrame` has no `pts` and no
1010/// `duration` seats. Whatever `AVFrame.pts` a one-shot image decoder
1011/// happens to leave behind is an artefact of the packet it was fed,
1012/// not a fact about the picture, and it is deliberately dropped rather
1013/// than carried into a field that would invite a consumer to sort by
1014/// it.
1015///
1016/// `visible_rect` is FFmpeg's crop, exactly as on the video side, and
1017/// it earns its place here: a JPEG's coded dimensions are rounded up
1018/// to its MCU grid, so the crop is what distinguishes the picture from
1019/// the padding the encoder added to reach a multiple of 8 or 16.
1020///
1021/// # Safety
1022///
1023/// `av_frame` must be a live `*const AVFrame` for the duration of this
1024/// call. The frame's buffers are not consumed — every byte the
1025/// produced [`ImageFrame`] carries is a copy.
1026/// * no handle capable of **mutating** the frame's buffers may
1027/// outlive this call while the returned carriers do. On the view
1028/// lane a plane is a window into `frame`'s own allocation, and
1029/// `ffmpeg_next`'s wrappers lend `&mut [u8]` by refcount with no
1030/// copy-on-write — so keeping the source frame and writing through
1031/// it would race a carrier a consumer is reading. Consume the
1032/// frame, or use the owned lane, or use the safe borrowed wrapper
1033/// (which is the owned lane for exactly this reason).
1034pub(crate) unsafe fn av_frame_to_image_frame_as<C: crate::FfmpegCarrier + crate::CarrierOps>(
1035 av_frame: *const AVFrame,
1036 limits: FrameLimits,
1037) -> Result<ImageFrame<mediadecode::PixelFormat, ImageFrameExtra, C::Buffer>, ConvertError> {
1038 if av_frame.is_null() {
1039 return Err(ConvertError::NullFrame);
1040 }
1041 // Same stance as `av_frame_to_video_frame`: never form `&AVFrame`.
1042 // See its comments for why every read here goes through the raw
1043 // pointer, and why the enum-typed fields go through `addr_of!` +
1044 // `read_unaligned::<i32>`.
1045 let format_raw = unsafe { (*av_frame).format };
1046 let width_raw = unsafe { (*av_frame).width };
1047 let height_raw = unsafe { (*av_frame).height };
1048 // **Judged before anything consumes them.** These were floored with
1049 // `.max(0)`, which turned a declared `-1` into `0` — and zero pixels
1050 // is under every ceiling, so the frame was built rather than refused.
1051 // The same order bug the audio road had with its channel count: the
1052 // field's first consumer ran ahead of the field's validator.
1053 if width_raw < 0 || height_raw < 0 {
1054 return Err(ConvertError::InvalidDimensions(InvalidDimensions::new(
1055 width_raw, height_raw,
1056 )));
1057 }
1058 let width = width_raw as u32;
1059 let height = height_raw as u32;
1060 let pix_fmt = boundary::from_av_pixel_format(format_raw);
1061
1062 // **The still's side data is judged here, before a plane is bought.**
1063 // It reads only header fields and allocates nothing, so it is one of
1064 // the free judgements and belongs with them. After the copy it meant
1065 // an over-budget still had already paid for up to `max_frame_bytes`
1066 // of plane copies before its annotations were so much as totalled —
1067 // a correct refusal delivered after the expensive half of the work.
1068 //
1069 // Everything this conversion can refuse is now refused before
1070 // anything it can allocate is allocated.
1071 //
1072 // SAFETY: caller upholds `av_frame`'s liveness for the whole call.
1073 unsafe { measure_image_side_data(av_frame, limits) }?;
1074
1075 // SAFETY: caller upholds `av_frame`'s liveness for the whole call.
1076 let (planes_out, plane_count) = unsafe {
1077 copy_out_planes::<C>(
1078 av_frame,
1079 &pix_fmt,
1080 format_raw,
1081 width,
1082 height,
1083 limits,
1084 PlaneRoad::Still,
1085 )
1086 }?;
1087
1088 // SAFETY: `av_frame` is live; the crop fields are plain integers.
1089 let visible_rect = unsafe { build_visible_rect(av_frame, width, height) };
1090
1091 // SAFETY: `av_frame` points at a live AVFrame; each enum-typed field
1092 // is read through a raw `i32` window rather than as its bindgen enum.
1093 let color_primaries_raw =
1094 unsafe { read_unaligned(addr_of!((*av_frame).color_primaries) as *const i32) };
1095 let color_trc_raw = unsafe { read_unaligned(addr_of!((*av_frame).color_trc) as *const i32) };
1096 let colorspace_raw = unsafe { read_unaligned(addr_of!((*av_frame).colorspace) as *const i32) };
1097 let color_range_raw = unsafe { read_unaligned(addr_of!((*av_frame).color_range) as *const i32) };
1098 let chroma_location_raw =
1099 unsafe { read_unaligned(addr_of!((*av_frame).chroma_location) as *const i32) };
1100 let color = ColorInfo::UNSPECIFIED
1101 .with_primaries(map_primaries(color_primaries_raw))
1102 .with_transfer(map_transfer(color_trc_raw))
1103 .with_matrix(map_matrix(colorspace_raw))
1104 // The `yuvj*` override matters more here than anywhere: cover art
1105 // is overwhelmingly MJPEG, and MJPEG is where a frame's
1106 // `color_range` is routinely left unspecified on a signal that is
1107 // full-range by definition.
1108 .with_range(map_range_for(&pix_fmt, color_range_raw))
1109 .with_chroma_location(map_chroma_loc(chroma_location_raw));
1110
1111 // SAFETY: caller upholds liveness; the collector reads the enum-typed
1112 // `type_` raw and bounds-checks each entry's data slice.
1113 let side_data = unsafe { collect_image_side_data(av_frame, limits) }?;
1114 let extra = ImageFrameExtra::default()
1115 .with_orientation(orientation_of(&side_data))
1116 .with_side_data(side_data);
1117
1118 Ok(
1119 ImageFrame::new(
1120 Dimensions::new(width, height),
1121 pix_fmt,
1122 planes_out,
1123 plane_count,
1124 extra,
1125 )
1126 .with_visible_rect(visible_rect)
1127 .with_color(color),
1128 )
1129}
1130
1131/// The orientation a still's display matrix names, if it carries one.
1132///
1133/// Read out of the side data this crate already collects rather than
1134/// off the `AVFrame` a second time: the entry is there, whole and
1135/// unparsed, and one read is one place for the fact to come from.
1136///
1137/// `None` when the frame carries no display matrix — the ordinary case
1138/// — and also when it carries one this vocabulary cannot read, in
1139/// which case the raw entry stays in the side-data list rather than
1140/// being lost.
1141fn orientation_of(side_data: &[SideDataEntry]) -> Option<ImageOrientation> {
1142 const DISPLAY_MATRIX: i32 = AVFrameSideDataType::AV_FRAME_DATA_DISPLAYMATRIX as i32;
1143 side_data
1144 .iter()
1145 .find(|entry| entry.kind() == DISPLAY_MATRIX)
1146 .and_then(|entry| ImageOrientation::from_display_matrix(entry.data()))
1147}
1148
1149/// Whether the **video** road can deliver `pix_fmt`.
1150///
1151/// Exposed so a consumer — and this crate's own tests — can ask the
1152/// question the still road answers differently. See [`PlaneRoad`].
1153pub fn is_video_deliverable(pix_fmt: &PixelFormat) -> bool {
1154 pixdesc::is_deliverable(pix_fmt)
1155}
1156
1157/// Which plane vocabulary a conversion is working in.
1158///
1159/// The two roads differ by exactly two layouts. A still may be
1160/// paletted (`pal8`, an indexed PNG or BMP — indices in `data[0]`, a
1161/// fixed 1024-byte palette in `data[1]`) or sub-byte packed (`monob` /
1162/// `monow`, a 1-bit PNG — rows of `ceil(width / 8)`); motion video
1163/// keeps refusing both.
1164///
1165/// **The still road was widened, not the shared one, and that was a
1166/// measured choice.** Widening the shared road would have changed what
1167/// every existing video consumer can be handed — `is_supported_cpu_pix_fmt`,
1168/// the HW transfer validation and the video suites all key off the same
1169/// deliverability answer — to serve formats motion video does not
1170/// occur in. The still road is where indexed and 1-bit pictures
1171/// actually arrive, and it is one enum away.
1172///
1173/// Nothing is converted on either road. mediadecode delivers what
1174/// FFmpeg decoded; turning `pal8` into RGB is colconv's job, one tier
1175/// along, and doing it here would be this crate deciding what a
1176/// consumer's pixels should look like.
1177#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1178enum PlaneRoad {
1179 /// Motion video: the shared vocabulary.
1180 Video,
1181 /// A still: the shared vocabulary plus paletted and sub-byte
1182 /// layouts.
1183 Still,
1184}
1185
1186impl PlaneRoad {
1187 fn is_deliverable(self, pix_fmt: &PixelFormat) -> bool {
1188 match self {
1189 Self::Video => pixdesc::is_deliverable(pix_fmt),
1190 Self::Still => pixdesc::is_still_deliverable(pix_fmt),
1191 }
1192 }
1193
1194 fn plane_geometry(
1195 self,
1196 pix_fmt: &PixelFormat,
1197 width: usize,
1198 height: usize,
1199 ) -> Option<pixdesc::PlaneGeometry> {
1200 match self {
1201 Self::Video => pixdesc::plane_geometry(pix_fmt, width, height),
1202 Self::Still => pixdesc::still_plane_geometry(pix_fmt, width, height),
1203 }
1204 }
1205}
1206
1207/// The planes of a CPU-side picture `AVFrame`, copied out.
1208///
1209/// Shared by the video and image households: the geometry of a still
1210/// is the geometry of a picture, and there is one plane-extraction
1211/// rule here rather than two that could drift apart.
1212///
1213/// Returns the four-slot array and how many of its entries are
1214/// populated. Unused slots hold the shared empty carrier.
1215///
1216/// # Safety
1217///
1218/// `av_frame` must be a live `*const AVFrame` for the duration of this
1219/// call, and `format_raw` / `pix_fmt` / `width` / `height` must be the
1220/// values read from it.
1221unsafe fn copy_out_planes<C: crate::FfmpegCarrier + crate::CarrierOps>(
1222 av_frame: *const AVFrame,
1223 pix_fmt: &PixelFormat,
1224 format_raw: i32,
1225 width: u32,
1226 height: u32,
1227 limits: FrameLimits,
1228 road: PlaneRoad,
1229) -> Result<([Plane<C::Buffer>; 4], u8), ConvertError> {
1230 // The pixel ceiling, first of all — before the format is even looked
1231 // up, because a forged `width` / `height` costs nothing to write and
1232 // everything to honour. libavcodec has normally refused such a frame
1233 // already (the same number reaches `AVCodecContext.max_pixels` when a
1234 // decoder is opened from these limits), but this path also converts
1235 // frames the caller produced by other means, so the ceiling is
1236 // enforced on both sides of that door.
1237 let pixels = u64::from(width) * u64::from(height);
1238 if pixels > limits.max_pixels() {
1239 return Err(ConvertError::TooManyPixels(TooManyPixels::new(
1240 pixels,
1241 limits.max_pixels(),
1242 )));
1243 }
1244 // Reject any format whose planes we can't safely extract — HWACCEL
1245 // surfaces, Bayer mosaics, paletted, and sub-byte bitstream
1246 // packings — before touching plane memory. Without a deliverable
1247 // layout we'd be reading garbage `linesize * height` bytes.
1248 if !road.is_deliverable(pix_fmt) {
1249 return Err(unsupported_pixel_format(pix_fmt.clone(), format_raw));
1250 }
1251 // The per-plane row count and visible (tight) byte width come from
1252 // `pixdesc::plane_geometry`, which derives them from libavutil's own
1253 // `av_image_fill_linesizes` / `av_image_fill_plane_sizes` for this
1254 // exact `(format, width, height)` — correct by construction for every
1255 // deliverable CPU format. For a deliverable format `plane_geometry`
1256 // only returns `None` on out-of-range dimensions; treat that as an
1257 // unsupported frame rather than guessing a layout.
1258 let geom = match road.plane_geometry(pix_fmt, width as usize, height as usize) {
1259 Some(g) => g,
1260 None => return Err(unsupported_pixel_format(pix_fmt.clone(), format_raw)),
1261 };
1262
1263 // The byte ceiling, before a single plane is allocated. Totalled over
1264 // what the planes will *actually* export — which needs the stride
1265 // decision, so it is this crate's real allocation figure rather than
1266 // an estimate of it. A first pass to judge, a second to pay: the
1267 // alternative is discovering the frame was too big three plane
1268 // allocations in, which is the shape that OOMs.
1269 // **Judged from the geometry alone — no per-plane frame read at
1270 // all.** Every plane exports the format's own row width times its own
1271 // row count: a tight stride equals that width and a padded one is
1272 // compacted back to it, so the total does not depend on any number
1273 // the frame chose. That makes this the cheapest judgement available,
1274 // which is why it runs before the strides are so much as looked at.
1275 let mut exported: usize = 0;
1276 for plane_idx in 0..geom.count {
1277 let plane_bytes = geom.row_bytes[plane_idx]
1278 .checked_mul(geom.height[plane_idx])
1279 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1280 plane_idx,
1281 )))?;
1282 exported = exported
1283 .checked_add(plane_bytes)
1284 .ok_or(ConvertError::FrameTooLarge(FrameTooLarge::new(
1285 usize::MAX,
1286 limits.max_frame_bytes(),
1287 )))?;
1288 }
1289 if exported > limits.max_frame_bytes() {
1290 return Err(ConvertError::FrameTooLarge(FrameTooLarge::new(
1291 exported,
1292 limits.max_frame_bytes(),
1293 )));
1294 }
1295
1296 // **Then every stride, before a single plane is copied.** Splitting
1297 // this out of the copy loop is the point: the loop allocates as it
1298 // goes, so a frame refused on plane 2 had already paid for planes 0
1299 // and 1 and thrown them away. A layout fault is a property of the
1300 // frame, knowable before any of it is bought.
1301 //
1302 // An undersized stride used to be treated as a *padded* one here —
1303 // the branch for a stride that is larger — which meant the frame was
1304 // sized from a row width the plane did not have and the real refusal
1305 // was left to the copy. The copy loop keeps its own form of this
1306 // check: one comparison guarding a `from_raw_parts`, and defence in
1307 // depth at a pointer boundary is not duplication.
1308 for plane_idx in 0..geom.count {
1309 // The palette is flat: its size is the format's, and FFmpeg leaves
1310 // its `linesize` at zero deliberately, so there is no stride here
1311 // to judge.
1312 if geom.palette_plane == Some(plane_idx) {
1313 continue;
1314 }
1315 // SAFETY: `av_frame` is live per the contract and `plane_idx` is
1316 // below the descriptor's plane count, so within `linesize`'s eight
1317 // slots.
1318 let linesize = unsafe { (*av_frame).linesize[plane_idx] };
1319 // A zero stride means the decoder left a plane this format
1320 // populates unset; a negative one is FFmpeg's vertical-flip
1321 // convention, which this crate's safe accessors refuse; and one
1322 // below the row width is a plane that does not hold what the format
1323 // says it holds. All three are the same answer.
1324 if linesize <= 0 || (linesize as usize) < geom.row_bytes[plane_idx] {
1325 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1326 plane_idx,
1327 )));
1328 }
1329 }
1330
1331 let mut planes_out: [Plane<C::Buffer>; 4] = std::array::from_fn(|_| plane_placeholder::<C>());
1332 let mut plane_count: u8 = 0;
1333
1334 // The loop body indexes `planes_out`, the AVFrame's `linesize`, and
1335 // its `data` array all by `plane_idx`. None of these are slices we
1336 // can iterate via `iter_mut().enumerate()` — `linesize` / `data` are
1337 // raw `[T; 8]` fields read through `(*av_frame).field[plane_idx]`,
1338 // and `planes_out` is also indexed by the same key for symmetry —
1339 // so the index-based loop is the natural shape. The descriptor's
1340 // `count` (`1..=4`) bounds the loop to exactly the planes this format
1341 // populates.
1342 #[allow(clippy::needless_range_loop)]
1343 for plane_idx in 0..geom.count {
1344 // Read per-plane fields through the raw pointer (no `&AVFrame`
1345 // formed). `linesize` is `[c_int; 8]` and `data` is `[*mut u8; 8]`.
1346 // The palette first: a flat `AVPALETTE_SIZE` run at `data[i]` with
1347 // no linesize of its own. Bounded by the format, so there is
1348 // nothing here for a budget to judge.
1349 if geom.palette_plane == Some(plane_idx) {
1350 let data_ptr = unsafe { (*av_frame).data[plane_idx] };
1351 if data_ptr.is_null() {
1352 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1353 plane_idx,
1354 )));
1355 }
1356 let bytes = geom.row_bytes[plane_idx];
1357 // SAFETY: `find_backing_buffer` proves the run lies inside one of
1358 // the frame's own live buffers before it is read.
1359 // The palette is a flat `AVPALETTE_SIZE` run whose length is the
1360 // format's, not the file's — fully written, so shareable whole.
1361 //
1362 // SAFETY: non-null and addressing this plane.
1363 let carried =
1364 unsafe { capture_from_backing::<C>(av_frame, data_ptr as *const u8, bytes, plane_idx) }?;
1365 planes_out[plane_idx] = Plane::new(carried, bytes as u32);
1366 plane_count = (plane_idx + 1) as u8;
1367 continue;
1368 }
1369
1370 let linesize = unsafe { (*av_frame).linesize[plane_idx] };
1371 if linesize <= 0 {
1372 // `plane_idx < geom.count`, so this plane must be populated; a
1373 // zero linesize means the decoder left an expected plane unset,
1374 // and a negative linesize is FFmpeg's vertical-flip convention
1375 // (which our safe accessors refuse). Either way the layout is
1376 // unusable.
1377 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1378 plane_idx,
1379 )));
1380 }
1381 let data_ptr = unsafe { (*av_frame).data[plane_idx] };
1382 if data_ptr.is_null() {
1383 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1384 plane_idx,
1385 )));
1386 }
1387 let plane_h = geom.height[plane_idx];
1388 let row_bytes = geom.row_bytes[plane_idx];
1389 if row_bytes > linesize as usize {
1390 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1391 plane_idx,
1392 )));
1393 }
1394 // What the copy may read, and what shape it leaves behind:
1395 //
1396 // Each row in the AVBufferRef is `linesize` bytes wide but only the
1397 // first `row_bytes` of them are guaranteed-initialized (the
1398 // codec's actual output). The remaining `linesize - row_bytes`
1399 // bytes per row are FFmpeg-allocator scratch — `av_malloc`'d, not
1400 // necessarily written by the decoder. Forming an `&[u8]` over those
1401 // bytes is UB even if no consumer reads them, which is why the
1402 // padded branch never touches them.
1403 //
1404 // - When `linesize == row_bytes` (no padding), the plane is one
1405 // contiguous run and is copied whole; `stride` stays `linesize`.
1406 // - When `linesize > row_bytes`, each row is copied tightly and
1407 // `stride` becomes `row_bytes`.
1408 //
1409 // Both branches copy in 0.9 — the amputation. The *geometry* is
1410 // untouched: a consumer of a tight plane still reads the decoder's
1411 // own stride, and a padded plane still arrives compacted.
1412 let (data, exported_stride) = if (linesize as usize) == row_bytes {
1413 let plane_bytes =
1414 (plane_h)
1415 .checked_mul(linesize as usize)
1416 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1417 plane_idx,
1418 )))?;
1419 // The bounds proof: the AVBufferRef in `(*av_frame).buf[]` that
1420 // contains `data_ptr` covers at least `plane_bytes` from it. The
1421 // returned pointer is not needed — 0.8 used it to compute a view
1422 // offset; 0.9 only needs the guarantee that the read is in range.
1423 // **The tight plane is the shareable one.** `linesize ==
1424 // row_bytes` means the whole `plane_bytes` run is the decoder's
1425 // own output with nothing between the rows, so a view over it
1426 // exposes no byte that was not written. The owned lane copies it;
1427 // the view lane takes a reference to exactly this range.
1428 //
1429 // SAFETY: `data_ptr` is non-null and addresses this plane.
1430 let carried = unsafe {
1431 capture_from_backing::<C>(av_frame, data_ptr as *const u8, plane_bytes, plane_idx)
1432 }?;
1433 (carried, linesize as u32)
1434 } else {
1435 let total_bytes = row_bytes
1436 .checked_mul(plane_h)
1437 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1438 plane_idx,
1439 )))?;
1440 // Bound-check the readable extent in the source AVBufferRef
1441 // BEFORE we start dereferencing per-row offsets. The contiguous
1442 // branch above does this by passing `plane_bytes` to
1443 // `find_backing_buffer`; the row-wise branch must do the same — a
1444 // buggy or hostile decoder/filter could hand us a `data_ptr`
1445 // backed by a buffer too small for `(plane_h - 1) * linesize +
1446 // row_bytes`, in which case `from_raw_parts` on the last few
1447 // rows would form a slice over invalid memory (immediate UB,
1448 // before any read).
1449 let last_row_offset = (plane_h.saturating_sub(1))
1450 .checked_mul(linesize as usize)
1451 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1452 plane_idx,
1453 )))?;
1454 let readable_extent =
1455 last_row_offset
1456 .checked_add(row_bytes)
1457 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
1458 plane_idx,
1459 )))?;
1460 unsafe { find_backing_buffer(av_frame, data_ptr, readable_extent) }.ok_or(
1461 ConvertError::BufferAcquireFailed(BufferAcquireFailed::new(plane_idx)),
1462 )?;
1463 // **A padded plane is copied on both lanes**, and the view lane
1464 // does not get an exception here. Only the first `row_bytes` of
1465 // each `linesize`-wide row are the decoder's output; the rest is
1466 // allocator scratch nothing wrote. A carrier is an `AsRef<[u8]>`,
1467 // so sharing the padded span would form a slice over
1468 // uninitialised memory — undefined before a consumer reads a byte
1469 // of it, and the same leak the owned lane refused when it stopped
1470 // exporting `linesize`. Stopping at the last row's `row_bytes`
1471 // does not help either: the gaps *between* rows are in the span
1472 // too.
1473 //
1474 // So this is the conditional-sharing rule again, in its second
1475 // place: share where the extent is provably all output, copy
1476 // where it is not.
1477 //
1478 // Written straight into the carrier's allocation, one row at a
1479 // time — **not** staged through a `Vec` first. The staged
1480 // spelling allocated the whole plane twice and copied it twice,
1481 // so a 250 MiB frame peaked at 750 MiB counting FFmpeg's own;
1482 // this leaves the unavoidable 2×. The size was checked against
1483 // the frame ceiling above, before any of this was allocated,
1484 // which is what took the place of the staging `Vec`'s
1485 // `try_reserve_exact`.
1486 debug_assert_eq!(total_bytes, row_bytes * plane_h);
1487 let packed = C::from_rows(plane_h, row_bytes, |row_idx| {
1488 // `row_offset` cannot overflow: `readable_extent` above already
1489 // added `(plane_h - 1) * linesize` to `row_bytes` without
1490 // overflowing, and `row_idx < plane_h`.
1491 let row_offset = row_idx * linesize as usize;
1492 // SAFETY: bounds-checked above via `find_backing_buffer`;
1493 // `row_offset + row_bytes <= readable_extent <= buf.size`.
1494 // Each per-row slice is the part the decoder writes
1495 // (initialized).
1496 unsafe { core::slice::from_raw_parts(data_ptr.add(row_offset) as *const u8, row_bytes) }
1497 })
1498 .ok_or(ConvertError::CarrierAllocFailed(CarrierAllocFailed::new(
1499 plane_idx,
1500 )))?;
1501 (packed, row_bytes as u32)
1502 };
1503
1504 planes_out[plane_idx] = Plane::new(data, exported_stride);
1505 plane_count = (plane_idx + 1) as u8;
1506 }
1507
1508 Ok((planes_out, plane_count))
1509}
1510
1511/// A placeholder for an unused plane slot.
1512///
1513/// `[Plane<D>; 4]` requires four populated entries; only
1514/// `plane_count` of them are exposed through `planes()`. 0.8 gave each
1515/// slot its own one-byte `AVBufferRef` and could fail doing it; the
1516/// shared empty carrier costs one allocation for the process.
1517fn plane_placeholder<C: crate::FfmpegCarrier + crate::CarrierOps>() -> Plane<C::Buffer> {
1518 Plane::new(C::empty(), 0)
1519}
1520
1521/// # Safety
1522/// `av_frame` must be a live `*const AVFrame` for the duration of this
1523/// call. The function reads only `crop_*` fields through the raw
1524/// pointer — it never forms `&AVFrame`, so unrelated invalid enum
1525/// fields elsewhere in the struct don't matter.
1526unsafe fn build_visible_rect(av_frame: *const AVFrame, width: u32, height: u32) -> Option<Rect> {
1527 // The crops are `size_t`. Read as `u64` and kept there: `as u32`
1528 // truncated them, so a crop of `2^32 + 5` arrived as a perfectly
1529 // plausible `5` and the rect that came out was wrong in a way nothing
1530 // could see. The same law as the dimensions above — a number a file
1531 // chooses is judged, not clipped — applied to the one field on this
1532 // road that is pure annotation.
1533 let crop_left = unsafe { (*av_frame).crop_left } as u64;
1534 let crop_top = unsafe { (*av_frame).crop_top } as u64;
1535 let crop_right = unsafe { (*av_frame).crop_right } as u64;
1536 let crop_bottom = unsafe { (*av_frame).crop_bottom } as u64;
1537 if crop_left == 0 && crop_top == 0 && crop_right == 0 && crop_bottom == 0 {
1538 return None;
1539 }
1540 // A crop that does not fit inside the picture is not a crop. FFmpeg's
1541 // own `av_frame_apply_cropping` maintains `left + right < width`, so
1542 // a frame breaking that is malformed — and `saturating_sub` used to
1543 // answer it with a zero-extent rect, which is a claim rather than an
1544 // absence.
1545 //
1546 // The frame is not refused over it: the pixels are still whatever the
1547 // decoder produced, and this field only annotates them. What is
1548 // withheld is the annotation. That is the same stance the colour
1549 // fields take toward a value this build cannot name — say nothing
1550 // rather than say something invented.
1551 // Checked, per pair. These are `size_t` straight off the frame, so
1552 // each one alone can be near `u64::MAX` and `left + right` is a real
1553 // overflow — which panics in debug and *wraps* in release, and a
1554 // wrapped sum passes the extent test and then narrows into a rect
1555 // pointing outside the picture. The refusal has to come before the
1556 // arithmetic can lie, not after it.
1557 let (Some(horizontal), Some(vertical)) = (
1558 crop_left.checked_add(crop_right),
1559 crop_top.checked_add(crop_bottom),
1560 ) else {
1561 return None;
1562 };
1563 // `>=`, not `>`. FFmpeg's own `av_frame_apply_cropping` requires the
1564 // crops to leave something behind, and a sum *equal* to the extent
1565 // leaves a zero-width or zero-height rect — which is not a smaller
1566 // picture, it is the absence of one, asserted as a fact. Withheld
1567 // like any other uninterpretable annotation.
1568 if horizontal >= u64::from(width) || vertical >= u64::from(height) {
1569 return None;
1570 }
1571 // Narrowed only now. Each subtraction is proved non-negative by the
1572 // test above, and all four values are proved strictly below the
1573 // frame's own `u32` extent, so no cast here can truncate.
1574 Some(Rect::new(
1575 crop_left as u32,
1576 crop_top as u32,
1577 (u64::from(width) - horizontal) as u32,
1578 (u64::from(height) - vertical) as u32,
1579 ))
1580}
1581
1582/// # Safety
1583/// `av_frame` must be a live `*const AVFrame` for the duration of this
1584/// call. Reads each individual field through the raw pointer; never
1585/// forms a `&AVFrame` reference.
1586unsafe fn build_video_frame_extra(av_frame: *const AVFrame) -> VideoFrameExtra {
1587 let mut out = VideoFrameExtra::default();
1588 // SAR.
1589 let sar_num = unsafe { (*av_frame).sample_aspect_ratio.num };
1590 let sar_den = unsafe { (*av_frame).sample_aspect_ratio.den };
1591 if sar_num > 0 && sar_den > 0 && (sar_num != 1 || sar_den != 1) {
1592 out.set_sample_aspect_ratio(Some((sar_num as u32, sar_den as u32)));
1593 }
1594 // Picture type — read raw to avoid bindgen-enum UB if FFmpeg writes
1595 // an out-of-range value (version skew / hostile decoder).
1596
1597 // SAFETY: `av_frame` is live; reading `pict_type` as `i32` matches
1598 // the bindgen enum's underlying `c_int` storage.
1599 let pict_type_raw = unsafe { read_unaligned(addr_of!((*av_frame).pict_type) as *const i32) };
1600 out.set_picture_type(map_picture_type_raw(pict_type_raw));
1601 // Key frame and interlace flags. AVFrame.flags has dedicated bits
1602 // for these in recent FFmpeg; the deprecated fields (key_frame,
1603 // interlaced_frame, top_field_first) still mirror them.
1604 let flags = unsafe { (*av_frame).flags };
1605 out.set_key_frame(flags & ffmpeg_next::ffi::AV_FRAME_FLAG_KEY != 0);
1606 out.set_interlaced(flags & ffmpeg_next::ffi::AV_FRAME_FLAG_INTERLACED != 0);
1607 out.set_top_field_first(flags & ffmpeg_next::ffi::AV_FRAME_FLAG_TOP_FIELD_FIRST != 0);
1608 // Best-effort timestamp.
1609 let bet = unsafe { (*av_frame).best_effort_timestamp };
1610 if bet != AV_NOPTS_VALUE {
1611 out.set_best_effort_timestamp(Some(bet));
1612 }
1613 // Side data — passthrough as raw bytes, and the two statically-
1614 // shaped HDR entries additionally parsed onto their own seats.
1615 // Parsed from the already-copied `SideDataEntry` bytes rather than
1616 // re-walking `av_frame` a second time — one unsafe walk, two uses.
1617 let side_data = unsafe { collect_side_data(av_frame) };
1618 out.set_mastering_display(find_mastering_display(&side_data));
1619 out.set_content_light_level(find_content_light_level(&side_data));
1620 out.set_side_data(side_data);
1621 out
1622}
1623
1624/// Byte length of FFmpeg's in-process `AVMasteringDisplayMetadata`:
1625/// ten `AVRational`s (six chromaticities, two white-point, min and max
1626/// luminance) plus two `int` presence flags, each seat four bytes wide
1627/// and none of them padded — `10 * 8 + 2 * 4 = 88`. Not part of
1628/// `AVMasteringDisplayMetadata`'s own ABI contract (its header says so
1629/// explicitly), but true for every FFmpeg this crate has linked; a
1630/// payload shorter than this is refused rather than partially read.
1631const MASTERING_DISPLAY_METADATA_BYTES: usize = 88;
1632/// Byte length of FFmpeg's in-process `AVContentLightMetadata`: two
1633/// `unsigned` seats, `MaxCLL` then `MaxFALL`.
1634const CONTENT_LIGHT_METADATA_BYTES: usize = 8;
1635/// SMPTE ST 2086 chromaticity fixed-point unit: `raw / 50000.0` is the
1636/// CIE 1931 coordinate. Shared with [`mediaframe::color::ChromaCoord`].
1637const CHROMA_FIXED_POINT_DENOM: i64 = 50_000;
1638
1639/// Reads one native-endian `AVRational` (`{ i32 num; i32 den; }`) at
1640/// `offset`, or `None` if `bytes` is too short to hold it.
1641fn read_rational(bytes: &[u8], offset: usize) -> Option<(i32, i32)> {
1642 let num = i32::from_ne_bytes(bytes.get(offset..offset + 4)?.try_into().ok()?);
1643 let den = i32::from_ne_bytes(bytes.get(offset + 4..offset + 8)?.try_into().ok()?);
1644 Some((num, den))
1645}
1646
1647/// Resolves one CIE 1931 chromaticity coordinate's own `AVRational` to
1648/// the shared SMPTE ST 2086 fixed-point unit (`raw / 50000`), by exact
1649/// rescaling rather than truncating float math. `None` on a negative
1650/// component (chromaticity is physically non-negative — SMPTE ST 2086
1651/// and every producer this crate has observed agree) or a zero/negative
1652/// denominator, either of which marks the entry unreadable rather than
1653/// a value to carry through.
1654fn rescale_chroma_coord(num: i32, den: i32) -> Option<u32> {
1655 if num < 0 || den <= 0 {
1656 return None;
1657 }
1658 let scaled = (i64::from(num) * CHROMA_FIXED_POINT_DENOM + i64::from(den) / 2) / i64::from(den);
1659 u32::try_from(scaled).ok()
1660}
1661
1662/// A rational's `(num, den)`, verbatim as `(u32, u32)`. `None` when
1663/// `num` reads negative — [`MasteringDisplay::max_luminance`] /
1664/// [`MasteringDisplay::min_luminance`] are physical quantities and a
1665/// negative seat marks the payload corrupt rather than a value to
1666/// keep — or when `den` is not strictly positive: FFmpeg's own
1667/// `AVRational` documents a non-positive denominator as an invalid
1668/// value (`av_cmp_q`/`av_q2d` treat it as such), and `0` specifically
1669/// would make the ratio this ships as "verbatim, uninterpreted" mean
1670/// nothing at all to a caller who does go on to divide.
1671fn rational_as_u32_pair(num: i32, den: i32) -> Option<(u32, u32)> {
1672 if den <= 0 {
1673 return None;
1674 }
1675 Some((u32::try_from(num).ok()?, u32::try_from(den).ok()?))
1676}
1677
1678/// Byte offset of the `has_primaries` presence flag (`int`) in
1679/// `AVMasteringDisplayMetadata` — after the ten `AVRational`s.
1680const MASTERING_DISPLAY_HAS_PRIMARIES_OFFSET: usize = 80;
1681/// Byte offset of the `has_luminance` presence flag.
1682const MASTERING_DISPLAY_HAS_LUMINANCE_OFFSET: usize = 84;
1683
1684/// Reads one native-endian `int` (`i32`) presence flag at `offset`.
1685fn read_presence_flag(bytes: &[u8], offset: usize) -> Option<bool> {
1686 let raw = i32::from_ne_bytes(bytes.get(offset..offset + 4)?.try_into().ok()?);
1687 Some(raw != 0)
1688}
1689
1690/// Parses an `AV_FRAME_DATA_MASTERING_DISPLAY_METADATA` payload — a
1691/// byte-for-byte copy of FFmpeg's `AVMasteringDisplayMetadata` — into a
1692/// [`MasteringDisplay`]. `None` when `bytes` is shorter than
1693/// [`MASTERING_DISPLAY_METADATA_BYTES`] (a version-skew or corrupt
1694/// entry), when the struct's own `has_primaries` / `has_luminance`
1695/// presence flags (offsets [`MASTERING_DISPLAY_HAS_PRIMARIES_OFFSET`] /
1696/// [`MASTERING_DISPLAY_HAS_LUMINANCE_OFFSET`]) say either half is
1697/// unset, or when a component this function cannot make sense of.
1698///
1699/// **Both flags are required, not merely read.** `av_mastering_
1700/// display_metadata_alloc`'s own default-initialized record is ten
1701/// zeroed `AVRational`s with both flags `0` — indistinguishable, byte
1702/// for byte, from "primaries and luminance all at the coordinate
1703/// origin" unless the flags gate construction. [`MasteringDisplay`]
1704/// has no seat for reporting one half present and the other absent, so
1705/// the honest answer to a record where either flag is unset is `None`
1706/// for the whole struct, not a value with a fabricated half.
1707fn parse_mastering_display(bytes: &[u8]) -> Option<MasteringDisplay> {
1708 if bytes.len() < MASTERING_DISPLAY_METADATA_BYTES {
1709 return None;
1710 }
1711 let has_primaries = read_presence_flag(bytes, MASTERING_DISPLAY_HAS_PRIMARIES_OFFSET)?;
1712 let has_luminance = read_presence_flag(bytes, MASTERING_DISPLAY_HAS_LUMINANCE_OFFSET)?;
1713 if !has_primaries || !has_luminance {
1714 return None;
1715 }
1716 let coord = |offset: usize| -> Option<u32> {
1717 let (num, den) = read_rational(bytes, offset)?;
1718 rescale_chroma_coord(num, den)
1719 };
1720 // Offsets mirror `AVMasteringDisplayMetadata`'s field order exactly:
1721 // display_primaries[3][2] (R, G, B; each x then y), white_point[2],
1722 // min_luminance, max_luminance — verified against the linked
1723 // FFmpeg's own `libavutil/mastering_display_metadata.h` and cross-
1724 // checked with `ffprobe -show_frames` on a real HDR10 mastering
1725 // side-data entry (red_x=34000/50000, …, min_luminance=1/10000,
1726 // max_luminance=10000000/10000).
1727 let display_primaries = [
1728 (coord(0)?, coord(8)?),
1729 (coord(16)?, coord(24)?),
1730 (coord(32)?, coord(40)?),
1731 ];
1732 let white_point = (coord(48)?, coord(56)?);
1733 let (min_num, min_den) = read_rational(bytes, 64)?;
1734 let (max_num, max_den) = read_rational(bytes, 72)?;
1735 let min_luminance = rational_as_u32_pair(min_num, min_den)?;
1736 let max_luminance = rational_as_u32_pair(max_num, max_den)?;
1737 Some(MasteringDisplay::new(
1738 display_primaries,
1739 white_point,
1740 max_luminance,
1741 min_luminance,
1742 ))
1743}
1744
1745/// Parses an `AV_FRAME_DATA_CONTENT_LIGHT_LEVEL` payload — a byte-for-
1746/// byte copy of FFmpeg's `AVContentLightMetadata` (`{ unsigned MaxCLL;
1747/// unsigned MaxFALL; }`) — into a [`ContentLightLevel`]. `None` when
1748/// `bytes` is shorter than [`CONTENT_LIGHT_METADATA_BYTES`].
1749fn parse_content_light_level(bytes: &[u8]) -> Option<ContentLightLevel> {
1750 if bytes.len() < CONTENT_LIGHT_METADATA_BYTES {
1751 return None;
1752 }
1753 let max_cll = u32::from_ne_bytes(bytes.get(0..4)?.try_into().ok()?);
1754 let max_fall = u32::from_ne_bytes(bytes.get(4..8)?.try_into().ok()?);
1755 Some(ContentLightLevel::new(max_cll, max_fall))
1756}
1757
1758/// Finds the first `AV_FRAME_DATA_MASTERING_DISPLAY_METADATA` entry
1759/// among `side_data` and parses it. `None` when the frame carries no
1760/// such entry — absent metadata answers absent, not a default.
1761fn find_mastering_display(side_data: &[SideDataEntry]) -> Option<MasteringDisplay> {
1762 let kind = AVFrameSideDataType::AV_FRAME_DATA_MASTERING_DISPLAY_METADATA as i32;
1763 side_data
1764 .iter()
1765 .find(|entry| entry.kind() == kind)
1766 .and_then(|entry| parse_mastering_display(entry.data()))
1767}
1768
1769/// Finds the first `AV_FRAME_DATA_CONTENT_LIGHT_LEVEL` entry among
1770/// `side_data` and parses it. `None` when the frame carries none.
1771fn find_content_light_level(side_data: &[SideDataEntry]) -> Option<ContentLightLevel> {
1772 let kind = AVFrameSideDataType::AV_FRAME_DATA_CONTENT_LIGHT_LEVEL as i32;
1773 side_data
1774 .iter()
1775 .find(|entry| entry.kind() == kind)
1776 .and_then(|entry| parse_content_light_level(entry.data()))
1777}
1778
1779/// Maximum number of `AVFrameSideData` entries we will copy out of
1780/// a single AVFrame. Realistic streams attach a handful (mastering
1781/// display, content light level, dynamic HDR metadata, S12M
1782/// timecodes, A53 captions, …) — usually < 8. The cap exists so a
1783/// crafted stream can't drive the safe converter into a long
1784/// per-frame entry-allocation loop.
1785pub(crate) const SIDE_DATA_MAX_ENTRIES: usize = 64;
1786/// Per-AVFrame total side-data byte cap. HDR / dynamic-metadata
1787/// payloads are typically a few hundred bytes; A53 captions can run
1788/// to a few kilobytes; SEI dumps in pathological streams have been
1789/// observed in the tens of kilobytes. 256 KiB is two orders of
1790/// magnitude over the realistic upper bound while still bounded
1791/// enough that an attacker-driven OOM via metadata is impossible.
1792pub(crate) const SIDE_DATA_MAX_TOTAL_BYTES: usize = 256 * 1024;
1793
1794/// Maximum number of `AVSubtitleRect` entries we copy from a single
1795/// AVSubtitle. Realistic subtitles attach 1–4 rects per cue; 64
1796/// gives two orders of magnitude of headroom.
1797const SUBTITLE_MAX_RECTS: usize = 64;
1798/// Per-rect text/ASS payload byte cap. ASS lines exceeding this
1799/// are unrealistic; the cap exists to defeat a malicious decoder
1800/// attaching a multi-megabyte "subtitle" string.
1801const SUBTITLE_MAX_TEXT_BYTES_PER_RECT: usize = 64 * 1024;
1802/// Total text/ASS payload byte cap across all rects of a single
1803/// AVSubtitle, including newline separators.
1804const SUBTITLE_MAX_TEXT_TOTAL_BYTES: usize = 256 * 1024;
1805/// Per-rect bitmap (`linesize * height`) byte cap. DVB / PGS
1806/// subtitles realistically run to ~256 KiB on full-HD overlays;
1807/// 16 MiB is two orders of magnitude over.
1808const SUBTITLE_MAX_BITMAP_BYTES_PER_RECT: usize = 16 * 1024 * 1024;
1809/// Total bitmap byte cap across all rects of a single AVSubtitle.
1810const SUBTITLE_MAX_BITMAP_TOTAL_BYTES: usize = 32 * 1024 * 1024;
1811
1812/// Bounded counterpart to `CStr::from_ptr(p).to_bytes()`. Reads at
1813/// most `cap + 1` bytes from `ptr` looking for a NUL terminator;
1814/// returns `Some(slice)` of the bytes preceding the NUL on success,
1815/// or `None` if no NUL was found within the window (the input was
1816/// either too long or missing its required terminator entirely).
1817///
1818/// `CStr::from_ptr` walks until it hits a NUL — a valid-but-
1819/// pathological string makes that scan unbounded, and a missing
1820/// NUL is an outright UB precondition violation. This helper bounds
1821/// both at `cap + 1` bytes.
1822///
1823/// # Safety
1824/// `ptr` must be non-null and valid for reads of at least
1825/// `min(cap + 1, length-until-NUL)` bytes. FFmpeg subtitle/text
1826/// pointers satisfy this when `(*rect).text` / `.ass` is non-null
1827/// (per FFmpeg's contract — though the contract itself doesn't
1828/// bound the length).
1829unsafe fn bounded_cstr_bytes<'a>(ptr: *const core::ffi::c_char, cap: usize) -> Option<&'a [u8]> {
1830 // Read up to `cap + 1` bytes; the +1 lets a string exactly `cap`
1831 // bytes long (with a NUL at index `cap`) succeed.
1832 let max = cap.saturating_add(1);
1833 for i in 0..max {
1834 // SAFETY: Caller guarantees `ptr` is valid for reads of bytes
1835 // until the NUL or `max`. We stop at the first NUL within the
1836 // window.
1837 let byte = unsafe { *(ptr.add(i) as *const u8) };
1838 if byte == 0 {
1839 // SAFETY: `ptr` is valid for `i` byte reads (we just walked
1840 // them above). The slice doesn't include the NUL.
1841 return Some(unsafe { core::slice::from_raw_parts(ptr as *const u8, i) });
1842 }
1843 }
1844 // No NUL found within `cap + 1` bytes — input is too long or
1845 // missing its terminator. Reject.
1846 None
1847}
1848
1849/// # Safety
1850/// `av_frame` must be a live `*const AVFrame`. The function reads
1851/// `nb_side_data` and `side_data[]` through the raw pointer; each
1852/// `AVFrameSideData.type_` is read raw (it's a bindgen enum), and
1853/// each `data` payload is bounds-checked before slicing.
1854///
1855/// Memory-safety stance: this function is called on every decoded
1856/// frame, on data the decoder controls. Side-data is bounded by
1857/// [`SIDE_DATA_MAX_ENTRIES`] entries and [`SIDE_DATA_MAX_TOTAL_BYTES`]
1858/// total bytes; once either cap is reached we stop copying further
1859/// entries and a `tracing::warn!` is emitted at most once per call.
1860/// Allocations use `try_reserve_exact` so OOM surfaces as a dropped
1861/// entry rather than a process abort.
1862unsafe fn collect_side_data(av_frame: *const AVFrame) -> std::vec::Vec<SideDataEntry> {
1863 // Read `nb_side_data` as the bindgen `c_int` and clamp non-
1864 // positive values BEFORE casting to `usize`. A negative value
1865 // (corrupt / version-skew decoder output) cast directly to
1866 // `usize` becomes a huge positive count and would walk OOB
1867 // memory below; treat it as "no side data".
1868 let nb_side_data_raw = unsafe { (*av_frame).nb_side_data };
1869 let side_data = unsafe { (*av_frame).side_data };
1870 if nb_side_data_raw <= 0 || side_data.is_null() {
1871 return Vec::new();
1872 }
1873 let count_raw = nb_side_data_raw as usize;
1874 let count = count_raw.min(SIDE_DATA_MAX_ENTRIES);
1875 if count_raw > SIDE_DATA_MAX_ENTRIES {
1876 tracing::warn!(
1877 cap = SIDE_DATA_MAX_ENTRIES,
1878 requested = count_raw,
1879 "mediadecode-ffmpeg: AVFrame.nb_side_data exceeds entry cap; truncating",
1880 );
1881 }
1882 let mut out: Vec<SideDataEntry> = Vec::new();
1883 if out.try_reserve_exact(count).is_err() {
1884 return Vec::new();
1885 }
1886 let mut total_bytes: usize = 0;
1887 for i in 0..count {
1888 let sd = unsafe { *side_data.add(i) };
1889 if sd.is_null() {
1890 continue;
1891 }
1892 // `AVFrameSideData.type_` is `AVFrameSideDataType` — bindgen
1893 // enum. Read raw to avoid forming an invalid value if FFmpeg
1894 // writes an unknown discriminant (version skew).
1895 let kind = unsafe { read_unaligned(addr_of!((*sd).type_) as *const i32) };
1896 let size = unsafe { (*sd).size };
1897 let data_ptr = unsafe { (*sd).data };
1898 let data_slice = if size == 0 || data_ptr.is_null() {
1899 FfmpegBytes::empty()
1900 } else {
1901 // Byte-budget check: stop copying further side-data entries
1902 // once we've reached the per-frame cap. Earlier entries
1903 // already in `out` stay; later entries are dropped.
1904 let projected = total_bytes.saturating_add(size);
1905 if projected > SIDE_DATA_MAX_TOTAL_BYTES {
1906 tracing::warn!(
1907 cap = SIDE_DATA_MAX_TOTAL_BYTES,
1908 projected,
1909 "mediadecode-ffmpeg: AVFrame side-data byte cap reached; dropping remaining entries",
1910 );
1911 break;
1912 }
1913 total_bytes = projected;
1914 // Staged through a `Vec` first, so `try_reserve_exact` keeps
1915 // *one* of the two payload-sized allocations a dropped entry
1916 // rather than a process abort. The carrier copy that follows is a
1917 // second full allocation of the same size — not a header — and it
1918 // is infallible; what the staging buys is that the first and
1919 // larger risk is reportable and the second is asked for a size
1920 // the allocator has just proved it has. Affordable only because
1921 // side data is capped at `SIDE_DATA_MAX_TOTAL_BYTES`; the plane
1922 // path next door is not small and uses the one-allocation road.
1923 let mut buf: Vec<u8> = Vec::new();
1924 if buf.try_reserve_exact(size).is_err() {
1925 continue;
1926 }
1927 // SAFETY: `data_ptr` is documented as valid for `size` bytes
1928 // per FFmpeg's AVFrameSideData contract.
1929 let src = unsafe { core::slice::from_raw_parts(data_ptr, size) };
1930 buf.extend_from_slice(src);
1931 FfmpegBytes::copy_from_slice(&buf)
1932 };
1933 out.push(SideDataEntry::new(kind, data_slice));
1934 }
1935 out
1936}
1937
1938/// Totals a still's declared side data and judges it, **allocating
1939/// nothing and reading no payload**.
1940///
1941/// Split out of [`collect_image_side_data`] so it can run before the
1942/// planes are copied. It was not enough for the budget to be checked
1943/// before the side data was copied: `av_frame_to_image_frame` buys the
1944/// planes first, so an over-budget still had already paid for up to
1945/// `max_frame_bytes` of plane copies by the time its annotations were
1946/// judged. The refusal was correct and arrived after the expensive half
1947/// of the work.
1948///
1949/// Judging is free here. Every number this pass reads is a header
1950/// field — the entry count, and each entry's declared `size` — and no
1951/// payload is dereferenced. So it belongs at the front, with the other
1952/// free judgements.
1953///
1954/// # Safety
1955///
1956/// `av_frame` must be a live `*const AVFrame`.
1957unsafe fn measure_image_side_data(
1958 av_frame: *const AVFrame,
1959 limits: FrameLimits,
1960) -> Result<usize, ConvertError> {
1961 let nb_side_data_raw = unsafe { (*av_frame).nb_side_data };
1962 let side_data = unsafe { (*av_frame).side_data };
1963 if nb_side_data_raw <= 0 || side_data.is_null() {
1964 return Ok(0);
1965 }
1966 let count = nb_side_data_raw as usize;
1967 if count > SIDE_DATA_MAX_ENTRIES {
1968 return Err(ConvertError::ImageSideDataEntries(
1969 ImageSideDataEntries::new(count, SIDE_DATA_MAX_ENTRIES),
1970 ));
1971 }
1972 let budget = limits.max_image_side_data_bytes();
1973 let mut total: usize = 0;
1974 for i in 0..count {
1975 // The entry *pointer* comes out of the array; the entry itself is
1976 // read only for its declared size. A null slot is skipped exactly
1977 // as the copying pass skips it, so the two totals agree.
1978 let sd = unsafe { *side_data.add(i) };
1979 if sd.is_null() {
1980 continue;
1981 }
1982 let size = unsafe { (*sd).size };
1983 total = total.saturating_add(size);
1984 if total > budget {
1985 return Err(ConvertError::ImageSideDataTooLarge(
1986 ImageSideDataTooLarge::new(total, budget),
1987 ));
1988 }
1989 }
1990 Ok(total)
1991}
1992
1993/// [`collect_side_data`] for the **still** road: budgeted, and it
1994/// refuses rather than truncating.
1995///
1996/// The two roads want different answers to the same overflow. A video
1997/// stream's frame side data is small, repeated, and per-frame, so the
1998/// shared collector's fixed caps and silent drop are a reasonable trade
1999/// — losing one frame's annotation is recoverable, and refusing a
2000/// frame mid-stream is not. A still is decoded once and *is* its
2001/// annotations: the ICC profile that decides its colours and the
2002/// display matrix that decides its orientation both live here, both are
2003/// carried by exactly one frame, and dropping either is not degradation
2004/// but a wrong picture returned as a right one.
2005///
2006/// So this collector takes a budget from [`FrameLimits`] and names its
2007/// refusals. See
2008/// [`DEFAULT_MAX_IMAGE_SIDE_DATA_BYTES`](crate::DEFAULT_MAX_IMAGE_SIDE_DATA_BYTES)
2009/// for why the default is what the parameter road already admits.
2010///
2011/// # Safety
2012///
2013/// `av_frame` must be a live `*const AVFrame`.
2014unsafe fn collect_image_side_data(
2015 av_frame: *const AVFrame,
2016 limits: FrameLimits,
2017) -> Result<std::vec::Vec<SideDataEntry>, ConvertError> {
2018 // Same raw reads as the shared collector: a negative count is
2019 // malformed rather than empty, and the entry `type_` is an open C
2020 // enum read as the integer it is.
2021 let nb_side_data_raw = unsafe { (*av_frame).nb_side_data };
2022 let side_data = unsafe { (*av_frame).side_data };
2023 if nb_side_data_raw <= 0 || side_data.is_null() {
2024 return Ok(Vec::new());
2025 }
2026 let count = nb_side_data_raw as usize;
2027 let budget = limits.max_image_side_data_bytes();
2028 // **The measuring pass, re-run.** It runs earlier too — before the
2029 // planes are bought — and this is the copying pass. Repeating a pair
2030 // of comparisons that guard an allocation is defence in depth, not
2031 // duplication: it keeps this function correct on its own terms rather
2032 // than only in the order it happens to be called in.
2033 let total = unsafe { measure_image_side_data(av_frame, limits) }?;
2034
2035 let mut out: Vec<SideDataEntry> = Vec::new();
2036 if out.try_reserve_exact(count).is_err() {
2037 return Err(ConvertError::ImageSideDataTooLarge(
2038 ImageSideDataTooLarge::new(total, budget),
2039 ));
2040 }
2041 for i in 0..count {
2042 let sd = unsafe { *side_data.add(i) };
2043 if sd.is_null() {
2044 continue;
2045 }
2046 let kind = unsafe { read_unaligned(addr_of!((*sd).type_) as *const i32) };
2047 let size = unsafe { (*sd).size };
2048 let data_ptr = unsafe { (*sd).data };
2049 let payload = if size == 0 || data_ptr.is_null() {
2050 FfmpegBytes::empty()
2051 } else {
2052 // SAFETY: `data_ptr` is documented as valid for `size` bytes per
2053 // FFmpeg's `AVFrameSideData` contract, and the total was proved
2054 // to fit the budget above.
2055 let src = unsafe { core::slice::from_raw_parts(data_ptr, size) };
2056 FfmpegBytes::copy_from_slice(src)
2057 };
2058 out.push(SideDataEntry::new(kind, payload));
2059 }
2060 Ok(out)
2061}
2062
2063/// Locate the `AVBufferRef` in `(*av_frame).buf[]` that backs
2064/// `data_ptr`, confirming the requested `bytes` fit inside the buffer.
2065/// Returns `None` on no match, null/empty `buf` entries, or any
2066/// arithmetic that would overflow `usize`.
2067///
2068/// # Safety
2069/// `av_frame` must be a live `*const AVFrame`. Reads `buf[]` (an
2070/// array of pointers — no bindgen-enum validity hazards).
2071/// Captures `len` bytes at `data_ptr` out of whichever of the frame's
2072/// own buffers backs it.
2073///
2074/// **The proof runs before the capture, on both lanes.**
2075/// [`find_backing_buffer`] establishes that `data_ptr .. +len` lies
2076/// inside one of `(*av_frame).buf[]`; only then is the seam asked for a
2077/// carrier. The owned lane copies those bytes out; the view lane takes
2078/// a reference to the same range. Neither gets to skip the proof,
2079/// because it is written once, here.
2080///
2081/// The `len` a caller passes is therefore a claim about **what is
2082/// initialised**, and each medium computes it differently — see the
2083/// call sites for the per-medium rules.
2084///
2085/// # Safety
2086///
2087/// `av_frame` must be a live `*const AVFrame` and `data_ptr` must point
2088/// into one of its planes.
2089unsafe fn capture_from_backing<C: crate::FfmpegCarrier + crate::CarrierOps>(
2090 av_frame: *const AVFrame,
2091 data_ptr: *const u8,
2092 len: usize,
2093 plane_idx: usize,
2094) -> Result<C::Buffer, ConvertError> {
2095 // SAFETY: the caller upholds `av_frame`'s liveness and `data_ptr`'s
2096 // provenance.
2097 let backing = unsafe { find_backing_buffer(av_frame, data_ptr, len) }.ok_or(
2098 ConvertError::BufferAcquireFailed(BufferAcquireFailed::new(plane_idx)),
2099 )?;
2100 // SAFETY: `backing` is one of the frame's live buffers and was just
2101 // proved to cover `len` bytes from `data_ptr`.
2102 let offset = unsafe { (data_ptr as usize).wrapping_sub((*backing).data as usize) };
2103 // SAFETY: the offset and length were proved to lie inside `backing`.
2104 unsafe { C::capture(backing, offset, len) }.ok_or(ConvertError::CarrierAllocFailed(
2105 CarrierAllocFailed::new(plane_idx),
2106 ))
2107}
2108
2109unsafe fn find_backing_buffer(
2110 av_frame: *const AVFrame,
2111 data_ptr: *const u8,
2112 bytes: usize,
2113) -> Option<*mut ffmpeg_next::ffi::AVBufferRef> {
2114 let buf_array_len = unsafe { (*av_frame).buf.len() };
2115 for i in 0..buf_array_len {
2116 let buf = unsafe { (*av_frame).buf[i] };
2117 if buf.is_null() {
2118 continue;
2119 }
2120 let buf_data = unsafe { (*buf).data as *const u8 };
2121 let buf_size = unsafe { (*buf).size };
2122 if buf_data.is_null() {
2123 continue;
2124 }
2125 let start = buf_data as usize;
2126 let Some(end) = start.checked_add(buf_size) else {
2127 continue;
2128 };
2129 let dp = data_ptr as usize;
2130 let Some(dp_end) = dp.checked_add(bytes) else {
2131 continue;
2132 };
2133 if dp >= start && dp_end <= end {
2134 return Some(buf);
2135 }
2136 }
2137 None
2138}
2139
2140fn map_primaries(raw: i32) -> ColorPrimaries {
2141 match raw {
2142 x if x == AVColorPrimaries::AVCOL_PRI_BT709 as i32 => ColorPrimaries::Bt709,
2143 x if x == AVColorPrimaries::AVCOL_PRI_UNSPECIFIED as i32 => ColorPrimaries::Unspecified,
2144 x if x == AVColorPrimaries::AVCOL_PRI_BT470M as i32 => ColorPrimaries::Bt470M,
2145 x if x == AVColorPrimaries::AVCOL_PRI_BT470BG as i32 => ColorPrimaries::Bt470Bg,
2146 x if x == AVColorPrimaries::AVCOL_PRI_SMPTE170M as i32 => ColorPrimaries::Smpte170M,
2147 x if x == AVColorPrimaries::AVCOL_PRI_SMPTE240M as i32 => ColorPrimaries::Smpte240M,
2148 x if x == AVColorPrimaries::AVCOL_PRI_FILM as i32 => ColorPrimaries::Film,
2149 x if x == AVColorPrimaries::AVCOL_PRI_BT2020 as i32 => ColorPrimaries::Bt2020,
2150 x if x == AVColorPrimaries::AVCOL_PRI_SMPTE428 as i32 => ColorPrimaries::SmpteSt428,
2151 x if x == AVColorPrimaries::AVCOL_PRI_SMPTE431 as i32 => ColorPrimaries::SmpteRp431,
2152 x if x == AVColorPrimaries::AVCOL_PRI_SMPTE432 as i32 => ColorPrimaries::SmpteEg432,
2153 x if x == AVColorPrimaries::AVCOL_PRI_EBU3213 as i32 => ColorPrimaries::Ebu3213E,
2154 _ => ColorPrimaries::Unspecified,
2155 }
2156}
2157
2158fn map_transfer(raw: i32) -> ColorTransfer {
2159 match raw {
2160 x if x == AVColorTransferCharacteristic::AVCOL_TRC_BT709 as i32 => ColorTransfer::Bt709,
2161 x if x == AVColorTransferCharacteristic::AVCOL_TRC_UNSPECIFIED as i32 => {
2162 ColorTransfer::Unspecified
2163 }
2164 x if x == AVColorTransferCharacteristic::AVCOL_TRC_GAMMA22 as i32 => ColorTransfer::Gamma22,
2165 x if x == AVColorTransferCharacteristic::AVCOL_TRC_GAMMA28 as i32 => ColorTransfer::Gamma28,
2166 x if x == AVColorTransferCharacteristic::AVCOL_TRC_SMPTE170M as i32 => ColorTransfer::Smpte170M,
2167 x if x == AVColorTransferCharacteristic::AVCOL_TRC_SMPTE240M as i32 => ColorTransfer::Smpte240M,
2168 x if x == AVColorTransferCharacteristic::AVCOL_TRC_LINEAR as i32 => ColorTransfer::Linear,
2169 x if x == AVColorTransferCharacteristic::AVCOL_TRC_LOG as i32 => ColorTransfer::Log100,
2170 x if x == AVColorTransferCharacteristic::AVCOL_TRC_LOG_SQRT as i32 => ColorTransfer::Log316,
2171 x if x == AVColorTransferCharacteristic::AVCOL_TRC_IEC61966_2_4 as i32 => {
2172 ColorTransfer::Iec6196624
2173 }
2174 x if x == AVColorTransferCharacteristic::AVCOL_TRC_BT1361_ECG as i32 => {
2175 ColorTransfer::Bt1361Ecg
2176 }
2177 x if x == AVColorTransferCharacteristic::AVCOL_TRC_IEC61966_2_1 as i32 => {
2178 ColorTransfer::Iec6196621
2179 }
2180 x if x == AVColorTransferCharacteristic::AVCOL_TRC_BT2020_10 as i32 => {
2181 ColorTransfer::Bt2020_10Bit
2182 }
2183 x if x == AVColorTransferCharacteristic::AVCOL_TRC_BT2020_12 as i32 => {
2184 ColorTransfer::Bt2020_12Bit
2185 }
2186 x if x == AVColorTransferCharacteristic::AVCOL_TRC_SMPTE2084 as i32 => {
2187 ColorTransfer::SmpteSt2084Pq
2188 }
2189 x if x == AVColorTransferCharacteristic::AVCOL_TRC_SMPTE428 as i32 => ColorTransfer::SmpteSt428,
2190 x if x == AVColorTransferCharacteristic::AVCOL_TRC_ARIB_STD_B67 as i32 => {
2191 ColorTransfer::AribStdB67Hlg
2192 }
2193 _ => ColorTransfer::Unspecified,
2194 }
2195}
2196
2197fn map_matrix(raw: i32) -> ColorMatrix {
2198 match raw {
2199 x if x == AVColorSpace::AVCOL_SPC_BT709 as i32 => ColorMatrix::Bt709,
2200 x if x == AVColorSpace::AVCOL_SPC_BT2020_NCL as i32 => ColorMatrix::Bt2020Ncl,
2201 x if x == AVColorSpace::AVCOL_SPC_SMPTE170M as i32 => ColorMatrix::Bt601,
2202 x if x == AVColorSpace::AVCOL_SPC_BT470BG as i32 => ColorMatrix::Bt601,
2203 x if x == AVColorSpace::AVCOL_SPC_SMPTE240M as i32 => ColorMatrix::Smpte240m,
2204 x if x == AVColorSpace::AVCOL_SPC_FCC as i32 => ColorMatrix::Fcc,
2205 x if x == AVColorSpace::AVCOL_SPC_YCGCO as i32 => ColorMatrix::YCgCo,
2206 _ => ColorMatrix::Bt709, // ColorMatrix has no Unspecified; Bt709 is FFmpeg's height>=720 default
2207 }
2208}
2209
2210fn map_range(raw: i32) -> ColorRange {
2211 match raw {
2212 x if x == AVColorRange::AVCOL_RANGE_JPEG as i32 => ColorRange::Full,
2213 x if x == AVColorRange::AVCOL_RANGE_MPEG as i32 => ColorRange::Limited,
2214 _ => ColorRange::Unspecified,
2215 }
2216}
2217
2218/// `true` for the JPEG-range planar YUV (`yuvj*`) formats. These are
2219/// **full-range by definition** — the `j` is FFmpeg's marker for an
2220/// MJPEG/JPEG-family full-swing signal — so their color range is a
2221/// property of the format itself, not something the frame's
2222/// `color_range` field needs to (or reliably does) carry.
2223fn is_yuvj(pix_fmt: &PixelFormat) -> bool {
2224 matches!(
2225 pix_fmt,
2226 PixelFormat::Yuvj411p
2227 | PixelFormat::Yuvj420p
2228 | PixelFormat::Yuvj422p
2229 | PixelFormat::Yuvj440p
2230 | PixelFormat::Yuvj444p
2231 )
2232}
2233
2234/// Derives the delivered [`ColorRange`] from the frame's `color_range`
2235/// field, honoring the range a pixel format *implies*.
2236///
2237/// A `yuvj*` frame is JPEG full-range by definition, but its
2238/// `AVFrame.color_range` is frequently `AVCOL_RANGE_UNSPECIFIED` (the
2239/// MJPEG/JPEG decode paths don't always stamp it). Deriving the range
2240/// purely from that field would mislabel a full-range frame as
2241/// `Unspecified` (which downstream YUV→RGB conversion reads as the
2242/// Limited-swing default) — a silent decode-correctness regression. So
2243/// for the `yuvj*` family we force [`ColorRange::Full`] regardless of
2244/// the field. Every other format defers entirely to `color_range`.
2245fn map_range_for(pix_fmt: &PixelFormat, color_range_raw: i32) -> ColorRange {
2246 if is_yuvj(pix_fmt) {
2247 return ColorRange::Full;
2248 }
2249 map_range(color_range_raw)
2250}
2251
2252fn map_chroma_loc(raw: i32) -> ChromaLocation {
2253 match raw {
2254 x if x == AVChromaLocation::AVCHROMA_LOC_LEFT as i32 => ChromaLocation::Left,
2255 x if x == AVChromaLocation::AVCHROMA_LOC_CENTER as i32 => ChromaLocation::Center,
2256 x if x == AVChromaLocation::AVCHROMA_LOC_TOPLEFT as i32 => ChromaLocation::TopLeft,
2257 x if x == AVChromaLocation::AVCHROMA_LOC_TOP as i32 => ChromaLocation::Top,
2258 x if x == AVChromaLocation::AVCHROMA_LOC_BOTTOMLEFT as i32 => ChromaLocation::BottomLeft,
2259 x if x == AVChromaLocation::AVCHROMA_LOC_BOTTOM as i32 => ChromaLocation::Bottom,
2260 _ => ChromaLocation::Unspecified,
2261 }
2262}
2263
2264/// Converts an FFmpeg audio `AVFrame` into a `mediadecode::AudioFrame`.
2265///
2266/// Each plane is copied out of the source frame's `AVBufferRef`
2267/// entries into an `FfmpegBytes` (the corresponding `data[i]` is always
2268/// covered by exactly one of `buf[i]` per FFmpeg's contract, which is
2269/// what bounds the read). Channel counts above 8 (which would spill
2270/// into `extended_buf`) are refused rather than clamped — see the
2271/// plane-count check below.
2272///
2273/// # Safety
2274///
2275/// `av_frame` must be a live `*const AVFrame` for the duration of this
2276/// call and must describe an audio frame (`format` is an
2277/// `AVSampleFormat`, `nb_samples > 0`, and `data[]` / `buf[]`
2278/// populated). The frame's buffers are neither consumed nor
2279/// referenced; every byte the produced `AudioFrame` carries is a copy.
2280/// * no handle capable of **mutating** the frame's buffers may
2281/// outlive this call while the returned carriers do. On the view
2282/// lane a plane is a window into `frame`'s own allocation, and
2283/// `ffmpeg_next`'s wrappers lend `&mut [u8]` by refcount with no
2284/// copy-on-write — so keeping the source frame and writing through
2285/// it would race a carrier a consumer is reading. Consume the
2286/// frame, or use the owned lane, or use the safe borrowed wrapper
2287/// (which is the owned lane for exactly this reason).
2288pub(crate) unsafe fn av_frame_to_audio_frame_as<C: crate::FfmpegCarrier + crate::CarrierOps>(
2289 av_frame: *const AVFrame,
2290 time_base: Timebase,
2291 limits: FrameLimits,
2292) -> Result<
2293 AudioFrame<SampleFormat, ChannelLayoutDescription, AudioFrameExtra, C::Buffer>,
2294 ConvertError,
2295> {
2296 if av_frame.is_null() {
2297 return Err(ConvertError::NullFrame);
2298 }
2299 // Same stance as `av_frame_to_video_frame`: never form `&AVFrame`.
2300 // Read every field through the raw pointer; for `ch_layout` (which
2301 // contains an `order: AVChannelOrder` enum) we hand the raw pointer
2302 // straight into
2303 // `channel_layout::channel_layout_description_from_raw_ptr`,
2304 // which validates `order` as `i32` before constructing any
2305 // `AVChannelOrder` value.
2306 let format_raw = unsafe { (*av_frame).format };
2307 let sample_rate_raw = unsafe { (*av_frame).sample_rate };
2308 let nb_samples_raw = unsafe { (*av_frame).nb_samples };
2309 let pts_raw = unsafe { (*av_frame).pts };
2310 let duration_raw = unsafe { (*av_frame).duration };
2311 let bet_raw = unsafe { (*av_frame).best_effort_timestamp };
2312
2313 let sample_format = SampleFormat::from_raw(format_raw);
2314 let sample_rate = sample_rate_raw.max(0) as u32;
2315
2316 // **Every header field is judged here, before a byte of geometry is
2317 // computed — and none of them is clamped.**
2318 //
2319 // A clamp on this road is silent truncation of an attacker-supplied
2320 // number, which is the exact sin this boundary exists to refuse. The
2321 // three that mattered each produced a *well-formed-looking* frame out
2322 // of a malformed one, which is worse than an error: a floored
2323 // negative count became an empty frame a consumer went on decoding
2324 // past, and a clipped channel count made a packed frame compute its
2325 // byte product from 255 when the file said 256 — copying 510 of 512
2326 // bytes and advertising the wrong shape.
2327 //
2328 // The one survivor is `sample_rate`, floored above. Censused and
2329 // kept: it feeds no geometry, no allocation and no copy length — it
2330 // is metadata — and zero is already this crate's "rate unspecified".
2331 // Nothing downstream sizes anything from it.
2332 if nb_samples_raw < 0 {
2333 return Err(ConvertError::InvalidSampleCount(InvalidSampleCount::new(
2334 nb_samples_raw,
2335 )));
2336 }
2337 let nb_samples = nb_samples_raw as u32;
2338
2339 // SAFETY: `av_frame` is a live `*const AVFrame`; passing the
2340 // address of the embedded ch_layout as `*const AVChannelLayout`
2341 // is sound because `addr_of!` doesn't form a reference.
2342 let ch_layout_ptr = unsafe { addr_of!((*av_frame).ch_layout) };
2343
2344 // **The channel count is judged off the raw field, before the layout
2345 // is materialised.** The first version of this guard read it back off
2346 // the `ChannelLayoutDescription`, which was two bugs at once:
2347 //
2348 // * the description stores `nb_channels.max(0) as u32`, so a declared
2349 // `-1` reached the guard as a legitimate-looking zero and produced
2350 // a zero-channel frame instead of a refusal — the validator was
2351 // reading a number its own consumer had already laundered; and
2352 // * materialising runs first. For an `AV_CHANNEL_ORDER_CUSTOM`
2353 // layout that means rendering the layout's name and walking
2354 // `nb_channels` map entries into a `Vec` — work proportional to a
2355 // number this very guard exists to bound, done *before* the bound
2356 // is applied.
2357 //
2358 // A validator downstream of its own field's first consumer is not a
2359 // validator. The raw signed read comes first, every refusal is stated
2360 // against it, and only a count already proved to be in `0..=255` is
2361 // allowed to drive the description.
2362 //
2363 // SAFETY: `ch_layout_ptr` addresses the frame's live embedded layout.
2364 // `nb_channels` is a plain `c_int`, so a direct field read through the
2365 // raw pointer is sound — the enum-typed `order` beside it is what
2366 // needs `addr_of!` + a raw `i32` read, and that read happens inside
2367 // the description helper below, not here.
2368 let channel_count_raw = unsafe { (*ch_layout_ptr).nb_channels };
2369 if channel_count_raw < 0 {
2370 return Err(ConvertError::UnsupportedChannelCount(
2371 UnsupportedChannelCount::new(channel_count_raw),
2372 ));
2373 }
2374 // Refused before any plane geometry, and refused for packed layouts
2375 // too — which the old `> 8` plane check never reached, because packed
2376 // audio declares one plane whatever its channel count is.
2377 if channel_count_raw > i32::from(u8::MAX) {
2378 return Err(ConvertError::UnsupportedChannelCount(
2379 UnsupportedChannelCount::new(channel_count_raw),
2380 ));
2381 }
2382 // A frame carrying samples across no channels is not an empty frame;
2383 // it is an incoherent one. The packed byte product used to substitute
2384 // 1 here, which invented a channel the file never declared.
2385 if channel_count_raw == 0 && nb_samples > 0 {
2386 return Err(ConvertError::UnsupportedChannelCount(
2387 UnsupportedChannelCount::new(channel_count_raw),
2388 ));
2389 }
2390 let channel_count_full = channel_count_raw as u32;
2391 let channel_count = channel_count_raw as u8;
2392
2393 // Materialised only now, with the count it will report already
2394 // proved to be one this crate can carry. Because the raw field is in
2395 // `0..=255`, the description's own `nb_channels.max(0)` is the
2396 // identity here and its `channels()` equals `channel_count_full`.
2397 let channel_layout =
2398 unsafe { crate::channel_layout::channel_layout_description_from_raw_ptr(ch_layout_ptr) };
2399 debug_assert_eq!(
2400 channel_layout.channels(),
2401 channel_count_full,
2402 "the description must report the count that was judged",
2403 );
2404
2405 // The sample format, **before** the zero-sample shortcut: a frame
2406 // whose format has no byte width is malformed whether or not it
2407 // carries samples, and letting an empty one through returned an
2408 // `AudioFrame` advertising a format nothing can interpret.
2409 let bytes_per_sample =
2410 sample_format
2411 .bytes_per_sample()
2412 .ok_or(ConvertError::UnsupportedSampleFormat(
2413 UnsupportedSampleFormat::new(format_raw),
2414 ))? as usize;
2415
2416 // Plane count: 1 for packed, channel_count for planar.
2417 let is_planar = sample_format.is_planar();
2418 let plane_count_full = if is_planar { channel_count as usize } else { 1 };
2419 // mediadecode's `AudioFrame` carries up to 8 plane slots
2420 // (matching `AV_NUM_DATA_POINTERS`). Planar audio with more than
2421 // 8 channels uses `AVFrame.extended_data[]` / `extended_buf[]`,
2422 // which we don't yet plumb through. Refuse the frame rather than
2423 // silently truncating to the first 8 channels and returning an
2424 // `AudioFrame` whose advertised `channel_count` exceeds its
2425 // populated plane count.
2426 if plane_count_full > 8 {
2427 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(8)));
2428 }
2429 let plane_count = plane_count_full as u8;
2430
2431 // **Two different numbers, and conflating them was a bug.**
2432 //
2433 // `linesize[0]` is what FFmpeg *allocated* per plane, which
2434 // `av_samples_get_buffer_size` rounds up for alignment — routinely
2435 // 32 or 64 bytes past the samples. The bytes that are *valid* are
2436 // `nb_samples * bytes_per_sample`, per plane when planar and times
2437 // the channel count when packed. Nothing initialises the difference.
2438 //
2439 // Exporting `linesize` therefore did two wrong things at once: it
2440 // formed a `&[u8]` over maybe-uninitialised padding, which is
2441 // undefined behaviour before anything reads it, and it handed that
2442 // padding to a consumer inside a safe `FfmpegBytes` — stale heap,
2443 // leaked through an owned carrier.
2444 //
2445 // So `linesize` is used for exactly one thing below: proving the
2446 // source allocation really is as large as it claims. What is copied
2447 // is the valid product. This is what the resampler's own output path
2448 // has always done (`per_sample * produced`); the decode path now
2449 // agrees with it.
2450 let linesize0 = unsafe { (*av_frame).linesize[0] };
2451 // A negative allocation is incoherent at any sample count, so it is
2452 // refused before the count is consulted rather than floored to zero.
2453 // Zero itself is only refused when the frame claims samples — it is
2454 // the canonical shape of an empty audio frame.
2455 if linesize0 < 0 || (nb_samples > 0 && linesize0 == 0) {
2456 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)));
2457 }
2458 let allocated_per_plane = linesize0 as usize;
2459 let valid_per_plane = if nb_samples_raw == 0 {
2460 // A header frame: real, and carrying no samples. There is nothing
2461 // valid to export, whatever the allocation says. Reached only for a
2462 // count that is *exactly* zero — a negative one was refused by name
2463 // above rather than floored into this branch.
2464 0
2465 } else {
2466 let valid = if is_planar {
2467 // Planar: each plane carries `nb_samples * bytes_per_sample`.
2468 (nb_samples as usize)
2469 .checked_mul(bytes_per_sample)
2470 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)))?
2471 } else {
2472 // Packed: the single plane interleaves all channels.
2473 // The **declared** channel count, never a substituted one: it was
2474 // proved above to be in `1..=u8::MAX` on a frame with samples.
2475 (nb_samples as usize)
2476 .checked_mul(bytes_per_sample)
2477 .and_then(|x| x.checked_mul(channel_count_full as usize))
2478 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)))?
2479 };
2480 // The allocation must cover the samples the header claims —
2481 // otherwise a shrunk `linesize` would let a consumer that trusts
2482 // `nb_samples` read past what is there.
2483 if allocated_per_plane < valid {
2484 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)));
2485 }
2486 valid
2487 };
2488
2489 // The byte ceiling, before a single plane is allocated. An audio
2490 // frame has no pixels to bound, so this is the whole ceiling here —
2491 // and it is needed: `linesize[0]` is a number from the decoder, and
2492 // the check above only proves it is not *smaller* than the format
2493 // requires. Nothing above bounds it from the other side.
2494 let exported =
2495 valid_per_plane
2496 .checked_mul(plane_count as usize)
2497 .ok_or(ConvertError::FrameTooLarge(FrameTooLarge::new(
2498 usize::MAX,
2499 limits.max_frame_bytes(),
2500 )))?;
2501 if exported > limits.max_frame_bytes() {
2502 return Err(ConvertError::FrameTooLarge(FrameTooLarge::new(
2503 exported,
2504 limits.max_frame_bytes(),
2505 )));
2506 }
2507
2508 // Every slot starts as the shared empty carrier at stride zero, which
2509 // is already exactly what a zero-sample frame's planes should be.
2510 let mut planes_out: [Plane<C::Buffer>; 8] = std::array::from_fn(|_| plane_placeholder::<C>());
2511
2512 // **A zero-sample frame has no planes to validate.** FFmpeg's
2513 // canonical empty audio frame carries a format, a layout and a rate
2514 // with `data[i] == NULL`, `linesize == 0` and no `AVBufferRef` at
2515 // all — there is nothing allocated because there is nothing to hold.
2516 // Running the loop below over it refused the frame on the first null
2517 // pointer, so a header frame mid-stream came back as
2518 // `InvalidPlaneLayout` and interrupted a decode that was going fine.
2519 //
2520 // The declared layout is still reported: `plane_count` stays packed's
2521 // 1 or planar's channel count, and those slots hold the empty carrier
2522 // at stride 0 — a consumer sees the shape it expects, carrying no
2523 // samples, which is what the frame says. No allocation happens; the
2524 // empty carrier is one refcount bump.
2525 //
2526 // Nothing below changes for a frame that does carry samples: the loop
2527 // body is untouched, and this only decides whether it runs at all.
2528 let populated = if valid_per_plane == 0 {
2529 0
2530 } else {
2531 plane_count as usize
2532 };
2533
2534 // Same rationale as in the video path — index-by-key over three
2535 // unrelated raw arrays (`planes_out`, `(*av_frame).data`, and the
2536 // implicit per-plane bookkeeping); no slice iteration applies.
2537 #[allow(clippy::needless_range_loop)]
2538 for plane_idx in 0..populated {
2539 let data_ptr = unsafe { (*av_frame).data[plane_idx] };
2540 if data_ptr.is_null() {
2541 // A null plane in a planar layout (or the sole plane in a
2542 // packed layout) means the decoder produced an incomplete
2543 // frame — surface as an error rather than returning a frame
2544 // whose `planes()` exposes empty placeholder channels for
2545 // the missing data.
2546 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(
2547 plane_idx,
2548 )));
2549 }
2550 // The bounds proof, against the **allocation**: the plane really is
2551 // as large as its `linesize` claims, and lies inside one of the
2552 // frame's own buffers. This is the only thing `linesize` is used
2553 // for.
2554 let backing = unsafe { find_audio_backing_buffer(av_frame, data_ptr, allocated_per_plane) }
2555 .ok_or(ConvertError::BufferAcquireFailed(BufferAcquireFailed::new(
2556 plane_idx,
2557 )))?;
2558 // Lossless, and provably so rather than by ceiling: this branch runs
2559 // only when `valid_per_plane <= allocated_per_plane`, which is an
2560 // `i32` read from `linesize[0]` proved non-negative above. No plane
2561 // can exceed `i32::MAX` bytes, so nothing here is truncated even if
2562 // a caller raises `max_frame_bytes` past `u32::MAX`.
2563 // **Audio stops at exactly the valid bytes, on both lanes.**
2564 // `linesize[0]` is what `av_samples_get_buffer_size` *allocated*,
2565 // rounded up for alignment; what the decoder wrote is
2566 // `nb_samples * bytes_per_sample` (times the channels when packed).
2567 // The difference is untouched allocator memory — the R5 finding —
2568 // and it is no more exportable through a view than it was through a
2569 // copy: a carrier is an `AsRef<[u8]>`, so the span it names is the
2570 // span a consumer may read, and padding in that span is the same
2571 // information leak whoever formed it.
2572 //
2573 // So the view lane shares the **prefix**, not the plane. Which is
2574 // also why `linesize` is used for exactly one thing here: proving
2575 // the allocation really is as large as it claims.
2576 //
2577 // SAFETY: `backing` is one of the frame's live buffers, proved above
2578 // to cover `allocated_per_plane` bytes from `data_ptr`, and
2579 // `valid_per_plane <= allocated_per_plane`.
2580 let offset = unsafe { (data_ptr as usize).wrapping_sub((*backing).data as usize) };
2581 // SAFETY: the offset and length lie inside `backing` by the proof
2582 // above.
2583 let carried = unsafe { C::capture(backing, offset, valid_per_plane) }.ok_or(
2584 ConvertError::CarrierAllocFailed(CarrierAllocFailed::new(plane_idx)),
2585 )?;
2586 planes_out[plane_idx] = Plane::new(carried, valid_per_plane as u32);
2587 }
2588
2589 let pts = if pts_raw != AV_NOPTS_VALUE {
2590 Some(Timestamp::new(pts_raw, time_base))
2591 } else {
2592 None
2593 };
2594 let duration = if duration_raw > 0 {
2595 Some(Timestamp::new(duration_raw, time_base))
2596 } else {
2597 None
2598 };
2599
2600 let mut extra = AudioFrameExtra::default();
2601 if bet_raw != AV_NOPTS_VALUE {
2602 extra.set_best_effort_timestamp(Some(bet_raw));
2603 }
2604 // SAFETY: caller upholds liveness for the duration of the call;
2605 // collect_side_data reads enum-typed `type_` raw and bounds-checks
2606 // each entry's data slice.
2607 extra.set_side_data(unsafe { collect_side_data(av_frame) });
2608
2609 Ok(
2610 AudioFrame::new(
2611 sample_rate,
2612 nb_samples,
2613 channel_count,
2614 sample_format,
2615 channel_layout,
2616 planes_out,
2617 plane_count,
2618 extra,
2619 )
2620 .with_pts(pts)
2621 .with_duration(duration),
2622 )
2623}
2624
2625/// The `AVBufferRef` in `(*av_frame).buf[]` that backs `data_ptr` for
2626/// `bytes` bytes, or `None` when none of them does.
2627///
2628/// # Safety
2629/// `av_frame` must be a live `*const AVFrame`.
2630pub(crate) unsafe fn find_audio_backing_buffer(
2631 av_frame: *const AVFrame,
2632 data_ptr: *const u8,
2633 bytes: usize,
2634) -> Option<*mut ffmpeg_next::ffi::AVBufferRef> {
2635 // Audio frames pack each plane into a separate AVBufferRef in buf[].
2636 // Same scan as the video path — finds whichever buffer's data range
2637 // contains data_ptr. Overflow-safe arithmetic per
2638 // `find_backing_buffer`'s rationale.
2639 let buf_array_len = unsafe { (*av_frame).buf.len() };
2640 for i in 0..buf_array_len {
2641 let buf = unsafe { (*av_frame).buf[i] };
2642 if buf.is_null() {
2643 continue;
2644 }
2645 let buf_data = unsafe { (*buf).data as *const u8 };
2646 let buf_size = unsafe { (*buf).size };
2647 if buf_data.is_null() {
2648 continue;
2649 }
2650 let start = buf_data as usize;
2651 let Some(end) = start.checked_add(buf_size) else {
2652 continue;
2653 };
2654 let dp = data_ptr as usize;
2655 let Some(dp_end) = dp.checked_add(bytes) else {
2656 continue;
2657 };
2658 if dp >= start && dp_end <= end {
2659 return Some(buf);
2660 }
2661 }
2662 None
2663}
2664
2665/// Converts an FFmpeg `AVSubtitle` into a `mediadecode::SubtitleFrame`.
2666///
2667/// Strategy:
2668/// - If the subtitle contains any text/ASS rects, produce a
2669/// [`SubtitlePayload::Text`] whose buffer is the concatenation of
2670/// their UTF-8 contents (newline-separated).
2671/// - Otherwise, if the subtitle contains bitmap rects, produce a
2672/// [`SubtitlePayload::Bitmap`] with one [`mediadecode::subtitle::BitmapRegion`]
2673/// per rect (paletted indices and RGBA palette copied into fresh
2674/// owned `FfmpegBytes` carriers, since `AVSubtitleRect` data is not
2675/// refcounted and does not outlive the `AVSubtitle`).
2676/// - An empty subtitle (no rects) becomes an empty `Text` payload.
2677///
2678/// `time_base` is the source stream's time base, used to label
2679/// `pts` / `duration`. The duration is computed as
2680/// `(end_display_time - start_display_time)` in milliseconds, then
2681/// rescaled into `time_base`.
2682///
2683/// # Safety
2684///
2685/// `av_subtitle` must be a live `*const AVSubtitle` for the duration
2686/// of this call; the rect array (`av_subtitle.rects`) must be valid
2687/// for `av_subtitle.num_rects` entries.
2688/// * no handle capable of **mutating** the frame's buffers may
2689/// outlive this call while the returned carriers do. On the view
2690/// lane a plane is a window into `frame`'s own allocation, and
2691/// `ffmpeg_next`'s wrappers lend `&mut [u8]` by refcount with no
2692/// copy-on-write — so keeping the source frame and writing through
2693/// it would race a carrier a consumer is reading. Consume the
2694/// frame, or use the owned lane, or use the safe borrowed wrapper
2695/// (which is the owned lane for exactly this reason).
2696pub(crate) unsafe fn av_subtitle_to_subtitle_frame_as<
2697 C: crate::FfmpegCarrier + crate::CarrierOps,
2698>(
2699 av_subtitle: *const ffmpeg_next::ffi::AVSubtitle,
2700 time_base: Timebase,
2701) -> Result<SubtitleFrame<SubtitleFrameExtra, C::Buffer>, ConvertError> {
2702 if av_subtitle.is_null() {
2703 return Err(ConvertError::NullFrame);
2704 }
2705 // Same stance as `av_frame_to_video_frame`: never form `&AVSubtitle`
2706 // or `&AVSubtitleRect` (both contain `type_: AVSubtitleType` enum
2707 // fields). Read every field through the raw pointer.
2708
2709 let mut text_chunks: std::vec::Vec<u8> = std::vec::Vec::new();
2710 let mut bitmap_regions: std::vec::Vec<mediadecode::subtitle::BitmapRegion<C::Buffer>> =
2711 std::vec::Vec::new();
2712
2713 let count_raw = unsafe { (*av_subtitle).num_rects } as usize;
2714 let rects_ptr = unsafe { (*av_subtitle).rects };
2715 // Defensive: `num_rects > 0` with `rects == null` would be a malformed
2716 // AVSubtitle, but a hostile decoder could produce one — bail rather
2717 // than dereferencing.
2718 if count_raw > 0 && rects_ptr.is_null() {
2719 return Err(ConvertError::NullFrame);
2720 }
2721 // Cap rect count, total text bytes, and total bitmap bytes
2722 // against decoder-controlled metadata. Realistic subtitles carry
2723 // a handful of rects (typically 1–4 per displayed cue), text
2724 // payloads in the low kilobytes (ASS lines), and bitmap
2725 // payloads in the low hundreds of KiB (DVB / PGS). These caps
2726 // are two orders of magnitude over realistic ceilings; their
2727 // job is to bound a malicious / corrupt stream's allocation
2728 // budget, not to limit legitimate use.
2729 let count = count_raw.min(SUBTITLE_MAX_RECTS);
2730 if count_raw > SUBTITLE_MAX_RECTS {
2731 tracing::warn!(
2732 cap = SUBTITLE_MAX_RECTS,
2733 requested = count_raw,
2734 "mediadecode-ffmpeg: AVSubtitle.num_rects exceeds rect cap; truncating",
2735 );
2736 }
2737 let mut text_total_bytes: usize = 0;
2738 let mut bitmap_total_bytes: usize = 0;
2739
2740 let text_kind = AVSubtitleType::SUBTITLE_TEXT as i32;
2741 let ass_kind = AVSubtitleType::SUBTITLE_ASS as i32;
2742 let bitmap_kind = AVSubtitleType::SUBTITLE_BITMAP as i32;
2743 for i in 0..count {
2744 // SAFETY: rects_ptr is non-null (checked above) and points to
2745 // num_rects valid `*mut AVSubtitleRect` entries per FFmpeg's
2746 // contract; `i < count == num_rects`, so the offset is in-bounds.
2747 let rect_ptr = unsafe { *rects_ptr.add(i) };
2748 if rect_ptr.is_null() {
2749 continue;
2750 }
2751 // Read `type_` raw — avoid forming `&AVSubtitleRect` (which
2752 // would require type_ to be a valid AVSubtitleType variant).
2753 // SAFETY: `rect_ptr` is a live `*mut AVSubtitleRect`; `addr_of!`
2754 // computes the field address without forming a reference;
2755 // reading as `i32` matches the bindgen enum's `c_int` storage.
2756 let rect_type_raw = unsafe { read_unaligned(addr_of!((*rect_ptr).type_) as *const i32) };
2757 // Pre-read primitive fields we'll use later (no `&AVSubtitleRect`
2758 // ever formed).
2759 let rect_text_ptr = unsafe { (*rect_ptr).text };
2760 let rect_ass_ptr = unsafe { (*rect_ptr).ass };
2761 let rect_data0_ptr = unsafe { (*rect_ptr).data[0] };
2762 let rect_data1_ptr = unsafe { (*rect_ptr).data[1] };
2763 let rect_linesize0 = unsafe { (*rect_ptr).linesize[0] };
2764 let rect_w = unsafe { (*rect_ptr).w };
2765 let rect_h = unsafe { (*rect_ptr).h };
2766 let rect_x = unsafe { (*rect_ptr).x };
2767 let rect_y = unsafe { (*rect_ptr).y };
2768
2769 match rect_type_raw {
2770 x if x == text_kind && !rect_text_ptr.is_null() => {
2771 // SAFETY: `text` is documented as a 0-terminated UTF-8
2772 // string, owned by FFmpeg for the lifetime of the AVSubtitle.
2773 // We use a *bounded* NUL search instead of `CStr::from_ptr`
2774 // — the latter walks until it finds a NUL, which a valid-
2775 // but-pathological string makes unbounded, and a missing
2776 // NUL violates the `CStr::from_ptr` precondition outright.
2777 // `bounded_cstr_bytes` searches at most
2778 // `SUBTITLE_MAX_TEXT_BYTES_PER_RECT + 1` bytes; if no NUL
2779 // is found inside that window the rect is rejected.
2780 let bytes = unsafe { bounded_cstr_bytes(rect_text_ptr, SUBTITLE_MAX_TEXT_BYTES_PER_RECT) }
2781 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)))?;
2782 // The cap is now enforced inside `bounded_cstr_bytes` (no
2783 // NUL within `cap + 1` ⇒ rejection); a redundant length
2784 // check is unnecessary but kept as documentation.
2785 if bytes.len() > SUBTITLE_MAX_TEXT_BYTES_PER_RECT {
2786 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)));
2787 }
2788 let separator = if text_chunks.is_empty() { 0 } else { 1 };
2789 let projected = text_total_bytes
2790 .saturating_add(bytes.len())
2791 .saturating_add(separator);
2792 if projected > SUBTITLE_MAX_TEXT_TOTAL_BYTES {
2793 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)));
2794 }
2795 if separator == 1 {
2796 text_chunks.push(b'\n');
2797 }
2798 text_chunks.extend_from_slice(bytes);
2799 text_total_bytes = projected;
2800 }
2801 x if x == ass_kind && !rect_ass_ptr.is_null() => {
2802 // SAFETY: `ass` is documented as 0-terminated UTF-8.
2803 // Same bounded-scan rationale as the TEXT branch above.
2804 let bytes = unsafe { bounded_cstr_bytes(rect_ass_ptr, SUBTITLE_MAX_TEXT_BYTES_PER_RECT) }
2805 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)))?;
2806 if bytes.len() > SUBTITLE_MAX_TEXT_BYTES_PER_RECT {
2807 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)));
2808 }
2809 let separator = if text_chunks.is_empty() { 0 } else { 1 };
2810 let projected = text_total_bytes
2811 .saturating_add(bytes.len())
2812 .saturating_add(separator);
2813 if projected > SUBTITLE_MAX_TEXT_TOTAL_BYTES {
2814 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)));
2815 }
2816 if separator == 1 {
2817 text_chunks.push(b'\n');
2818 }
2819 text_chunks.extend_from_slice(bytes);
2820 text_total_bytes = projected;
2821 }
2822 x if x == bitmap_kind => {
2823 // Bitmap region. data[0] = paletted indices, data[1] = RGBA
2824 // palette (256 entries × 4 bytes = 1024 bytes). Both are
2825 // owned by FFmpeg and not refcounted; copy into fresh buffers.
2826 let w = rect_w.max(0) as u32;
2827 let h = rect_h.max(0) as u32;
2828 let stride = rect_linesize0.max(0) as u32;
2829 if rect_data0_ptr.is_null() || stride == 0 || h == 0 {
2830 continue;
2831 }
2832 // `checked_mul` so a corrupt rect can't drive
2833 // `from_raw_parts` to an address-space-spanning length (UB
2834 // even before any deref).
2835 let data_len = (stride as usize)
2836 .checked_mul(h as usize)
2837 .ok_or(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)))?;
2838 // Per-rect bitmap byte cap (defends against a single
2839 // attacker rect larger than realistic DVB / PGS subtitles
2840 // by a wide margin).
2841 if data_len > SUBTITLE_MAX_BITMAP_BYTES_PER_RECT {
2842 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)));
2843 }
2844 let projected_total = bitmap_total_bytes.saturating_add(data_len);
2845 if projected_total > SUBTITLE_MAX_BITMAP_TOTAL_BYTES {
2846 return Err(ConvertError::InvalidPlaneLayout(InvalidPlaneLayout::new(0)));
2847 }
2848 // SAFETY: data[0] is valid for `linesize[0] * h` bytes per
2849 // FFmpeg's contract; the multiplication is checked above.
2850 let data_slice = unsafe { core::slice::from_raw_parts(rect_data0_ptr, data_len) };
2851 // **A rect is copied on both lanes.** `AVSubtitleRect` has no
2852 // `buf[]`: its `data[]` are plain `av_malloc` allocations owned
2853 // by the `AVSubtitle`, which `avsubtitle_free` releases when
2854 // this call returns. There is no refcount to take, so the view
2855 // lane has nothing to view and says so.
2856 let data_buf = C::from_bytes(data_slice)
2857 .ok_or(ConvertError::CarrierAllocFailed(CarrierAllocFailed::new(0)))?;
2858 let palette_len = 256 * 4;
2859 let palette_buf = if rect_data1_ptr.is_null() {
2860 C::empty()
2861 } else {
2862 // SAFETY: palette buffer is 256*4 bytes per FFmpeg's contract.
2863 let p = unsafe { core::slice::from_raw_parts(rect_data1_ptr, palette_len) };
2864 C::from_bytes(p).ok_or(ConvertError::CarrierAllocFailed(CarrierAllocFailed::new(1)))?
2865 };
2866 bitmap_regions.push(mediadecode::subtitle::BitmapRegion::new(
2867 rect_x.max(0) as u32,
2868 rect_y.max(0) as u32,
2869 w,
2870 h,
2871 stride,
2872 data_buf,
2873 palette_buf,
2874 ));
2875 bitmap_total_bytes = projected_total;
2876 }
2877 _ => {}
2878 }
2879 }
2880
2881 let payload = if !text_chunks.is_empty() {
2882 SubtitlePayload::Text(SubtitleText::new(
2883 C::from_bytes(&text_chunks)
2884 .ok_or(ConvertError::CarrierAllocFailed(CarrierAllocFailed::new(0)))?,
2885 None,
2886 ))
2887 } else if !bitmap_regions.is_empty() {
2888 SubtitlePayload::Bitmap(SubtitleBitmap::new(bitmap_regions))
2889 } else {
2890 // No rects (or only `None`-typed) — empty text payload.
2891 SubtitlePayload::Text(SubtitleText::new(C::empty(), None))
2892 };
2893
2894 let sub_pts = unsafe { (*av_subtitle).pts };
2895 let pts = if sub_pts != AV_NOPTS_VALUE {
2896 Some(Timestamp::new(sub_pts, time_base))
2897 } else {
2898 None
2899 };
2900
2901 let extra = SubtitleFrameExtra::new(unsafe { (*av_subtitle).start_display_time }, unsafe {
2902 (*av_subtitle).end_display_time
2903 });
2904
2905 Ok(SubtitleFrame::new(payload, extra).with_pts(pts))
2906}
2907
2908fn map_picture_type_raw(raw: i32) -> PictureType {
2909 match raw {
2910 x if x == AVPictureType::AV_PICTURE_TYPE_I as i32 => PictureType::I,
2911 x if x == AVPictureType::AV_PICTURE_TYPE_P as i32 => PictureType::P,
2912 x if x == AVPictureType::AV_PICTURE_TYPE_B as i32 => PictureType::B,
2913 x if x == AVPictureType::AV_PICTURE_TYPE_S as i32 => PictureType::S,
2914 x if x == AVPictureType::AV_PICTURE_TYPE_SI as i32 => PictureType::Si,
2915 x if x == AVPictureType::AV_PICTURE_TYPE_SP as i32 => PictureType::Sp,
2916 x if x == AVPictureType::AV_PICTURE_TYPE_BI as i32 => PictureType::Bi,
2917 _ => PictureType::Unspecified,
2918 }
2919}
2920
2921#[cfg(test)]
2922mod tests;
2923
2924/// [`av_frame_to_video_frame_as`] on the **view** lane.
2925///
2926/// # Safety
2927///
2928/// As the crate-private worker: a live source for the duration of the
2929/// call, and — on this lane — no handle capable of mutating its buffers
2930/// may outlive the returned carriers.
2931pub unsafe fn av_frame_to_video_frame(
2932 av_frame: *const AVFrame,
2933 time_base: Timebase,
2934 limits: FrameLimits,
2935) -> Result<VideoFrame<mediadecode::PixelFormat, VideoFrameExtra, crate::FfmpegBuffer>, ConvertError>
2936{
2937 // SAFETY: forwarded verbatim; the caller's obligations are the
2938 // worker's.
2939 unsafe { av_frame_to_video_frame_as::<crate::View>(av_frame, time_base, limits) }
2940}
2941
2942/// [`av_frame_to_video_frame`] on the **owned** lane, which copies every byte it
2943/// reads and therefore has no aliasing obligation.
2944///
2945/// # Safety
2946///
2947/// The source must be live for the duration of the call.
2948pub unsafe fn av_frame_to_owned_video_frame(
2949 av_frame: *const AVFrame,
2950 time_base: Timebase,
2951 limits: FrameLimits,
2952) -> Result<VideoFrame<mediadecode::PixelFormat, VideoFrameExtra, FfmpegBytes>, ConvertError> {
2953 // SAFETY: forwarded verbatim.
2954 unsafe { av_frame_to_video_frame_as::<crate::Owned>(av_frame, time_base, limits) }
2955}
2956
2957/// [`av_frame_to_image_frame_as`] on the **view** lane.
2958///
2959/// # Safety
2960///
2961/// As the crate-private worker: a live source for the duration of the
2962/// call, and — on this lane — no handle capable of mutating its buffers
2963/// may outlive the returned carriers.
2964pub unsafe fn av_frame_to_image_frame(
2965 av_frame: *const AVFrame,
2966 limits: FrameLimits,
2967) -> Result<ImageFrame<mediadecode::PixelFormat, ImageFrameExtra, crate::FfmpegBuffer>, ConvertError>
2968{
2969 // SAFETY: forwarded verbatim; the caller's obligations are the
2970 // worker's.
2971 unsafe { av_frame_to_image_frame_as::<crate::View>(av_frame, limits) }
2972}
2973
2974/// [`av_frame_to_image_frame`] on the **owned** lane, which copies every byte it
2975/// reads and therefore has no aliasing obligation.
2976///
2977/// # Safety
2978///
2979/// The source must be live for the duration of the call.
2980pub unsafe fn av_frame_to_owned_image_frame(
2981 av_frame: *const AVFrame,
2982 limits: FrameLimits,
2983) -> Result<ImageFrame<mediadecode::PixelFormat, ImageFrameExtra, FfmpegBytes>, ConvertError> {
2984 // SAFETY: forwarded verbatim.
2985 unsafe { av_frame_to_image_frame_as::<crate::Owned>(av_frame, limits) }
2986}
2987
2988/// [`av_frame_to_audio_frame_as`] on the **view** lane.
2989///
2990/// # Safety
2991///
2992/// As the crate-private worker: a live source for the duration of the
2993/// call, and — on this lane — no handle capable of mutating its buffers
2994/// may outlive the returned carriers.
2995pub unsafe fn av_frame_to_audio_frame(
2996 av_frame: *const AVFrame,
2997 time_base: Timebase,
2998 limits: FrameLimits,
2999) -> Result<
3000 AudioFrame<SampleFormat, ChannelLayoutDescription, AudioFrameExtra, crate::FfmpegBuffer>,
3001 ConvertError,
3002> {
3003 // SAFETY: forwarded verbatim; the caller's obligations are the
3004 // worker's.
3005 unsafe { av_frame_to_audio_frame_as::<crate::View>(av_frame, time_base, limits) }
3006}
3007
3008/// [`av_frame_to_audio_frame`] on the **owned** lane, which copies every byte it
3009/// reads and therefore has no aliasing obligation.
3010///
3011/// # Safety
3012///
3013/// The source must be live for the duration of the call.
3014pub unsafe fn av_frame_to_owned_audio_frame(
3015 av_frame: *const AVFrame,
3016 time_base: Timebase,
3017 limits: FrameLimits,
3018) -> Result<
3019 AudioFrame<SampleFormat, ChannelLayoutDescription, AudioFrameExtra, FfmpegBytes>,
3020 ConvertError,
3021> {
3022 // SAFETY: forwarded verbatim.
3023 unsafe { av_frame_to_audio_frame_as::<crate::Owned>(av_frame, time_base, limits) }
3024}
3025
3026/// [`av_subtitle_to_subtitle_frame_as`] on the **view** lane.
3027///
3028/// # Safety
3029///
3030/// As the crate-private worker: a live source for the duration of the
3031/// call, and — on this lane — no handle capable of mutating its buffers
3032/// may outlive the returned carriers.
3033pub unsafe fn av_subtitle_to_subtitle_frame(
3034 av_subtitle: *const ffmpeg_next::ffi::AVSubtitle,
3035 time_base: Timebase,
3036) -> Result<SubtitleFrame<SubtitleFrameExtra, crate::FfmpegBuffer>, ConvertError> {
3037 // SAFETY: forwarded verbatim; the caller's obligations are the
3038 // worker's.
3039 unsafe { av_subtitle_to_subtitle_frame_as::<crate::View>(av_subtitle, time_base) }
3040}
3041
3042/// [`av_subtitle_to_subtitle_frame`] on the **owned** lane, which copies every byte it
3043/// reads and therefore has no aliasing obligation.
3044///
3045/// # Safety
3046///
3047/// The source must be live for the duration of the call.
3048pub unsafe fn av_subtitle_to_owned_subtitle_frame(
3049 av_subtitle: *const ffmpeg_next::ffi::AVSubtitle,
3050 time_base: Timebase,
3051) -> Result<SubtitleFrame<SubtitleFrameExtra, FfmpegBytes>, ConvertError> {
3052 // SAFETY: forwarded verbatim.
3053 unsafe { av_subtitle_to_subtitle_frame_as::<crate::Owned>(av_subtitle, time_base) }
3054}