diff --git a/apps/desktop-gpui/src/import.rs b/apps/desktop-gpui/src/import.rs index 03ae8ff73ec..22436c970c7 100644 --- a/apps/desktop-gpui/src/import.rs +++ b/apps/desktop-gpui/src/import.rs @@ -1948,9 +1948,6 @@ fn frame_timestamp(frame: &ffmpeg::frame::Video, time_base: ffmpeg::Rational) -> Duration::from_secs_f64(seconds.max(0.0)) } -/// The Y'CbCr matrix an imported display.mp4 is written and tagged with. The -/// renderer decodes with BT.709 for a BT.709 tag and BT.601 for anything -/// else, so the tag has to describe the samples the scaler wrote. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ImportMatrix { Bt601, @@ -1979,9 +1976,12 @@ impl SourceColor { _ if rgb => ImportMatrix::Bt709, ffmpeg::color::Space::BT709 => ImportMatrix::Bt709, ffmpeg::color::Space::BT470BG | ffmpeg::color::Space::SMPTE170M => ImportMatrix::Bt601, - // Untagged video follows the usual convention: BT.601 for - // standard definition, BT.709 for HD. - ffmpeg::color::Space::Unspecified if height < 720 => ImportMatrix::Bt601, + ffmpeg::color::Space::Unspecified => { + match cap_rendering::cpu_yuv::YuvMatrix::from_color_space(space, height) { + cap_rendering::cpu_yuv::YuvMatrix::Bt709 => ImportMatrix::Bt709, + cap_rendering::cpu_yuv::YuvMatrix::Bt601 => ImportMatrix::Bt601, + } + } _ => ImportMatrix::Bt709, }; let full_range = rgb diff --git a/crates/export/src/tracks.rs b/crates/export/src/tracks.rs index 7a297903a46..73e0503132a 100644 --- a/crates/export/src/tracks.rs +++ b/crates/export/src/tracks.rs @@ -636,11 +636,6 @@ const SWS_CS_ITU709: i32 = 1; const SWS_CS_ITU601: i32 = 5; impl Nv12Converter { - /// Writes `decoded` into `target`, NV12 at the track's size, in BT.709 - /// because that is how the encoder tags every track. A BT.709 frame of - /// the same size is a plane copy; anything else (a BT.601 or untagged - /// source, which the renderer also reads as BT.601, or a camera swapped - /// mid-recording) goes through swscale with the source's matrix. fn fill(&mut self, decoded: &DecodedFrame, target: &mut frame::Video) -> Result<(), String> { let (width, height) = (decoded.width(), decoded.height()); if width == 0 || height == 0 { diff --git a/crates/rendering/src/cpu_yuv.rs b/crates/rendering/src/cpu_yuv.rs index 3c4668e7134..923527d1d8c 100644 --- a/crates/rendering/src/cpu_yuv.rs +++ b/crates/rendering/src/cpu_yuv.rs @@ -1,10 +1,6 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -/// The Y'CbCr matrix a limited-range picture was encoded with, which decides -/// how it converts back to RGB. Decoders take it from the source's colour tag: -/// BT.709 when the stream says so, BT.601 otherwise (untagged sources keep the -/// BT.601 decode they always had). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum YuvMatrix { #[default] @@ -12,10 +8,15 @@ pub enum YuvMatrix { Bt709, } +pub const UNTAGGED_HD_MIN_HEIGHT: u32 = 720; + impl YuvMatrix { - pub fn from_color_space(space: ffmpeg::util::color::Space) -> Self { + pub fn from_color_space(space: ffmpeg::util::color::Space, height: u32) -> Self { match space { ffmpeg::util::color::Space::BT709 => Self::Bt709, + ffmpeg::util::color::Space::Unspecified if height >= UNTAGGED_HD_MIN_HEIGHT => { + Self::Bt709 + } _ => Self::Bt601, } } @@ -2468,14 +2469,33 @@ mod tests { #[test] fn matrix_follows_the_colour_tag() { use ffmpeg::util::color::Space; - assert_eq!(YuvMatrix::from_color_space(Space::BT709), YuvMatrix::Bt709); - for space in [ - Space::Unspecified, - Space::BT470BG, - Space::SMPTE170M, - Space::RGB, - ] { - assert_eq!(YuvMatrix::from_color_space(space), YuvMatrix::Bt601); + assert_eq!( + YuvMatrix::from_color_space(Space::BT709, 480), + YuvMatrix::Bt709 + ); + assert_eq!( + YuvMatrix::from_color_space(Space::BT709, 1080), + YuvMatrix::Bt709 + ); + assert_eq!( + YuvMatrix::from_color_space(Space::Unspecified, UNTAGGED_HD_MIN_HEIGHT), + YuvMatrix::Bt709 + ); + assert_eq!( + YuvMatrix::from_color_space(Space::Unspecified, 1080), + YuvMatrix::Bt709 + ); + assert_eq!( + YuvMatrix::from_color_space(Space::Unspecified, 480), + YuvMatrix::Bt601 + ); + assert_eq!( + YuvMatrix::from_color_space(Space::Unspecified, 0), + YuvMatrix::Bt601 + ); + for space in [Space::BT470BG, Space::SMPTE170M, Space::RGB] { + assert_eq!(YuvMatrix::from_color_space(space, 1080), YuvMatrix::Bt601); + assert_eq!(YuvMatrix::from_color_space(space, 480), YuvMatrix::Bt601); } } diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs index d9706a43f78..9131c6ec6d1 100644 --- a/crates/rendering/src/decoder/avassetreader.rs +++ b/crates/rendering/src/decoder/avassetreader.rs @@ -710,7 +710,7 @@ impl AVAssetReaderDecoder { Ok(( video.width(), video.height(), - YuvMatrix::from_color_space(video.color_space()), + YuvMatrix::from_color_space(video.color_space(), video.height()), )) })(); let (width, height, matrix) = match dimensions { diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs index f077478d6ca..8590fa88d53 100644 --- a/crates/rendering/src/decoder/ffmpeg.rs +++ b/crates/rendering/src/decoder/ffmpeg.rs @@ -330,7 +330,10 @@ impl CachedFrame { width: frame.width(), height: frame.height(), format: PixelFormat::Nv12, - matrix: YuvMatrix::from_color_space(frame.color_space()), + matrix: YuvMatrix::from_color_space( + frame.color_space(), + frame.height(), + ), y_stride: cuda.y_pitch as u32, uv_stride: cuda.uv_pitch as u32, planes: Arc::clone(converter.plane_pool()), @@ -344,7 +347,7 @@ impl CachedFrame { let planes = Arc::clone(converter.plane_pool()); let width = frame.width(); let height = frame.height(); - let matrix = YuvMatrix::from_color_space(frame.color_space()); + let matrix = YuvMatrix::from_color_space(frame.color_space(), frame.height()); if let Some((pixel_format, y_stride, uv_stride)) = borrowable_yuv_layout(frame) { let bytes = yuv_plane_bytes(pixel_format, y_stride, uv_stride, height); diff --git a/crates/rendering/src/decoder/frame_converter.rs b/crates/rendering/src/decoder/frame_converter.rs index 514bb124a9b..e14405f6d94 100644 --- a/crates/rendering/src/decoder/frame_converter.rs +++ b/crates/rendering/src/decoder/frame_converter.rs @@ -127,7 +127,7 @@ impl FrameConverter { width, height, &mut output, - YuvMatrix::from_color_space(frame.color_space()), + YuvMatrix::from_color_space(frame.color_space(), frame.height()), ); return output; } @@ -137,7 +137,7 @@ impl FrameConverter { self.ensure_scaler( frame.format(), - YuvMatrix::from_color_space(frame.color_space()), + YuvMatrix::from_color_space(frame.color_space(), frame.height()), width, height, ); @@ -500,6 +500,36 @@ mod tests { } } + #[test] + fn untagged_height_selects_the_matrix_swscale_uses() { + ffmpeg::init().unwrap(); + let orange = [224u8, 122, 48]; + let bt709 = [133u8, 85, 175]; + let bt601 = [140u8, 80, 178]; + let cases = [ + (720u32, bt709, ffmpeg::color::Space::Unspecified), + (480, bt601, ffmpeg::color::Space::Unspecified), + (720, bt601, ffmpeg::color::Space::SMPTE170M), + ]; + for (height, [y, cb, cr], space) in cases { + let mut source = frame::Video::new(format::Pixel::YUV420P, 32, height); + source.data_mut(0).fill(y); + source.data_mut(1).fill(cb); + source.data_mut(2).fill(cr); + source.set_color_space(space); + source.set_color_range(ffmpeg::color::Range::MPEG); + let rgba = FrameConverter::new().convert(&mut source); + let index = ((height as usize / 2) * 32 + 16) * 4; + let pixel = [rgba[index], rgba[index + 1], rgba[index + 2]]; + for (channel, (actual, expected)) in pixel.into_iter().zip(orange).enumerate() { + assert!( + actual.abs_diff(expected) <= 8, + "{height} {space:?} channel {channel}: {pixel:?}" + ); + } + } + } + #[test] fn spare_planes_never_keep_a_buffer_above_the_frame_limit() { let limit = MAX_SPARE_PLANE_BYTES; diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs index 69544f792fc..fa7c6ef8a26 100644 --- a/crates/rendering/src/decoder/mod.rs +++ b/crates/rendering/src/decoder/mod.rs @@ -794,9 +794,6 @@ pub enum VideoDecoderMessage { GetFrame(f32, u32, tokio::sync::oneshot::Sender), } -/// The source's Y'CbCr matrix from its colour tag, for decoders that do not -/// see FFmpeg frames (Media Foundation), and whether its chroma is 4:2:0. -/// BT.601 and unknown chroma when the file cannot be read. #[cfg(target_os = "windows")] pub(crate) fn probe_yuv_layout(path: &std::path::Path) -> (YuvMatrix, Option) { ::ffmpeg::format::input(path) @@ -806,7 +803,7 @@ pub(crate) fn probe_yuv_layout(path: &std::path::Path) -> (YuvMatrix, Option Option Some(HeaderVideoMetadata { width: video.width(), height: video.height(), - matrix: crate::cpu_yuv::YuvMatrix::from_color_space(color_space), + matrix: crate::cpu_yuv::YuvMatrix::from_color_space(color_space, video.height()), chroma_is_420, }) } @@ -951,7 +951,7 @@ mod ordinary_media_access_tests { .unwrap() .color_space(); assert_eq!( - YuvMatrix::from_color_space(probed), + YuvMatrix::from_color_space(probed, 48), expected, "{name} full probe" ); diff --git a/crates/rendering/tests/untagged_color.rs b/crates/rendering/tests/untagged_color.rs new file mode 100644 index 00000000000..e34365e1abc --- /dev/null +++ b/crates/rendering/tests/untagged_color.rs @@ -0,0 +1,257 @@ +use std::path::{Path, PathBuf}; + +use cap_rendering::{ + DecodedFrame, PixelFormat, + cpu_yuv::{YuvMatrix, nv12_to_rgba_with_matrix, yuv420p_to_rgba_with_matrix}, + decoder::{DecoderType, spawn_decoder}, +}; + +const ORANGE: [u8; 3] = [224, 122, 48]; +const ORANGE_BT709_YCBCR: [u8; 3] = [133, 85, 175]; +const ORANGE_BT601_YCBCR: [u8; 3] = [140, 80, 178]; +const TOLERANCE: u8 = 8; + +struct Clip { + name: &'static str, + width: u32, + height: u32, + ycbcr: [u8; 3], + tag: Option, + matrix: YuvMatrix, +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn editor_and_export_decode_untagged_hd_as_bt709() { + ffmpeg::init().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let clips = [ + Clip { + name: "untagged-hd", + width: 1280, + height: 720, + ycbcr: ORANGE_BT709_YCBCR, + tag: None, + matrix: YuvMatrix::Bt709, + }, + Clip { + name: "untagged-480p", + width: 640, + height: 480, + ycbcr: ORANGE_BT601_YCBCR, + tag: None, + matrix: YuvMatrix::Bt601, + }, + Clip { + name: "tagged-bt601", + width: 1280, + height: 720, + ycbcr: ORANGE_BT601_YCBCR, + tag: Some(ffmpeg::util::color::Space::SMPTE170M), + matrix: YuvMatrix::Bt601, + }, + ]; + + for clip in clips { + let path = directory.path().join(format!("{}.mp4", clip.name)); + write_clip(&path, &clip); + assert_stream_tag(&path, &clip); + let decoder = spawn_decoder(clip.name, path, 30, 0.0, true) + .await + .unwrap_or_else(|error| panic!("{} decoder: {error}", clip.name)); + let decoder_type = decoder.decoder_type(); + assert!( + matches!( + decoder_type, + DecoderType::FFmpegSoftware | DecoderType::FFmpegHardware + ), + "{} decoded with {decoder_type}, outside the FFmpeg path that applies the editor matrix", + clip.name + ); + let frame = decoder + .get_frame_initial(0.0) + .await + .unwrap_or_else(|| panic!("{} produced no frame", clip.name)); + let rgb = rgb_from_decoded(&frame); + for (channel, (actual, expected)) in rgb.into_iter().zip(ORANGE).enumerate() { + assert!( + actual.abs_diff(expected) <= TOLERANCE, + "{} channel {channel}: decoded {rgb:?}, source {ORANGE:?}, matrix {:?}", + clip.name, + frame.matrix() + ); + } + assert_eq!( + frame.matrix(), + clip.matrix, + "{} matrix from the editor and export decoder", + clip.name + ); + } +} + +fn rgb_from_decoded(frame: &DecodedFrame) -> [u8; 3] { + let width = frame.width(); + let height = frame.height(); + let mut rgba = vec![0u8; width as usize * height as usize * 4]; + match frame.format() { + PixelFormat::Yuv420p => yuv420p_to_rgba_with_matrix( + frame.y_plane().expect("y"), + frame.u_plane().expect("u"), + frame.v_plane().expect("v"), + width, + height, + frame.y_stride(), + frame.uv_stride(), + &mut rgba, + frame.matrix(), + ), + PixelFormat::Nv12 => nv12_to_rgba_with_matrix( + frame.y_plane().expect("y"), + frame.uv_plane().expect("uv"), + width, + height, + frame.y_stride(), + frame.uv_stride(), + &mut rgba, + frame.matrix(), + ), + PixelFormat::Rgba => { + rgba = frame.data().to_vec(); + } + } + let x = (width / 2) as usize; + let y = (height / 2) as usize; + let index = (y * width as usize + x) * 4; + [rgba[index], rgba[index + 1], rgba[index + 2]] +} + +fn write_clip(path: &Path, clip: &Clip) { + let codec = ffmpeg::encoder::find_by_name("libx264") + .or_else(|| ffmpeg::encoder::find(ffmpeg::codec::Id::MPEG4)) + .expect("a bundled video encoder"); + let mut output = ffmpeg::format::output_as(path, "mp4").unwrap(); + let global_header = output + .format() + .flags() + .contains(ffmpeg::format::Flags::GLOBAL_HEADER); + let (stream_index, mut encoder) = { + let mut stream = output.add_stream(codec).unwrap(); + let stream_index = stream.index(); + stream.set_time_base((1, 30)); + stream.set_rate((30, 1)); + let mut encoder = ffmpeg::codec::context::Context::new_with_codec(codec) + .encoder() + .video() + .unwrap(); + encoder.set_width(clip.width); + encoder.set_height(clip.height); + encoder.set_format(ffmpeg::format::Pixel::YUV420P); + encoder.set_frame_rate(Some((30, 1))); + encoder.set_time_base((1, 30)); + if let Some(space) = clip.tag { + encoder.set_colorspace(space); + encoder.set_color_range(ffmpeg::util::color::Range::MPEG); + unsafe { + (*encoder.as_mut_ptr()).color_primaries = + ffmpeg::ffi::AVColorPrimaries::AVCOL_PRI_SMPTE170M; + (*encoder.as_mut_ptr()).color_trc = + ffmpeg::ffi::AVColorTransferCharacteristic::AVCOL_TRC_SMPTE170M; + } + } + if global_header { + encoder.set_flags(ffmpeg::codec::Flags::GLOBAL_HEADER); + } + stream.set_parameters(&encoder); + let encoder = encoder.open_as(codec).unwrap(); + stream.set_parameters(&encoder); + if clip.tag.is_none() { + unsafe { + let parameters = (*stream.as_mut_ptr()).codecpar; + (*parameters).color_space = ffmpeg::ffi::AVColorSpace::AVCOL_SPC_UNSPECIFIED; + (*parameters).color_primaries = + ffmpeg::ffi::AVColorPrimaries::AVCOL_PRI_UNSPECIFIED; + (*parameters).color_trc = + ffmpeg::ffi::AVColorTransferCharacteristic::AVCOL_TRC_UNSPECIFIED; + (*parameters).color_range = ffmpeg::ffi::AVColorRange::AVCOL_RANGE_UNSPECIFIED; + } + } + (stream_index, encoder) + }; + let mut header = ffmpeg::Dictionary::new(); + if clip.tag.is_some() { + header.set("movflags", "+write_colr"); + } + output.write_header_with(header).unwrap(); + let output_time_base = output.stream(stream_index).unwrap().time_base(); + let mut frame = + ffmpeg::frame::Video::new(ffmpeg::format::Pixel::YUV420P, clip.width, clip.height); + frame.data_mut(0).fill(clip.ycbcr[0]); + frame.data_mut(1).fill(clip.ycbcr[1]); + frame.data_mut(2).fill(clip.ycbcr[2]); + let (space, range) = match clip.tag { + Some(space) => (space, ffmpeg::util::color::Range::MPEG), + None => ( + ffmpeg::util::color::Space::Unspecified, + ffmpeg::util::color::Range::Unspecified, + ), + }; + frame.set_color_space(space); + frame.set_color_range(range); + for pts in 0..2 { + frame.set_pts(Some(pts)); + encoder.send_frame(&frame).unwrap(); + write_packets(&mut encoder, &mut output, stream_index, output_time_base); + } + encoder.send_eof().unwrap(); + write_packets(&mut encoder, &mut output, stream_index, output_time_base); + output.write_trailer().unwrap(); +} + +fn write_packets( + encoder: &mut ffmpeg::codec::encoder::video::Encoder, + output: &mut ffmpeg::format::context::Output, + stream_index: usize, + output_time_base: ffmpeg::Rational, +) { + let mut packet = ffmpeg::Packet::empty(); + while encoder.receive_packet(&mut packet).is_ok() { + packet.set_stream(stream_index); + packet.rescale_ts(encoder.time_base(), output_time_base); + packet.write_interleaved(output).unwrap(); + } +} + +fn assert_stream_tag(path: &PathBuf, clip: &Clip) { + let expected = clip.tag.unwrap_or(ffmpeg::util::color::Space::Unspecified); + let mut input = ffmpeg::format::input(path).unwrap(); + let stream = input.streams().best(ffmpeg::media::Type::Video).unwrap(); + let container = + ffmpeg::util::color::Space::from(unsafe { (*stream.parameters().as_ptr()).color_space }); + assert_eq!(container, expected, "{} container tag", clip.name); + let index = stream.index(); + let mut decoder = ffmpeg::codec::Context::from_parameters(stream.parameters()) + .unwrap() + .decoder() + .video() + .unwrap(); + let mut decoded = ffmpeg::frame::Video::empty(); + for (stream, packet) in input.packets() { + if stream.index() != index { + continue; + } + decoder.send_packet(&packet).unwrap(); + if decoder.receive_frame(&mut decoded).is_ok() { + break; + } + } + if decoded.width() == 0 { + decoder.send_eof().unwrap(); + decoder.receive_frame(&mut decoded).unwrap(); + } + assert_eq!( + decoded.color_space(), + expected, + "{} decoded frame tag", + clip.name + ); +}