mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-27 04:38:38 +00:00
media: present full-range high-depth RGB from the shared decoder (#4063)
This commit is contained in:
@@ -2300,6 +2300,9 @@ fn push_decoded(
|
||||
#[cfg(test)]
|
||||
mod rgb8_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod wide_rgb_tests;
|
||||
|
||||
fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: Tick) -> Result<VideoFrame> {
|
||||
let FramePresentation { container_color, par: default_par, rotation, aperture } = presentation;
|
||||
let (mut width, mut height) = (vf.width(), vf.height());
|
||||
@@ -2311,7 +2314,7 @@ fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: T
|
||||
Some(sar) => sar,
|
||||
None => default_par,
|
||||
};
|
||||
let color = resolve_color(tags, container_color);
|
||||
let mut color = resolve_color(tags, container_color);
|
||||
let bit_depth = vf.bit_depth();
|
||||
let (planes, alpha) = vf.into_planes();
|
||||
|
||||
@@ -2338,6 +2341,38 @@ fn to_craft_frame(vf: DecodedVideoFrame, presentation: FramePresentation, pts: T
|
||||
}
|
||||
PixelData::Rgba8(Arc::new(rgba))
|
||||
}
|
||||
ColorFamily::Rgb if color.range == Range::Full && (9..=16).contains(&bit_depth) && planes.iter().all(|p| p.bit_depth() == bit_depth) => {
|
||||
let luma = aperture.and_then(|clap| clean_aperture_region(clap, (width, height)));
|
||||
if let Some(r) = luma {
|
||||
(width, height) = (r.w as u32, r.h as u32);
|
||||
}
|
||||
let samples = (width as usize)
|
||||
.checked_mul(height as usize)
|
||||
.and_then(|n| n.checked_mul(4))
|
||||
.filter(|&n| n <= craft_frame::DEFAULT_MAX_FRAME_BYTES / size_of::<f32>())
|
||||
.ok_or_else(|| MediaError::Decode("RGB picture exceeds the frame buffer limit".into()))?;
|
||||
let [r, g, b]: [Plane; 3] = planes.try_into().map_err(|_| MediaError::Decode("expected three RGB planes".into()))?;
|
||||
let r = plane_u16(r, luma)?;
|
||||
let g = plane_u16(g, luma)?;
|
||||
let b = plane_u16(b, luma)?;
|
||||
let alpha_max = alpha.as_ref().map_or(1, |a| ((1u32 << a.bit_depth()) - 1) as u16);
|
||||
let alpha = alpha.map(|a| plane_u16(a, luma)).transpose()?.into_iter().flatten().chain(std::iter::repeat(alpha_max));
|
||||
// One transfer lookup per code avoids evaluating the curve per pixel and keeps
|
||||
// every decoded code distinct, including at 16 bits.
|
||||
let max_code = (1usize << bit_depth) - 1;
|
||||
let mut transfer = Vec::new();
|
||||
transfer.try_reserve_exact(max_code + 1).map_err(|_| MediaError::Decode("could not allocate the RGB transfer table".into()))?;
|
||||
transfer.extend((0..=max_code).map(|code| craft_color::to_linear(code as f32 / max_code as f32, color.transfer)));
|
||||
let linear = |value: u16| transfer[usize::from(value).min(max_code)];
|
||||
let mut rgba = Vec::new();
|
||||
rgba.try_reserve_exact(samples).map_err(|_| MediaError::Decode("could not allocate the RGB picture".into()))?;
|
||||
for (((r, g), b), a) in r.into_iter().zip(g).zip(b).zip(alpha) {
|
||||
let a = (f32::from(a) / f32::from(alpha_max)).min(1.0);
|
||||
rgba.extend_from_slice(&[linear(r) * a, linear(g) * a, linear(b) * a, a]);
|
||||
}
|
||||
color.transfer = Transfer::Linear;
|
||||
PixelData::RgbaF32(Arc::new(rgba))
|
||||
}
|
||||
ColorFamily::YCbCr => {
|
||||
let chroma = match subsampling {
|
||||
Subsampling::S420 => Chroma::C420,
|
||||
@@ -2474,6 +2509,10 @@ fn rotate_frame(mut frame: VideoFrame, turns: u8) -> VideoFrame {
|
||||
let rotated = rotate_plane(pixels.as_chunks::<4>().0, w, h, turns);
|
||||
PixelData::Rgba8(Arc::new(rotated.into_flattened()))
|
||||
}
|
||||
PixelData::RgbaF32(pixels) => {
|
||||
let rotated = rotate_plane(pixels.as_chunks::<4>().0, w, h, turns);
|
||||
PixelData::RgbaF32(Arc::new(rotated.into_flattened()))
|
||||
}
|
||||
PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha } => {
|
||||
let (cw, ch, out_chroma) = match chroma {
|
||||
Chroma::C420 => (w.div_ceil(2), h.div_ceil(2), Chroma::C420),
|
||||
@@ -2513,7 +2552,6 @@ fn rotate_frame(mut frame: VideoFrame, turns: u8) -> VideoFrame {
|
||||
alpha: alpha.map(|a| Arc::new(rotate_plane(&a, w, h, turns))),
|
||||
}
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
frame.width = nw;
|
||||
frame.height = nh;
|
||||
|
||||
@@ -73,9 +73,11 @@ fn packed_rgb_keeps_stride_aperture_rotation_and_straight_alpha() -> TestResult
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn higher_depth_rgb_is_not_quantized_to_packed_bytes() -> TestResult {
|
||||
fn limited_range_high_depth_rgb_remains_unsupported() -> TestResult {
|
||||
let channel = Plane::packed(1, 1, 10, Samples::U16(vec![900]))?;
|
||||
let decoded = DecodedVideoFrame::new(1, 1, ColorFamily::Rgb, Subsampling::S444, vec![channel; 3], None)?;
|
||||
assert!(matches!(to_craft_frame(decoded, presentation(), Tick::ZERO), Err(MediaError::Unsupported(_))));
|
||||
let color = ColorInfo { range: Range::Limited, ..ColorInfo::SRGB_FULL };
|
||||
let presentation = FramePresentation { container_color: Some(color), ..presentation() };
|
||||
assert!(matches!(to_craft_frame(decoded, presentation, Tick::ZERO), Err(MediaError::Unsupported(_))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use craft_video::ffv1::{self, Colorspace, Encoder, EncoderConfig};
|
||||
|
||||
use super::*;
|
||||
use crate::stream::{self, MediaSource as OpenedSource};
|
||||
|
||||
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
fn assert_samples(actual: &[f32], expected: &[f32]) {
|
||||
assert_eq!(actual.len(), expected.len());
|
||||
for (i, (&got, &want)) in actual.iter().zip(expected).enumerate() {
|
||||
assert!((got - want).abs() < 1e-6, "sample {i}: expected {want}, got {got}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_range_rgb_ffv1_keeps_wide_samples_across_backward_seek() -> TestResult {
|
||||
const WIDTH: u32 = 5;
|
||||
const HEIGHT: u32 = 3;
|
||||
let mut raw = ffv1::Frame { width: WIDTH, height: HEIGHT, colorspace: Colorspace::Rgb, bit_depth: 10, chroma_shift: (0, 0), planes: vec![Vec::new(); 3] };
|
||||
let encoder = Encoder::new(&raw, EncoderConfig::default())?;
|
||||
let mut track = matroska::TrackSpec::new(matroska::TrackKind::Video, "V_FFV1");
|
||||
track.codec_private = encoder.config_record();
|
||||
track.video_size = Some((WIDTH, HEIGHT));
|
||||
track.default_duration_ns = Some(40_000_000);
|
||||
let mut writer = matroska::MkvWriter::new(Cursor::new(Vec::new()), vec![track], matroska::MuxOptions::default())?;
|
||||
|
||||
let mut expected = Vec::new();
|
||||
for n in 0u16..3 {
|
||||
let codes: Vec<[u16; 3]> = (0..WIDTH as u16 * HEIGHT as u16).map(|p| [256 + 96 * n + p, 500 + p, 910 - p]).collect();
|
||||
for (c, plane) in raw.planes.iter_mut().enumerate() {
|
||||
*plane = codes.iter().map(|pixel| pixel[c]).collect();
|
||||
}
|
||||
writer.write_frame(0, i64::from(n) * 40_000_000, true, &encoder.encode(&raw)?, Some(40_000_000))?;
|
||||
// The existing Rec.709 fallback uses the sRGB preview curve. All fixture codes are
|
||||
// above its linear segment, and adjacent codes must survive the full conversion.
|
||||
expected.push(
|
||||
codes
|
||||
.into_iter()
|
||||
.flat_map(|pixel| {
|
||||
let [r, g, b] = pixel.map(|c| ((f32::from(c) / 1023.0 + 0.055) / 1.055).powf(2.4));
|
||||
[r, g, b, 1.0]
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
}
|
||||
let bytes = writer.finish()?.into_inner();
|
||||
let OpenedSource::Craft(source) = stream::open_bytes("wide-rgb-ffv1.mkv", bytes.into())? else {
|
||||
panic!("expected the shared FFV1 reader");
|
||||
};
|
||||
for n in [2, 0, 1] {
|
||||
let pts = Tick::from_units(n as i64, 25);
|
||||
let frame = source.video_frame(FrameRequest { time: pts, scale: 1.0 })?;
|
||||
assert_eq!((frame.width, frame.height, frame.pts), (WIDTH, HEIGHT, pts));
|
||||
assert_eq!((frame.color.range, frame.color.transfer), (Range::Full, Transfer::Linear));
|
||||
let PixelData::RgbaF32(pixels) = &frame.data else { panic!("expected linear floating-point RGBA") };
|
||||
assert_samples(pixels, &expected[n]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_range_wide_rgb_crops_rotates_and_premultiplies() -> TestResult {
|
||||
let plane = |rows| Plane::new(3, 2, 4, 10, Samples::U16(rows));
|
||||
let red = plane(vec![8, 1023, 11, 999, 12, 1023, 13, 999])?;
|
||||
let green = plane(vec![20, 512, 21, 999, 22, 256, 23, 999])?;
|
||||
let blue = plane(vec![24, 1, 25, 999, 26, 1023, 27, 999])?;
|
||||
let alpha = plane(vec![0, 512, 0, 999, 0, 0, 0, 999])?;
|
||||
let mut decoded = DecodedVideoFrame::new(3, 2, ColorFamily::Rgb, Subsampling::S444, vec![red, green, blue], Some(alpha))?;
|
||||
decoded.sar = Some((5, 4));
|
||||
let aperture = isobmff::CleanAperture { width: (1, 1), height: (2, 1), horiz_offset: (0, 1), vert_offset: (0, 1) };
|
||||
let color = ColorInfo { transfer: Transfer::Linear, ..ColorInfo::SRGB_FULL };
|
||||
let presentation = FramePresentation { container_color: Some(color), par: (1, 1), rotation: 1, aperture: Some(aperture) };
|
||||
let pts = Tick::from_units(4, 25);
|
||||
let frame = to_craft_frame(decoded, presentation, pts)?;
|
||||
assert_eq!((frame.width, frame.height, frame.par, frame.pts, frame.color), (2, 1, (4, 5), pts, color));
|
||||
let PixelData::RgbaF32(pixels) = &frame.data else { panic!("expected linear floating-point RGBA") };
|
||||
let half = 512.0 / 1023.0;
|
||||
assert_samples(pixels, &[0.0, 0.0, 0.0, 0.0, half, half * half, half / 1023.0, half]);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user