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 Container::Wav => c"wav",
650 }
651}
652
653pub(crate) fn muxer_header_options(container: Container) -> Option<AVDictionary> {
658 matches!(container, Container::Mkv | Container::Webm)
659 .then(|| AVDictionary::new(c"fflags", c"+bitexact", 0))
660}
661
662pub(crate) fn container_codec_tag(
669 container: Container,
670 codec_id: ffi::AVCodecID,
671 tag: u32,
672 copied: bool,
673) -> u32 {
674 if matches!(container, Container::Mkv | Container::Webm) {
675 0
676 } else if codec_id == ffi::AV_CODEC_ID_HEVC {
677 if tag == HVC1 || tag == HEV1 {
678 tag
679 } else {
680 HVC1
681 }
682 } else if copied {
683 0
684 } else {
685 tag
686 }
687}
688
689pub(crate) fn color_metadata(
690 parameters: &rsmpeg::avcodec::AVCodecParameters,
691) -> Option<ColorMetadata> {
692 map_color(
693 parameters.color_primaries,
694 parameters.color_trc,
695 parameters.color_space,
696 parameters.color_range,
697 )
698}
699
700pub(crate) fn frame_color_metadata(frame: &AVFrame) -> Option<ColorMetadata> {
701 map_color(
702 frame.color_primaries,
703 frame.color_trc,
704 frame.colorspace,
705 frame.color_range,
706 )
707}
708
709pub(crate) fn map_color(
714 primaries: ffi::AVColorPrimaries,
715 transfer: ffi::AVColorTransferCharacteristic,
716 matrix: ffi::AVColorSpace,
717 range: ffi::AVColorRange,
718) -> Option<ColorMetadata> {
719 let code = |value| u8::try_from(value).unwrap_or(u8::MAX);
720 let full_range = match range {
721 ffi::AVCOL_RANGE_UNSPECIFIED => None,
722 range => Some(range == ffi::AVCOL_RANGE_JPEG),
723 };
724 ColorMetadata::from_h273(code(primaries), code(transfer), code(matrix), full_range)
725}
726
727pub(crate) fn check_frame_size(width: u32, height: u32) -> Result<(), DecodeError> {
734 if alpha2_media::frame_size_supported(width, height) {
735 return Ok(());
736 }
737 Err(DecodeError::Unsupported(format!(
738 "a {width}x{height} frame is larger than {} pixels or {} on a side",
739 alpha2_media::MAX_FRAME_PIXELS,
740 alpha2_media::MAX_FRAME_DIMENSION
741 )))
742}
743
744pub(crate) fn video_decoder_options(threads: i64) -> AVDictionary {
747 let max_pixels = i64::try_from(alpha2_media::MAX_FRAME_PIXELS).unwrap_or(i64::MAX);
748 AVDictionary::new_int(c"threads", threads, 0)
749 .set(c"flags", c"+unaligned", 0)
750 .set_int(c"max_pixels", max_pixels, 0)
751}
752
753pub(crate) fn pixel_format(
755 layout: alpha2_media::PixelLayout,
756) -> Result<ffi::AVPixelFormat, EncodeError> {
757 pixel_format_named(layout.ffmpeg_name())
758}
759
760pub(crate) fn pixel_format_named(name: &str) -> Result<ffi::AVPixelFormat, EncodeError> {
761 Ok(match name {
762 "yuv420p" => ffi::AV_PIX_FMT_YUV420P,
763 "yuva420p" => ffi::AV_PIX_FMT_YUVA420P,
764 "yuv420p10le" => ffi::AV_PIX_FMT_YUV420P10LE,
765 "yuva420p10le" => ffi::AV_PIX_FMT_YUVA420P10LE,
766 "yuv422p" => ffi::AV_PIX_FMT_YUV422P,
767 "yuva422p" => ffi::AV_PIX_FMT_YUVA422P,
768 "yuv422p10le" => ffi::AV_PIX_FMT_YUV422P10LE,
769 "yuva422p10le" => ffi::AV_PIX_FMT_YUVA422P10LE,
770 "yuv444p" => ffi::AV_PIX_FMT_YUV444P,
771 "yuva444p" => ffi::AV_PIX_FMT_YUVA444P,
772 "yuv444p10le" => ffi::AV_PIX_FMT_YUV444P10LE,
773 "yuva444p10le" => ffi::AV_PIX_FMT_YUVA444P10LE,
774 "p010le" => ffi::AV_PIX_FMT_P010LE,
775 _ => {
776 return Err(EncodeError::Adapter(format!(
777 "pixel layout {name} has no FFmpeg pixel format"
778 )));
779 }
780 })
781}
782
783pub fn packed_frame(
789 width: u32,
790 height: u32,
791 layout: alpha2_media::PixelLayout,
792) -> Result<alpha2_ffmpeg_bridge::Yuv420pFrameBuffer, alpha2_ffmpeg_bridge::BridgeError> {
793 let (coded_width, coded_height) = (
794 i32::try_from(width)
795 .map_err(|_| alpha2_ffmpeg_bridge::BridgeError::InvalidInput("width"))?,
796 i32::try_from(height)
797 .map_err(|_| alpha2_ffmpeg_bridge::BridgeError::InvalidInput("height"))?,
798 );
799 let format = pixel_format(layout).map_err(|_| {
800 alpha2_ffmpeg_bridge::BridgeError::InvalidInput("pixel layout has no FFmpeg format")
801 })?;
802 alpha2_ffmpeg_bridge::Yuv420pFrameBuffer::with_format(coded_width, coded_height, format)
803}
804
805pub(crate) fn prores_options(layout: alpha2_media::PixelLayout) -> Vec<(&'static CStr, String)> {
806 let mut options = vec![
807 (
808 c"profile",
809 if layout.alpha { "4444" } else { "hq" }.to_owned(),
810 ),
811 (c"vendor", "apl0".to_owned()),
812 ];
813 if layout.alpha {
814 options.push((c"alpha_bits", "16".to_owned()));
815 }
816 options
817}
818
819pub(crate) fn video_encoder_options(
820 color: ColorMetadata,
821 codec: &AVCodec,
822 on_hardware: bool,
823 threads: i64,
824 width: u32,
825) -> AVDictionary {
826 let mut options = color_options(color);
827 if encoder_class(codec) == NativeEncoderClass::Hybrid {
830 options = options.set_int(c"hw_encoding", i64::from(on_hardware), 0);
831 }
832 if on_hardware {
833 return options;
834 }
835 let name = codec.name().to_string_lossy();
836 for (key, value) in software_encoder_profile(&name, width, threads) {
837 options = set_encoder_option(options, key, &value);
838 }
839 options.set_int(c"threads", threads, 0)
840}
841
842fn software_encoder_profile(name: &str, width: u32, threads: i64) -> Vec<(&'static CStr, String)> {
850 match name {
851 "libvpx-vp9" => vec![
852 (c"deadline", "good".into()),
853 (c"cpu-used", "4".into()),
854 (c"row-mt", "1".into()),
855 (c"tile-columns", vp9_tile_columns_log2(width).to_string()),
856 (c"lag-in-frames", "25".into()),
857 (c"auto-alt-ref", "1".into()),
858 ],
859 "libsvtav1" => vec![
860 (c"preset", "8".into()),
861 (
862 c"svtav1-params",
863 format!(
864 "lp={}",
865 if deterministic_encode() {
866 1
867 } else {
868 svt_av1_parallelism(threads)
869 }
870 ),
871 ),
872 ],
873 _ => Vec::new(),
874 }
875}
876
877pub(crate) fn deterministic_encode() -> bool {
880 std::env::var_os("ALPHA2_DETERMINISTIC_ENCODE").is_some_and(|value| value == "1")
881}
882
883pub(crate) fn vp9_tile_columns_log2(width: u32) -> u32 {
885 (width / 256).max(1).ilog2().min(6)
886}
887
888pub(crate) fn svt_av1_parallelism(threads: i64) -> u32 {
891 match threads {
892 ..=1 => 1,
893 2 => 2,
894 3..=5 => 3,
895 6..=11 => 4,
896 12..=23 => 5,
897 _ => 6,
898 }
899}
900
901pub(crate) fn set_encoder_option(options: AVDictionary, key: &CStr, value: &str) -> AVDictionary {
904 let value = CString::new(value).unwrap_or_default();
905 if key == c"svtav1-params" && options.get(key, None, 0).is_some() {
906 let appended = CString::new(format!(":{}", value.to_string_lossy())).unwrap_or_default();
907 options.set(key, &appended, ffi::AV_DICT_APPEND)
908 } else {
909 options.set(key, &value, 0)
910 }
911}
912
913#[must_use]
918pub fn codec_thread_budget() -> i64 {
919 i64::try_from(configured_codec_thread_budget().min(16)).unwrap_or(1)
920}
921
922pub fn configured_codec_thread_override() -> Result<Option<usize>, String> {
928 codec_thread_override(std::env::var_os("ALPHA2_FFMPEG_THREADS").as_deref())
929}
930
931pub fn codec_thread_override(setting: Option<&std::ffi::OsStr>) -> Result<Option<usize>, String> {
936 let Some(setting) = setting else {
937 return Ok(None);
938 };
939 setting
940 .to_str()
941 .and_then(|value| value.parse::<usize>().ok())
942 .filter(|value| *value > 0)
943 .map(|value| Some(value.min(64)))
944 .ok_or_else(|| setting.to_string_lossy().into_owned())
945}
946
947fn configured_codec_thread_budget() -> usize {
948 configured_codec_thread_override()
949 .ok()
950 .flatten()
951 .unwrap_or_else(|| {
952 codec_thread_budget_for(
953 std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
954 )
955 })
956 .clamp(1, 64)
957}
958
959pub(crate) fn codec_thread_budget_for(hardware_threads: usize) -> usize {
962 hardware_threads
963 .saturating_sub(codec_thread_reserve(hardware_threads))
964 .max(1)
965}
966
967pub(crate) const fn codec_thread_reserve(hardware_threads: usize) -> usize {
973 match hardware_threads {
974 16.. => 2,
975 6..=15 => 1,
976 _ => 0,
977 }
978}
979
980#[derive(Clone, Copy, Debug, PartialEq, Eq)]
982pub struct CodecThreadRequest {
983 pub decode_concurrency: usize,
985 pub hardware_decode: bool,
987 pub source_frame_pixels: u64,
989 pub software_video_encoder: bool,
991 pub encoder_fixed_threads: Option<usize>,
995}
996
997const DECODE_PIXELS_PER_THREAD: u64 = 2_000_000;
999const MIN_SOFTWARE_DECODER_THREADS: usize = 2;
1001const MAX_SOFTWARE_DECODER_THREADS: usize = 6;
1004const ENCODER_THREAD_FLOOR: usize = 4;
1007
1008const fn encoder_thread_floor(total_threads: usize) -> usize {
1011 let third = total_threads / 3;
1012 if third < ENCODER_THREAD_FLOOR {
1013 if third == 0 { 1 } else { third }
1014 } else {
1015 ENCODER_THREAD_FLOOR
1016 }
1017}
1018pub const HARDWARE_DECODER_THREADS: usize = 2;
1026
1027#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1030pub struct CodecThreadAllocation {
1031 pub total_threads: usize,
1033 pub decode_concurrency: usize,
1035 pub decoder_threads: i64,
1037 pub hardware_decoder_threads: i64,
1039 pub encoder_threads: i64,
1041 pub allocated_threads: usize,
1043}
1044
1045#[must_use]
1058pub fn codec_thread_allocation(request: CodecThreadRequest) -> CodecThreadAllocation {
1059 codec_thread_allocation_within(request, configured_codec_thread_budget())
1060}
1061
1062#[must_use]
1065pub fn decode_concurrency_ceiling(software_video_encoder: bool) -> usize {
1066 decode_concurrency_ceiling_for(configured_codec_thread_budget(), software_video_encoder)
1067}
1068
1069#[must_use]
1071pub fn decode_concurrency_ceiling_for(configured: usize, software_video_encoder: bool) -> usize {
1072 configured
1073 .saturating_sub(usize::from(software_video_encoder))
1074 .max(1)
1075}
1076
1077pub(crate) fn codec_thread_allocation_within(
1079 request: CodecThreadRequest,
1080 configured: usize,
1081) -> CodecThreadAllocation {
1082 let encoder_slots = usize::from(request.software_video_encoder);
1083 let decode_concurrency = request
1084 .decode_concurrency
1085 .max(1)
1086 .min(decode_concurrency_ceiling_for(
1087 configured,
1088 request.software_video_encoder,
1089 ));
1090 let total_threads = configured.max(decode_concurrency.saturating_add(encoder_slots));
1091 let fixed_encoder = request
1094 .encoder_fixed_threads
1095 .filter(|_| request.software_video_encoder)
1096 .map(|threads| threads.max(1));
1097 let encoder_floor = match fixed_encoder {
1098 Some(threads) => threads.min(total_threads.saturating_sub(decode_concurrency).max(1)),
1099 None if request.software_video_encoder => encoder_thread_floor(total_threads)
1100 .min(total_threads.saturating_sub(decode_concurrency).max(1)),
1101 None => 0,
1102 };
1103 let decode_budget = total_threads
1104 .saturating_sub(encoder_floor)
1105 .max(decode_concurrency);
1106 let even_share = if fixed_encoder.is_some() {
1107 (decode_budget / decode_concurrency).max(1)
1109 } else {
1110 let contexts = decode_concurrency.saturating_add(encoder_slots).max(1);
1111 (total_threads / contexts).max(1)
1112 };
1113 let decoder_threads = if request.hardware_decode || !request.software_video_encoder {
1114 even_share
1117 } else {
1118 software_decoder_threads(request.source_frame_pixels)
1121 .clamp(1, (decode_budget / decode_concurrency).max(1))
1122 .min(even_share)
1123 };
1124 let decode_assigned = decoder_threads.saturating_mul(decode_concurrency);
1125 let encoder_threads = match fixed_encoder {
1128 Some(threads) => threads,
1129 None if request.software_video_encoder => {
1130 total_threads.saturating_sub(decode_assigned).max(1)
1131 }
1132 None => 0,
1133 };
1134 CodecThreadAllocation {
1135 total_threads,
1136 decode_concurrency,
1137 decoder_threads: i64::try_from(decoder_threads).unwrap_or(1).clamp(1, 64),
1138 hardware_decoder_threads: i64::try_from(HARDWARE_DECODER_THREADS.min(total_threads))
1139 .unwrap_or(1)
1140 .max(1),
1141 encoder_threads: i64::try_from(encoder_threads).unwrap_or(0).clamp(0, 64),
1142 allocated_threads: decode_assigned.saturating_add(encoder_threads),
1143 }
1144}
1145
1146fn software_decoder_threads(source_frame_pixels: u64) -> usize {
1149 usize::try_from(source_frame_pixels.div_ceil(DECODE_PIXELS_PER_THREAD))
1150 .unwrap_or(MAX_SOFTWARE_DECODER_THREADS)
1151 .clamp(MIN_SOFTWARE_DECODER_THREADS, MAX_SOFTWARE_DECODER_THREADS)
1152}
1153
1154pub(crate) fn unused_option_names(options: Option<AVDictionary>) -> Option<String> {
1156 let options = options?;
1157 let names = options
1158 .iter()
1159 .map(|entry| entry.key().to_string_lossy().into_owned())
1160 .collect::<Vec<_>>();
1161 (!names.is_empty()).then(|| names.join(", "))
1162}
1163
1164pub(crate) fn reject_unused_decode_options(
1165 options: Option<AVDictionary>,
1166) -> Result<(), DecodeError> {
1167 if let Some(names) = unused_option_names(options) {
1168 Err(DecodeError::Adapter(format!(
1169 "FFmpeg decoder did not consume options: {names}"
1170 )))
1171 } else {
1172 Ok(())
1173 }
1174}
1175
1176pub(crate) fn reject_unused_encode_options(
1177 options: Option<AVDictionary>,
1178) -> Result<(), EncodeError> {
1179 if let Some(names) = unused_option_names(options) {
1180 Err(EncodeError::Adapter(format!(
1181 "FFmpeg encoder did not consume options: {names}"
1182 )))
1183 } else {
1184 Ok(())
1185 }
1186}
1187
1188pub(crate) fn color_tags(
1193 color: ColorMetadata,
1194) -> (
1195 ffi::AVColorPrimaries,
1196 ffi::AVColorTransferCharacteristic,
1197 ffi::AVColorSpace,
1198 ffi::AVColorRange,
1199) {
1200 (
1201 match color.primaries {
1202 ColorPrimaries::Bt601 => ffi::AVCOL_PRI_SMPTE170M,
1203 ColorPrimaries::Bt709 => ffi::AVCOL_PRI_BT709,
1204 ColorPrimaries::Bt2020 => ffi::AVCOL_PRI_BT2020,
1205 ColorPrimaries::DisplayP3 => ffi::AVCOL_PRI_SMPTE432,
1206 },
1207 match color.transfer {
1208 TransferFunction::Bt709 => ffi::AVCOL_TRC_BT709,
1209 TransferFunction::Srgb => ffi::AVCOL_TRC_IEC61966_2_1,
1210 TransferFunction::Pq => ffi::AVCOL_TRC_SMPTE2084,
1211 TransferFunction::Hlg => ffi::AVCOL_TRC_ARIB_STD_B67,
1212 },
1213 match color.matrix {
1214 ColorMatrix::Bt601 => ffi::AVCOL_SPC_SMPTE170M,
1215 ColorMatrix::Bt709 => ffi::AVCOL_SPC_BT709,
1216 ColorMatrix::Bt2020Ncl => ffi::AVCOL_SPC_BT2020_NCL,
1217 ColorMatrix::Rgb => ffi::AVCOL_SPC_RGB,
1218 },
1219 match color.range {
1220 ColorRange::Limited => ffi::AVCOL_RANGE_MPEG,
1221 ColorRange::Full => ffi::AVCOL_RANGE_JPEG,
1222 },
1223 )
1224}
1225
1226pub(crate) fn color_options(color: ColorMetadata) -> AVDictionary {
1229 let (primaries, transfer, matrix, range) = color_tags(color);
1230 AVDictionary::new_int(c"color_primaries", i64::from(primaries), 0)
1231 .set_int(c"color_trc", i64::from(transfer), 0)
1232 .set_int(c"colorspace", i64::from(matrix), 0)
1233 .set_int(c"color_range", i64::from(range), 0)
1234}
1235
1236fn gpu_fault(error: &dyn std::any::Any) -> Option<alpha2_media::GpuFault> {
1238 error
1239 .downcast_ref::<alpha2_ffmpeg_bridge::BridgeError>()
1240 .and_then(alpha2_ffmpeg_bridge::BridgeError::gpu_fault)
1241}
1242
1243pub(crate) fn adapter_error(error: impl std::fmt::Display + 'static) -> DecodeError {
1245 match gpu_fault(&error) {
1246 Some(fault) => DecodeError::Gpu {
1247 fault,
1248 message: error.to_string(),
1249 },
1250 None => DecodeError::Adapter(error.to_string()),
1251 }
1252}
1253
1254pub(crate) fn encode_adapter_error(error: impl std::fmt::Display + 'static) -> EncodeError {
1256 match gpu_fault(&error) {
1257 Some(fault) => EncodeError::Gpu {
1258 fault,
1259 message: error.to_string(),
1260 },
1261 None => EncodeError::Adapter(error.to_string()),
1262 }
1263}
1264
1265pub(crate) fn encode_adapter_error_at(
1266 context: &str,
1267 error: impl std::fmt::Display + 'static,
1268) -> EncodeError {
1269 match gpu_fault(&error) {
1270 Some(fault) => EncodeError::Gpu {
1271 fault,
1272 message: format!("{context}: {error}"),
1273 },
1274 None => EncodeError::Adapter(format!("{context}: {error}")),
1275 }
1276}