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