1use crate::capabilities::{NativeEncoderClass, encoder_class};
4use alpha2_ffmpeg_bridge::{DecodedFrame, DisplayRotation, PackedScaler};
5use std::ffi::{CStr, CString};
6
7use alpha2_media::{
8 ChromaLocation, ColorMatrix, ColorMetadata, ColorPrimaries, ColorRange, Container, DecodeError,
9 DecodedVideoFrame, EncodeError, Orientation, PixelFormat, Plane, Rect, Rotation,
10 SampleAspectRatio, TransferFunction, YuvFormat,
11};
12use alpha2_time::{MediaTime, TICKS_PER_SECOND};
13use rsmpeg::avcodec::AVCodec;
14use rsmpeg::avutil::{AVDictionary, AVFrame, AVRational, av_rescale_q, ra};
15use rsmpeg::ffi;
16
17#[allow(clippy::too_many_lines)]
18pub(crate) fn convert_video_frame(
19 frame: &DecodedFrame,
20 alpha: Option<crate::alpha::FrameAlpha<'_>>,
21 codec: ffi::AVCodecID,
22 time_base: AVRational,
23 color: ColorMetadata,
24 scaler: &mut FrameScaler,
25) -> Result<DecodedVideoFrame, DecodeError> {
26 let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
27 let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
28 let pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
29 frame.pts
30 } else {
31 frame.best_effort_timestamp
32 };
33 let visible_rect = Rect {
34 x: u32::try_from(frame.crop_left).unwrap_or(0),
35 y: u32::try_from(frame.crop_top).unwrap_or(0),
36 width: width.saturating_sub(
37 u32::try_from(frame.crop_left.saturating_add(frame.crop_right)).unwrap_or(0),
38 ),
39 height: height.saturating_sub(
40 u32::try_from(frame.crop_top.saturating_add(frame.crop_bottom)).unwrap_or(0),
41 ),
42 };
43 check_frame_size(width, height)?;
44 if let Some(planes) = frame.yuv_planes().map_err(adapter_error)? {
47 let layout = planes.layout;
48 let alpha = alpha
49 .map(|alpha| {
50 alpha.plane(
51 (planes.width, planes.height),
52 layout.bit_depth,
53 layout.msb_aligned,
54 )
55 })
56 .transpose()?;
57 return Ok(DecodedVideoFrame {
58 pts: timestamp(pts, time_base).ok_or(DecodeError::OutOfRange)?,
59 dts: None,
60 duration: timestamp(frame.duration, time_base),
61 visible_rect,
62 sample_aspect_ratio: declared_sar(frame.sample_aspect_ratio).unwrap_or_default(),
63 orientation: Orientation::UPRIGHT,
64 pixel_format: PixelFormat::Yuv(YuvFormat {
65 chroma_shift_x: layout.chroma_shift_x,
66 chroma_shift_y: layout.chroma_shift_y,
67 bit_depth: layout.bit_depth,
68 interleaved_chroma: layout.interleaved_chroma,
69 msb_aligned: layout.msb_aligned,
70 alpha: alpha.is_some(),
71 }),
72 chroma_location: decoded_chroma_location(codec, frame.chroma_location),
73 color: Some(color),
74 planes: planes
75 .planes
76 .into_iter()
77 .map(|plane| Plane {
78 bytes: plane.bytes,
79 stride: plane.stride,
80 width: plane.width,
81 height: plane.height,
82 })
83 .chain(alpha)
84 .collect(),
85 });
86 }
87 if alpha.is_some() {
88 return Err(DecodeError::Unsupported(format!(
89 "an alpha stream beside {} colour is not decoded",
90 alpha2_ffmpeg_bridge::pixel_format_name(frame.format)
91 .unwrap_or_else(|| "unknown".to_owned())
92 )));
93 }
94 let (pixel_format, planes, color) = if converts_like_rgba8(color) {
95 (
96 PixelFormat::Rgba8,
97 vec![rgba8_plane(frame, color, scaler)?],
98 color,
99 )
100 } else {
101 full_resolution_planes(frame, color, scaler)?
102 };
103 Ok(DecodedVideoFrame {
104 pts: timestamp(pts, time_base).ok_or(DecodeError::OutOfRange)?,
105 dts: None,
106 duration: timestamp(frame.duration, time_base),
107 visible_rect,
108 sample_aspect_ratio: declared_sar(frame.sample_aspect_ratio).unwrap_or_default(),
109 orientation: Orientation::UPRIGHT,
110 pixel_format,
111 chroma_location: ChromaLocation::Unspecified,
113 color: Some(color),
114 planes,
115 })
116}
117
118fn converts_like_rgba8(color: ColorMetadata) -> bool {
122 !color.is_hdr() && color.primaries == ColorPrimaries::Bt709
123}
124
125fn rgba8_plane(
127 frame: &AVFrame,
128 color: ColorMetadata,
129 scaler: &mut FrameScaler,
130) -> Result<Plane, DecodeError> {
131 let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
132 let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
133 let active = scaler.for_frame(frame, ffi::AV_PIX_FMT_RGBA)?;
134 configure_yuv_to_rgba(active, color).map_err(adapter_error)?;
135 let bytes = active.convert(frame).map_err(adapter_error)?;
136 if bytes.len() != packed_len(width, height, 4)? {
137 return Err(DecodeError::OutOfRange);
138 }
139 Ok(Plane {
140 bytes: bytes.into(),
141 stride: width.saturating_mul(4),
142 width,
143 height,
144 })
145}
146
147fn full_resolution_planes(
150 frame: &AVFrame,
151 color: ColorMetadata,
152 scaler: &mut FrameScaler,
153) -> Result<(PixelFormat, Vec<Plane>, ColorMetadata), DecodeError> {
154 let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
155 let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
156 let profile = alpha2_ffmpeg_bridge::sample_profile(frame.format)
157 .ok_or_else(|| DecodeError::Unsupported("unsupported FFmpeg pixel format".into()))?;
158 let depth = match profile.bit_depth {
159 0..=8 => 8,
160 9..=10 => 10,
161 11..=12 => 12,
162 _ => 16,
163 };
164 let target = planar_444_format(profile.is_rgb, profile.has_alpha, depth);
165 let active = scaler.for_frame(frame, target)?;
166 if !profile.is_rgb {
167 let coefficients = sws_coefficients(color.matrix);
169 let full = color.range == ColorRange::Full;
170 active
171 .configure_colorspace(coefficients, full, coefficients, full)
172 .map_err(adapter_error)?;
173 }
174 let plane_count = if profile.has_alpha { 4 } else { 3 };
175 let sample_bytes = if depth > 8 { 2 } else { 1 };
176 let plane_len = packed_len(width, height, sample_bytes)?;
177 let bytes = active.convert(frame).map_err(adapter_error)?;
178 if bytes.len() != plane_len * plane_count {
179 return Err(DecodeError::OutOfRange);
180 }
181 let bytes = bytes::Bytes::from(bytes);
182 let stride = width.saturating_mul(u32::try_from(sample_bytes).unwrap_or(2));
183 let plane = |index: usize| Plane {
184 bytes: bytes.slice(index * plane_len..(index + 1) * plane_len),
185 stride,
186 width,
187 height,
188 };
189 let order: &[usize] = if profile.is_rgb {
191 &[2, 0, 1]
192 } else {
193 &[0, 1, 2]
194 };
195 let mut planes = order.iter().map(|&index| plane(index)).collect::<Vec<_>>();
196 if profile.has_alpha {
197 planes.push(plane(3));
198 }
199 let format = YuvFormat::planar(0, 0, depth);
200 let format = if profile.has_alpha {
201 format.with_alpha()
202 } else {
203 format
204 };
205 let color = if profile.is_rgb {
206 ColorMetadata {
207 matrix: ColorMatrix::Rgb,
208 range: ColorRange::Full,
209 ..color
210 }
211 } else {
212 color
213 };
214 Ok((PixelFormat::Yuv(format), planes, color))
215}
216
217const fn planar_444_format(rgb: bool, alpha: bool, depth: u8) -> ffi::AVPixelFormat {
220 match (rgb, alpha, depth) {
221 (true, false, 8) => ffi::AV_PIX_FMT_GBRP,
222 (true, true, 8) => ffi::AV_PIX_FMT_GBRAP,
223 (true, false, 10) => ffi::AV_PIX_FMT_GBRP10LE,
224 (true, true, 10) => ffi::AV_PIX_FMT_GBRAP10LE,
225 (true, false, 12) => ffi::AV_PIX_FMT_GBRP12LE,
226 (true, true, 12) => ffi::AV_PIX_FMT_GBRAP12LE,
227 (true, false, _) => ffi::AV_PIX_FMT_GBRP16LE,
228 (true, true, _) => ffi::AV_PIX_FMT_GBRAP16LE,
229 (false, false, 8) => ffi::AV_PIX_FMT_YUV444P,
230 (false, true, 8) => ffi::AV_PIX_FMT_YUVA444P,
231 (false, false, 10) => ffi::AV_PIX_FMT_YUV444P10LE,
232 (false, true, 10) => ffi::AV_PIX_FMT_YUVA444P10LE,
233 (false, false, 12) => ffi::AV_PIX_FMT_YUV444P12LE,
234 (false, true, 12) => ffi::AV_PIX_FMT_YUVA444P12LE,
235 (false, false, _) => ffi::AV_PIX_FMT_YUV444P16LE,
236 (false, true, _) => ffi::AV_PIX_FMT_YUVA444P16LE,
237 }
238}
239
240#[derive(Default)]
245pub(crate) struct FrameScaler {
246 context: Option<(ScalerShape, PackedScaler)>,
247 made: u64,
248}
249
250#[derive(Clone, Copy, Debug, Eq, PartialEq)]
251struct ScalerShape {
252 width: i32,
253 height: i32,
254 source: ffi::AVPixelFormat,
255 target: ffi::AVPixelFormat,
256}
257
258impl FrameScaler {
259 fn for_frame(
261 &mut self,
262 frame: &AVFrame,
263 target: ffi::AVPixelFormat,
264 ) -> Result<&mut PackedScaler, DecodeError> {
265 let shape = ScalerShape {
266 width: frame.width,
267 height: frame.height,
268 source: frame.format,
269 target,
270 };
271 if self
272 .context
273 .as_ref()
274 .is_none_or(|(made_for, _)| *made_for != shape)
275 {
276 self.context = None;
277 let context = PackedScaler::new(frame.width, frame.height, frame.format, target)
278 .map_err(|_| DecodeError::Unsupported("unsupported FFmpeg pixel format".into()))?;
279 self.made += 1;
280 self.context = Some((shape, context));
281 }
282 self.context
283 .as_mut()
284 .map(|(_, context)| context)
285 .ok_or_else(|| DecodeError::Unsupported("unsupported FFmpeg pixel format".into()))
286 }
287
288 #[cfg(test)]
289 pub(crate) const fn made(&self) -> u64 {
290 self.made
291 }
292
293 #[cfg(test)]
294 pub(crate) const fn is_empty(&self) -> bool {
295 self.context.is_none()
296 }
297}
298
299fn packed_len(width: u32, height: u32, sample_bytes: usize) -> Result<usize, DecodeError> {
300 usize::try_from(width)
301 .ok()
302 .and_then(|width| {
303 usize::try_from(height)
304 .ok()
305 .and_then(|height| width.checked_mul(height))
306 })
307 .and_then(|pixels| pixels.checked_mul(sample_bytes))
308 .ok_or(DecodeError::OutOfRange)
309}
310
311pub(crate) fn decoded_chroma_location(
317 codec: ffi::AVCodecID,
318 location: ffi::AVChromaLocation,
319) -> ChromaLocation {
320 if codec == ffi::AV_CODEC_ID_H264 && location == ffi::AVCHROMA_LOC_UNSPECIFIED {
321 ChromaLocation::Left
322 } else {
323 chroma_location(location)
324 }
325}
326
327pub(crate) fn chroma_location(location: ffi::AVChromaLocation) -> ChromaLocation {
328 match location {
329 ffi::AVCHROMA_LOC_LEFT => ChromaLocation::Left,
330 ffi::AVCHROMA_LOC_CENTER => ChromaLocation::Center,
331 ffi::AVCHROMA_LOC_TOPLEFT => ChromaLocation::TopLeft,
332 _ => ChromaLocation::Unspecified,
333 }
334}
335
336pub(crate) fn configure_rgba_to_yuv(
338 scaler: &mut PackedScaler,
339 color: ColorMetadata,
340) -> Result<(), alpha2_ffmpeg_bridge::BridgeError> {
341 scaler.configure_colorspace(
342 i32::try_from(ffi::SWS_CS_ITU709).expect("color coefficient fits i32"),
343 true,
344 sws_coefficients(color.matrix),
345 color.range == ColorRange::Full,
346 )
347}
348
349pub(crate) fn configure_yuv_to_rgba(
351 scaler: &mut PackedScaler,
352 color: ColorMetadata,
353) -> Result<(), alpha2_ffmpeg_bridge::BridgeError> {
354 scaler.configure_colorspace(
355 sws_coefficients(color.matrix),
356 color.range == ColorRange::Full,
357 i32::try_from(ffi::SWS_CS_ITU709).expect("color coefficient fits i32"),
358 true,
359 )
360}
361
362pub(crate) fn sws_coefficients(matrix: ColorMatrix) -> i32 {
363 let value = match matrix {
364 ColorMatrix::Bt601 => ffi::SWS_CS_ITU601,
365 ColorMatrix::Bt709 | ColorMatrix::Rgb => ffi::SWS_CS_ITU709,
366 ColorMatrix::Bt2020Ncl => ffi::SWS_CS_BT2020,
367 };
368 i32::try_from(value).expect("color coefficient fits i32")
369}
370
371pub(crate) fn tick_base() -> AVRational {
373 ra(
374 1,
375 i32::try_from(TICKS_PER_SECOND).expect("tick rate fits i32"),
376 )
377}
378
379pub(crate) fn direct_yuv420p_frame(
384 frame: &DecodedVideoFrame,
385 width: i32,
386 height: i32,
387) -> Result<Option<AVFrame>, EncodeError> {
388 if frame.pixel_format != PixelFormat::Yuv(YuvFormat::I420) {
389 return Ok(None);
390 }
391 if frame.planes.len() != 3
392 || frame.visible_rect.x != 0
393 || frame.visible_rect.y != 0
394 || frame.planes[0].width != u32::try_from(width).unwrap_or(0)
395 || frame.planes[0].height != u32::try_from(height).unwrap_or(0)
396 {
397 return Err(EncodeError::Adapter(
398 "direct YUV encoder input must contain one uncropped coded frame".into(),
399 ));
400 }
401 alpha2_ffmpeg_bridge::yuv420p_frame(
402 &frame.planes[0].bytes,
403 frame.planes[0].stride,
404 &frame.planes[1].bytes,
405 frame.planes[1].stride,
406 &frame.planes[2].bytes,
407 frame.planes[2].stride,
408 width,
409 height,
410 )
411 .map(Some)
412 .map_err(encode_adapter_error)
413}
414
415pub(crate) struct Yuv420pConverter {
421 output: ColorMetadata,
422 scaler: Option<(ffi::AVPixelFormat, u32, u32, PackedScaler)>,
423}
424
425impl Yuv420pConverter {
426 pub(crate) const fn new(output: ColorMetadata) -> Self {
428 Self {
429 output,
430 scaler: None,
431 }
432 }
433
434 pub(crate) fn convert(
439 &mut self,
440 frame: &DecodedVideoFrame,
441 width: i32,
442 height: i32,
443 ) -> Result<Option<AVFrame>, EncodeError> {
444 let PixelFormat::Yuv(format) = frame.pixel_format else {
445 return Ok(None);
446 };
447 let rgb = frame
448 .color
449 .is_some_and(|color| color.matrix == ColorMatrix::Rgb);
450 if format == YuvFormat::I420 && !rgb {
451 return direct_yuv420p_frame(frame, width, height);
452 }
453 let (width, height) = (
454 u32::try_from(width).unwrap_or(0),
455 u32::try_from(height).unwrap_or(0),
456 );
457 let stored = if format.interleaved_chroma { 2 } else { 3 };
458 if frame.visible_rect.x != 0
459 || frame.visible_rect.y != 0
460 || frame.planes.len() < stored
461 || frame.planes[0].width != width
462 || frame.planes[0].height != height
463 {
464 return Err(EncodeError::Adapter(
465 "YUV encoder input must contain one uncropped frame of the encoder's size".into(),
466 ));
467 }
468 let (source_format, planes) = if rgb {
469 if format.chroma_shift_x != 0
470 || format.chroma_shift_y != 0
471 || format.interleaved_chroma
472 || format.msb_aligned
473 || !matches!(format.bit_depth, 8 | 10 | 12 | 16)
474 {
475 return Err(EncodeError::Adapter(format!(
476 "no FFmpeg pixel format stores red, green, and blue as {format:?}"
477 )));
478 }
479 let planes = [1, 2, 0]
481 .iter()
482 .map(|&index: &usize| (&frame.planes[index].bytes[..], frame.planes[index].stride))
483 .collect::<Vec<_>>();
484 (planar_444_format(true, false, format.bit_depth), planes)
485 } else {
486 let layout = alpha2_ffmpeg_bridge::YuvPlaneLayout {
487 chroma_shift_x: format.chroma_shift_x,
488 chroma_shift_y: format.chroma_shift_y,
489 bit_depth: format.bit_depth,
490 interleaved_chroma: format.interleaved_chroma,
491 msb_aligned: format.msb_aligned,
492 };
493 let source_format =
494 alpha2_ffmpeg_bridge::yuv_pixel_format(layout).ok_or_else(|| {
495 EncodeError::Adapter(format!("no FFmpeg pixel format stores {format:?}"))
496 })?;
497 let planes = frame.planes[..stored]
498 .iter()
499 .map(|plane| (&plane.bytes[..], plane.stride))
500 .collect::<Vec<_>>();
501 (source_format, planes)
502 };
503 let source = alpha2_ffmpeg_bridge::planar_frame(source_format, &planes, width, height)
504 .map_err(encode_adapter_error)?;
505 if self
506 .scaler
507 .as_ref()
508 .is_none_or(|(cached, w, h, _)| (*cached, *w, *h) != (source_format, width, height))
509 {
510 let (signed_width, signed_height) = (
511 i32::try_from(width).map_err(|_| EncodeError::Adapter("width overflow".into()))?,
512 i32::try_from(height)
513 .map_err(|_| EncodeError::Adapter("height overflow".into()))?,
514 );
515 let mut scaler = PackedScaler::new(
516 signed_width,
517 signed_height,
518 source_format,
519 ffi::AV_PIX_FMT_YUV420P,
520 )
521 .map_err(|_| EncodeError::Adapter("cannot create a YUV to YUV420P scaler".into()))?;
522 if rgb {
523 configure_rgba_to_yuv(&mut scaler, self.output).map_err(encode_adapter_error)?;
524 }
525 self.scaler = Some((source_format, width, height, scaler));
526 }
527 let Some((_, _, _, scaler)) = self.scaler.as_mut() else {
528 unreachable!("the scaler was just made");
529 };
530 let output = scaler
531 .convert_to_frame(&source)
532 .map_err(encode_adapter_error)?;
533 Ok(Some(output))
534 }
535}
536
537pub(crate) fn timestamp(value: i64, base: AVRational) -> Option<MediaTime> {
539 (value != ffi::AV_NOPTS_VALUE && base.den > 0)
540 .then(|| MediaTime::from_ticks(av_rescale_q(value, base, tick_base())))
541}
542
543pub(crate) fn declared_sar(value: AVRational) -> Option<SampleAspectRatio> {
546 SampleAspectRatio::new(
547 u64::try_from(value.num).ok()?,
548 u64::try_from(value.den).ok()?,
549 )
550}
551
552pub(crate) fn guess_sar(container: AVRational, pictures: AVRational) -> SampleAspectRatio {
555 declared_sar(container)
556 .or_else(|| declared_sar(pictures))
557 .unwrap_or_default()
558}
559
560pub(crate) fn stream_rotation(metadata: Option<rsmpeg::avutil::AVDictionaryRef<'_>>) -> Rotation {
562 let Some(metadata) = metadata else {
563 return Rotation::Deg0;
564 };
565 let Some(entry) = metadata.get(c"rotate", None, 0) else {
566 return Rotation::Deg0;
567 };
568 match entry
569 .value()
570 .to_string_lossy()
571 .parse::<i32>()
572 .unwrap_or(0)
573 .rem_euclid(360)
574 {
575 90 => Rotation::Deg90,
576 180 => Rotation::Deg180,
577 270 => Rotation::Deg270,
578 _ => Rotation::Deg0,
579 }
580}
581
582pub(crate) fn rotation_from_display(counter_clockwise: f64) -> Option<Rotation> {
586 let normalized = (-counter_clockwise).rem_euclid(360.0);
587 if !(0.5..359.5).contains(&normalized) {
588 Some(Rotation::Deg0)
589 } else if (normalized - 90.0).abs() < 0.5 {
590 Some(Rotation::Deg90)
591 } else if (normalized - 180.0).abs() < 0.5 {
592 Some(Rotation::Deg180)
593 } else if (normalized - 270.0).abs() < 0.5 {
594 Some(Rotation::Deg270)
595 } else {
596 None
597 }
598}
599
600pub(crate) fn orientation_from_display(display: DisplayRotation) -> Option<Orientation> {
605 if display.flipped {
606 rotation_from_display(-display.counter_clockwise_degrees).map(|rotation| Orientation {
607 rotation,
608 mirror: true,
609 })
610 } else {
611 rotation_from_display(display.counter_clockwise_degrees).map(Orientation::rotated)
612 }
613}
614
615pub(crate) fn display_of(orientation: Orientation) -> Option<DisplayRotation> {
618 if orientation == Orientation::default() {
619 return None;
620 }
621 let clockwise = match orientation.rotation {
622 Rotation::Deg0 => 0.0,
623 Rotation::Deg90 => 90.0,
624 Rotation::Deg180 => 180.0,
625 Rotation::Deg270 => 270.0,
626 };
627 Some(DisplayRotation {
628 counter_clockwise_degrees: if orientation.mirror {
629 clockwise
630 } else {
631 -clockwise
632 },
633 flipped: orientation.mirror,
634 })
635}
636
637const HVC1: u32 = u32::from_le_bytes(*b"hvc1");
639const HEV1: u32 = u32::from_le_bytes(*b"hev1");
641
642pub(crate) const fn muxer_name(container: Container) -> &'static CStr {
644 match container {
645 Container::Mp4 => c"mp4",
646 Container::Mov => c"mov",
647 Container::Mkv => c"matroska",
648 Container::Webm => c"webm",
649 }
650}
651
652pub(crate) fn muxer_header_options(container: Container) -> Option<AVDictionary> {
657 matches!(container, Container::Mkv | Container::Webm)
658 .then(|| AVDictionary::new(c"fflags", c"+bitexact", 0))
659}
660
661pub(crate) fn container_codec_tag(
668 container: Container,
669 codec_id: ffi::AVCodecID,
670 tag: u32,
671 copied: bool,
672) -> u32 {
673 if matches!(container, Container::Mkv | Container::Webm) {
674 0
675 } else if codec_id == ffi::AV_CODEC_ID_HEVC {
676 if tag == HVC1 || tag == HEV1 {
677 tag
678 } else {
679 HVC1
680 }
681 } else if copied {
682 0
683 } else {
684 tag
685 }
686}
687
688pub(crate) fn color_metadata(
689 parameters: &rsmpeg::avcodec::AVCodecParameters,
690) -> Option<ColorMetadata> {
691 map_color(
692 parameters.color_primaries,
693 parameters.color_trc,
694 parameters.color_space,
695 parameters.color_range,
696 )
697}
698
699pub(crate) fn frame_color_metadata(frame: &AVFrame) -> Option<ColorMetadata> {
700 map_color(
701 frame.color_primaries,
702 frame.color_trc,
703 frame.colorspace,
704 frame.color_range,
705 )
706}
707
708pub(crate) fn map_color(
713 primaries: ffi::AVColorPrimaries,
714 transfer: ffi::AVColorTransferCharacteristic,
715 matrix: ffi::AVColorSpace,
716 range: ffi::AVColorRange,
717) -> Option<ColorMetadata> {
718 let code = |value| u8::try_from(value).unwrap_or(u8::MAX);
719 let full_range = match range {
720 ffi::AVCOL_RANGE_UNSPECIFIED => None,
721 range => Some(range == ffi::AVCOL_RANGE_JPEG),
722 };
723 ColorMetadata::from_h273(code(primaries), code(transfer), code(matrix), full_range)
724}
725
726pub(crate) fn check_frame_size(width: u32, height: u32) -> Result<(), DecodeError> {
733 if alpha2_media::frame_size_supported(width, height) {
734 return Ok(());
735 }
736 Err(DecodeError::Unsupported(format!(
737 "a {width}x{height} frame is larger than {} pixels or {} on a side",
738 alpha2_media::MAX_FRAME_PIXELS,
739 alpha2_media::MAX_FRAME_DIMENSION
740 )))
741}
742
743pub(crate) fn video_decoder_options(threads: i64) -> AVDictionary {
746 let max_pixels = i64::try_from(alpha2_media::MAX_FRAME_PIXELS).unwrap_or(i64::MAX);
747 AVDictionary::new_int(c"threads", threads, 0)
748 .set(c"flags", c"+unaligned", 0)
749 .set_int(c"max_pixels", max_pixels, 0)
750}
751
752pub(crate) fn pixel_format(
754 layout: alpha2_media::PixelLayout,
755) -> Result<ffi::AVPixelFormat, EncodeError> {
756 pixel_format_named(layout.ffmpeg_name())
757}
758
759pub(crate) fn pixel_format_named(name: &str) -> Result<ffi::AVPixelFormat, EncodeError> {
760 Ok(match name {
761 "yuv420p" => ffi::AV_PIX_FMT_YUV420P,
762 "yuva420p" => ffi::AV_PIX_FMT_YUVA420P,
763 "yuv420p10le" => ffi::AV_PIX_FMT_YUV420P10LE,
764 "yuva420p10le" => ffi::AV_PIX_FMT_YUVA420P10LE,
765 "yuv422p" => ffi::AV_PIX_FMT_YUV422P,
766 "yuva422p" => ffi::AV_PIX_FMT_YUVA422P,
767 "yuv422p10le" => ffi::AV_PIX_FMT_YUV422P10LE,
768 "yuva422p10le" => ffi::AV_PIX_FMT_YUVA422P10LE,
769 "yuv444p" => ffi::AV_PIX_FMT_YUV444P,
770 "yuva444p" => ffi::AV_PIX_FMT_YUVA444P,
771 "yuv444p10le" => ffi::AV_PIX_FMT_YUV444P10LE,
772 "yuva444p10le" => ffi::AV_PIX_FMT_YUVA444P10LE,
773 "p010le" => ffi::AV_PIX_FMT_P010LE,
774 _ => {
775 return Err(EncodeError::Adapter(format!(
776 "pixel layout {name} has no FFmpeg pixel format"
777 )));
778 }
779 })
780}
781
782pub fn packed_frame(
788 width: u32,
789 height: u32,
790 layout: alpha2_media::PixelLayout,
791) -> Result<alpha2_ffmpeg_bridge::Yuv420pFrameBuffer, alpha2_ffmpeg_bridge::BridgeError> {
792 let (coded_width, coded_height) = (
793 i32::try_from(width)
794 .map_err(|_| alpha2_ffmpeg_bridge::BridgeError::InvalidInput("width"))?,
795 i32::try_from(height)
796 .map_err(|_| alpha2_ffmpeg_bridge::BridgeError::InvalidInput("height"))?,
797 );
798 let format = pixel_format(layout).map_err(|_| {
799 alpha2_ffmpeg_bridge::BridgeError::InvalidInput("pixel layout has no FFmpeg format")
800 })?;
801 alpha2_ffmpeg_bridge::Yuv420pFrameBuffer::with_format(coded_width, coded_height, format)
802}
803
804pub(crate) fn prores_options(layout: alpha2_media::PixelLayout) -> Vec<(&'static CStr, String)> {
805 let mut options = vec![
806 (
807 c"profile",
808 if layout.alpha { "4444" } else { "hq" }.to_owned(),
809 ),
810 (c"vendor", "apl0".to_owned()),
811 ];
812 if layout.alpha {
813 options.push((c"alpha_bits", "16".to_owned()));
814 }
815 options
816}
817
818pub(crate) fn video_encoder_options(
819 color: ColorMetadata,
820 codec: &AVCodec,
821 on_hardware: bool,
822 threads: i64,
823 width: u32,
824) -> AVDictionary {
825 let mut options = color_options(color);
826 if encoder_class(codec) == NativeEncoderClass::Hybrid {
829 options = options.set_int(c"hw_encoding", i64::from(on_hardware), 0);
830 }
831 if on_hardware {
832 return options;
833 }
834 let name = codec.name().to_string_lossy();
835 for (key, value) in software_encoder_profile(&name, width, threads) {
836 options = set_encoder_option(options, key, &value);
837 }
838 options.set_int(c"threads", threads, 0)
839}
840
841fn software_encoder_profile(name: &str, width: u32, threads: i64) -> Vec<(&'static CStr, String)> {
849 match name {
850 "libvpx-vp9" => vec![
851 (c"deadline", "good".into()),
852 (c"cpu-used", "4".into()),
853 (c"row-mt", "1".into()),
854 (c"tile-columns", vp9_tile_columns_log2(width).to_string()),
855 (c"lag-in-frames", "25".into()),
856 (c"auto-alt-ref", "1".into()),
857 ],
858 "libsvtav1" => vec![
859 (c"preset", "8".into()),
860 (
861 c"svtav1-params",
862 format!(
863 "lp={}",
864 if deterministic_encode() {
865 1
866 } else {
867 svt_av1_parallelism(threads)
868 }
869 ),
870 ),
871 ],
872 _ => Vec::new(),
873 }
874}
875
876pub(crate) fn deterministic_encode() -> bool {
879 std::env::var_os("ALPHA2_DETERMINISTIC_ENCODE").is_some_and(|value| value == "1")
880}
881
882pub(crate) fn vp9_tile_columns_log2(width: u32) -> u32 {
884 (width / 256).max(1).ilog2().min(6)
885}
886
887pub(crate) fn svt_av1_parallelism(threads: i64) -> u32 {
890 match threads {
891 ..=1 => 1,
892 2 => 2,
893 3..=5 => 3,
894 6..=11 => 4,
895 12..=23 => 5,
896 _ => 6,
897 }
898}
899
900pub(crate) fn set_encoder_option(options: AVDictionary, key: &CStr, value: &str) -> AVDictionary {
903 let value = CString::new(value).unwrap_or_default();
904 if key == c"svtav1-params" && options.get(key, None, 0).is_some() {
905 let appended = CString::new(format!(":{}", value.to_string_lossy())).unwrap_or_default();
906 options.set(key, &appended, ffi::AV_DICT_APPEND)
907 } else {
908 options.set(key, &value, 0)
909 }
910}
911
912#[must_use]
917pub fn codec_thread_budget() -> i64 {
918 i64::try_from(configured_codec_thread_budget().min(16)).unwrap_or(1)
919}
920
921pub fn configured_codec_thread_override() -> Result<Option<usize>, String> {
927 codec_thread_override(std::env::var_os("ALPHA2_FFMPEG_THREADS").as_deref())
928}
929
930pub fn codec_thread_override(setting: Option<&std::ffi::OsStr>) -> Result<Option<usize>, String> {
935 let Some(setting) = setting else {
936 return Ok(None);
937 };
938 setting
939 .to_str()
940 .and_then(|value| value.parse::<usize>().ok())
941 .filter(|value| *value > 0)
942 .map(|value| Some(value.min(64)))
943 .ok_or_else(|| setting.to_string_lossy().into_owned())
944}
945
946fn configured_codec_thread_budget() -> usize {
947 configured_codec_thread_override()
948 .ok()
949 .flatten()
950 .unwrap_or_else(|| {
951 codec_thread_budget_for(
952 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
953 )
954 })
955 .clamp(1, 64)
956}
957
958pub(crate) fn codec_thread_budget_for(hardware_threads: usize) -> usize {
961 hardware_threads
962 .saturating_sub(codec_thread_reserve(hardware_threads))
963 .max(1)
964}
965
966pub(crate) const fn codec_thread_reserve(hardware_threads: usize) -> usize {
972 match hardware_threads {
973 16.. => 2,
974 6..=15 => 1,
975 _ => 0,
976 }
977}
978
979#[derive(Clone, Copy, Debug, PartialEq, Eq)]
981pub struct CodecThreadRequest {
982 pub decode_concurrency: usize,
984 pub hardware_decode: bool,
986 pub source_frame_pixels: u64,
988 pub software_video_encoder: bool,
990 pub encoder_fixed_threads: Option<usize>,
994}
995
996const DECODE_PIXELS_PER_THREAD: u64 = 2_000_000;
998const MIN_SOFTWARE_DECODER_THREADS: usize = 2;
1000const MAX_SOFTWARE_DECODER_THREADS: usize = 6;
1003const ENCODER_THREAD_FLOOR: usize = 4;
1006
1007const fn encoder_thread_floor(total_threads: usize) -> usize {
1010 let third = total_threads / 3;
1011 if third < ENCODER_THREAD_FLOOR {
1012 if third == 0 { 1 } else { third }
1013 } else {
1014 ENCODER_THREAD_FLOOR
1015 }
1016}
1017pub const HARDWARE_DECODER_THREADS: usize = 2;
1025
1026#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1029pub struct CodecThreadAllocation {
1030 pub total_threads: usize,
1032 pub decode_concurrency: usize,
1034 pub decoder_threads: i64,
1036 pub hardware_decoder_threads: i64,
1038 pub encoder_threads: i64,
1040 pub allocated_threads: usize,
1042}
1043
1044#[must_use]
1057pub fn codec_thread_allocation(request: CodecThreadRequest) -> CodecThreadAllocation {
1058 codec_thread_allocation_within(request, configured_codec_thread_budget())
1059}
1060
1061#[must_use]
1064pub fn decode_concurrency_ceiling(software_video_encoder: bool) -> usize {
1065 decode_concurrency_ceiling_for(configured_codec_thread_budget(), software_video_encoder)
1066}
1067
1068#[must_use]
1070pub fn decode_concurrency_ceiling_for(configured: usize, software_video_encoder: bool) -> usize {
1071 configured
1072 .saturating_sub(usize::from(software_video_encoder))
1073 .max(1)
1074}
1075
1076pub(crate) fn codec_thread_allocation_within(
1078 request: CodecThreadRequest,
1079 configured: usize,
1080) -> CodecThreadAllocation {
1081 let encoder_slots = usize::from(request.software_video_encoder);
1082 let decode_concurrency = request
1083 .decode_concurrency
1084 .max(1)
1085 .min(decode_concurrency_ceiling_for(
1086 configured,
1087 request.software_video_encoder,
1088 ));
1089 let total_threads = configured.max(decode_concurrency.saturating_add(encoder_slots));
1090 let fixed_encoder = request
1093 .encoder_fixed_threads
1094 .filter(|_| request.software_video_encoder)
1095 .map(|threads| threads.max(1));
1096 let encoder_floor = match fixed_encoder {
1097 Some(threads) => threads.min(total_threads.saturating_sub(decode_concurrency).max(1)),
1098 None if request.software_video_encoder => encoder_thread_floor(total_threads)
1099 .min(total_threads.saturating_sub(decode_concurrency).max(1)),
1100 None => 0,
1101 };
1102 let decode_budget = total_threads
1103 .saturating_sub(encoder_floor)
1104 .max(decode_concurrency);
1105 let even_share = if fixed_encoder.is_some() {
1106 (decode_budget / decode_concurrency).max(1)
1108 } else {
1109 let contexts = decode_concurrency.saturating_add(encoder_slots).max(1);
1110 (total_threads / contexts).max(1)
1111 };
1112 let decoder_threads = if request.hardware_decode || !request.software_video_encoder {
1113 even_share
1116 } else {
1117 software_decoder_threads(request.source_frame_pixels)
1120 .clamp(1, (decode_budget / decode_concurrency).max(1))
1121 .min(even_share)
1122 };
1123 let decode_assigned = decoder_threads.saturating_mul(decode_concurrency);
1124 let encoder_threads = match fixed_encoder {
1127 Some(threads) => threads,
1128 None if request.software_video_encoder => {
1129 total_threads.saturating_sub(decode_assigned).max(1)
1130 }
1131 None => 0,
1132 };
1133 CodecThreadAllocation {
1134 total_threads,
1135 decode_concurrency,
1136 decoder_threads: i64::try_from(decoder_threads).unwrap_or(1).clamp(1, 64),
1137 hardware_decoder_threads: i64::try_from(HARDWARE_DECODER_THREADS.min(total_threads))
1138 .unwrap_or(1)
1139 .max(1),
1140 encoder_threads: i64::try_from(encoder_threads).unwrap_or(0).clamp(0, 64),
1141 allocated_threads: decode_assigned.saturating_add(encoder_threads),
1142 }
1143}
1144
1145fn software_decoder_threads(source_frame_pixels: u64) -> usize {
1148 usize::try_from(source_frame_pixels.div_ceil(DECODE_PIXELS_PER_THREAD))
1149 .unwrap_or(MAX_SOFTWARE_DECODER_THREADS)
1150 .clamp(MIN_SOFTWARE_DECODER_THREADS, MAX_SOFTWARE_DECODER_THREADS)
1151}
1152
1153pub(crate) fn unused_option_names(options: Option<AVDictionary>) -> Option<String> {
1155 let options = options?;
1156 let names = options
1157 .iter()
1158 .map(|entry| entry.key().to_string_lossy().into_owned())
1159 .collect::<Vec<_>>();
1160 (!names.is_empty()).then(|| names.join(", "))
1161}
1162
1163pub(crate) fn reject_unused_decode_options(
1164 options: Option<AVDictionary>,
1165) -> Result<(), DecodeError> {
1166 if let Some(names) = unused_option_names(options) {
1167 Err(DecodeError::Adapter(format!(
1168 "FFmpeg decoder did not consume options: {names}"
1169 )))
1170 } else {
1171 Ok(())
1172 }
1173}
1174
1175pub(crate) fn reject_unused_encode_options(
1176 options: Option<AVDictionary>,
1177) -> Result<(), EncodeError> {
1178 if let Some(names) = unused_option_names(options) {
1179 Err(EncodeError::Adapter(format!(
1180 "FFmpeg encoder did not consume options: {names}"
1181 )))
1182 } else {
1183 Ok(())
1184 }
1185}
1186
1187pub(crate) fn color_tags(
1192 color: ColorMetadata,
1193) -> (
1194 ffi::AVColorPrimaries,
1195 ffi::AVColorTransferCharacteristic,
1196 ffi::AVColorSpace,
1197 ffi::AVColorRange,
1198) {
1199 (
1200 match color.primaries {
1201 ColorPrimaries::Bt601 => ffi::AVCOL_PRI_SMPTE170M,
1202 ColorPrimaries::Bt709 => ffi::AVCOL_PRI_BT709,
1203 ColorPrimaries::Bt2020 => ffi::AVCOL_PRI_BT2020,
1204 ColorPrimaries::DisplayP3 => ffi::AVCOL_PRI_SMPTE432,
1205 },
1206 match color.transfer {
1207 TransferFunction::Bt709 => ffi::AVCOL_TRC_BT709,
1208 TransferFunction::Srgb => ffi::AVCOL_TRC_IEC61966_2_1,
1209 TransferFunction::Pq => ffi::AVCOL_TRC_SMPTE2084,
1210 TransferFunction::Hlg => ffi::AVCOL_TRC_ARIB_STD_B67,
1211 },
1212 match color.matrix {
1213 ColorMatrix::Bt601 => ffi::AVCOL_SPC_SMPTE170M,
1214 ColorMatrix::Bt709 => ffi::AVCOL_SPC_BT709,
1215 ColorMatrix::Bt2020Ncl => ffi::AVCOL_SPC_BT2020_NCL,
1216 ColorMatrix::Rgb => ffi::AVCOL_SPC_RGB,
1217 },
1218 match color.range {
1219 ColorRange::Limited => ffi::AVCOL_RANGE_MPEG,
1220 ColorRange::Full => ffi::AVCOL_RANGE_JPEG,
1221 },
1222 )
1223}
1224
1225pub(crate) fn color_options(color: ColorMetadata) -> AVDictionary {
1228 let (primaries, transfer, matrix, range) = color_tags(color);
1229 AVDictionary::new_int(c"color_primaries", i64::from(primaries), 0)
1230 .set_int(c"color_trc", i64::from(transfer), 0)
1231 .set_int(c"colorspace", i64::from(matrix), 0)
1232 .set_int(c"color_range", i64::from(range), 0)
1233}
1234
1235fn gpu_fault(error: &dyn std::any::Any) -> Option<alpha2_media::GpuFault> {
1237 error
1238 .downcast_ref::<alpha2_ffmpeg_bridge::BridgeError>()
1239 .and_then(alpha2_ffmpeg_bridge::BridgeError::gpu_fault)
1240}
1241
1242pub(crate) fn adapter_error(error: impl std::fmt::Display + 'static) -> DecodeError {
1244 match gpu_fault(&error) {
1245 Some(fault) => DecodeError::Gpu {
1246 fault,
1247 message: error.to_string(),
1248 },
1249 None => DecodeError::Adapter(error.to_string()),
1250 }
1251}
1252
1253pub(crate) fn encode_adapter_error(error: impl std::fmt::Display + 'static) -> EncodeError {
1255 match gpu_fault(&error) {
1256 Some(fault) => EncodeError::Gpu {
1257 fault,
1258 message: error.to_string(),
1259 },
1260 None => EncodeError::Adapter(error.to_string()),
1261 }
1262}
1263
1264pub(crate) fn encode_adapter_error_at(
1265 context: &str,
1266 error: impl std::fmt::Display + 'static,
1267) -> EncodeError {
1268 match gpu_fault(&error) {
1269 Some(fault) => EncodeError::Gpu {
1270 fault,
1271 message: format!("{context}: {error}"),
1272 },
1273 None => EncodeError::Adapter(format!("{context}: {error}")),
1274 }
1275}