forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

prores_out.rs240 lines, 9.4 KiBHistoryRawDownload
1//! The pieces of a ProRes export that are not the picture walk: the chroma
2//! upsampling that takes the compositor's 4:2:0 to the 4:2:2 / 4:4:4 a ProRes
3//! profile codes, and the QuickTime `.mov` writer.
4//!
5//! # Chroma upsampling
6//!
7//! The compositor and every decoder here hand the export 4:2:0 (8-bit, or 10-bit
8//! where the span passes a 10-bit source through untouched). ProRes 422 codes
9//! 4:2:2 and ProRes 4444 codes 4:4:4, so the chroma is upsampled -- not by
10//! duplicating samples, which would double every chroma edge into a blocky
11//! staircase, but by the linear filter the siting of 4:2:0 asks for:
12//!
13//! * vertically, 4:2:0 chroma sits half way between two luma rows
14//! (MPEG-2 / H.264 "left" siting), so the two luma rows of a chroma row take
15//! `3/4 * own + 1/4 * neighbour` (the row above for the upper, the row below
16//! for the lower), edges clamped;
17//! * horizontally (4:4:4 only), chroma is co-sited with the even luma column, so
18//! even columns copy and odd columns average their two neighbours.
19//!
20//! An 8-bit picture is widened first to 10 bits with the same `x << 2 | x >> 6`
21//! scale the HEVC and AV1 seats use (255 maps to 1023), so the encoder always
22//! sees 10-bit samples and the filter runs at 10-bit precision. Nothing here can
23//! recover chroma detail the 4:2:0 picture never had: a ProRes 422 file of a
24//! 4:2:0 timeline is a 4:2:2 *container* of 4:2:0 information.
25
26use std::fs::File;
27use std::io::{BufWriter, Write};
28use std::path::Path;
29
30use ec_core::frame::{PixelFormat, Plane, VideoFrame};
31use ec_core::registry::{AudioParameters, CodecId, CodecParameters, MediaParameters, StreamInfo};
32use ec_core::{ChannelLayout, Muxer as _, Packet, TimeBase};
33
34/// Little-endian bytes of 16-bit samples.
35fn le_bytes(samples: &[u16]) -> Vec<u8> {
36 samples.iter().flat_map(|s| s.to_le_bytes()).collect()
37}
38
39/// An 8-bit sample at 10 bits: the same scale as the HEVC/AV1 widening.
40fn widen(s: u8) -> u16 {
41 u16::from(s) << 2 | u16::from(s) >> 6
42}
43
44/// Vertical 4:2:0 -> 4:2:2: a `cw` x `ch` chroma plane to `cw` x `h` rows.
45fn up_vertical(src: &[u16], cw: usize, ch: usize, h: usize) -> Vec<u16> {
46 let mut out = Vec::with_capacity(cw * h);
47 for y in 0..h {
48 let own = (y / 2).min(ch - 1);
49 let other = if y % 2 == 0 { own.saturating_sub(1) } else { (own + 1).min(ch - 1) };
50 let (a, b) = (&src[own * cw..own * cw + cw], &src[other * cw..other * cw + cw]);
51 out.extend(a.iter().zip(b).map(|(&a, &b)| ((3 * u32::from(a) + u32::from(b) + 2) >> 2) as u16));
52 }
53 out
54}
55
56/// Horizontal 4:2:2 -> 4:4:4: `cw` columns to `w`, even columns copied and odd
57/// columns the mean of their two neighbours.
58fn up_horizontal(src: &[u16], cw: usize, rows: usize, w: usize) -> Vec<u16> {
59 let mut out = Vec::with_capacity(w * rows);
60 for r in 0..rows {
61 let line = &src[r * cw..r * cw + cw];
62 for x in 0..w {
63 let i = (x / 2).min(cw - 1);
64 out.push(if x % 2 == 0 {
65 line[i]
66 } else {
67 ((u32::from(line[i]) + u32::from(line[(i + 1).min(cw - 1)]) + 1) >> 1) as u16
68 });
69 }
70 }
71 out
72}
73
74/// Planes of an `w` x `h` 4:2:0 picture at 10 bits as the 4:2:2 (`I210`) or
75/// 4:4:4 (`I410`) frame the encoder takes.
76pub(crate) fn upsampled_frame(
77 y: &[u16],
78 u: &[u16],
79 v: &[u16],
80 w: usize,
81 h: usize,
82 full_chroma: bool,
83) -> crate::Result<VideoFrame> {
84 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
85 let chroma = |p: &[u16]| {
86 let tall = up_vertical(&p[..cw * ch], cw, ch, h);
87 if full_chroma { up_horizontal(&tall, cw, h, w) } else { tall }
88 };
89 let (cb, cr) = (chroma(u), chroma(v));
90 let cstride = if full_chroma { w } else { cw } * 2;
91 let planes = vec![
92 Plane::new(le_bytes(&y[..w * h]), w * 2),
93 Plane::new(le_bytes(&cb), cstride),
94 Plane::new(le_bytes(&cr), cstride),
95 ];
96 let format = if full_chroma { PixelFormat::I410 } else { PixelFormat::I210 };
97 VideoFrame::try_new(format, w as u32, h as u32, planes)
98 .map_err(|e| format!("ProRes frame: {e}").into())
99}
100
101/// [`upsampled_frame`] from 8-bit planes, widened to 10 bits first.
102pub(crate) fn upsampled_frame_8(
103 y: &[u8],
104 u: &[u8],
105 v: &[u8],
106 w: usize,
107 h: usize,
108 full_chroma: bool,
109) -> crate::Result<VideoFrame> {
110 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
111 let wide = |p: &[u8], n: usize| p[..n].iter().map(|&s| widen(s)).collect::<Vec<u16>>();
112 upsampled_frame(&wide(y, w * h), &wide(u, cw * ch), &wide(v, cw * ch), w, h, full_chroma)
113}
114
115/// PCM frames per packet the sound is written in: about a second at 48 kHz.
116const PCM_CHUNK: usize = 48_000;
117
118/// A QuickTime `.mov`: one ProRes picture track and, where the timeline has
119/// sound, one 16-bit little-endian PCM track (`sowt`).
120pub(crate) struct MovWriter {
121 writer: ec_mp4::Mp4Muxer<BufWriter<File>>,
122 stream: u32,
123 tb: TimeBase,
124 ticks: i64,
125 frames: i64,
126}
127
128impl MovWriter {
129 /// Opens `out`. `params` are the encoder's codec parameters (the sample-entry
130 /// fourcc rides in its extradata); `(timescale, ticks)` is the frame clock
131 /// ([`crate::mux::frame_timing`]).
132 pub(crate) fn create(out: &Path, params: &CodecParameters, (timescale, ticks): (u32, u32)) -> crate::Result<Self> {
133 let file = BufWriter::new(File::create(out)?);
134 let mut writer = ec_mp4::Mp4Muxer::with_brands(file, *b"qt ", &[*b"qt "]).map_err(crate::demux::mp4_error)?;
135 let tb = TimeBase::new(1, i64::from(timescale));
136 let mut info = StreamInfo::new(0, tb, params.clone());
137 info.default = true;
138 let stream = writer.add_stream(info).map_err(crate::demux::mp4_error)?;
139 Ok(Self { writer, stream, tb, ticks: i64::from(ticks), frames: 0 })
140 }
141
142 /// One coded frame.
143 pub(crate) fn write_frame(&mut self, bytes: &[u8]) -> crate::Result<()> {
144 let mut p = Packet::new(self.stream, self.tb, bytes.to_vec());
145 p.pts = Some(self.frames * self.ticks);
146 p.dts = p.pts;
147 p.duration = Some(self.ticks);
148 p.flags.keyframe = true;
149 self.writer.write_packet(&p).map_err(crate::demux::mp4_error)?;
150 self.frames += 1;
151 Ok(())
152 }
153
154 /// The sound: interleaved `bits`-wide (16 or 24) samples in `i32`s, written after the picture in
155 /// packets of about a second. `frames` PCM frames per channel are written
156 /// exactly (the caller has already padded or trimmed to the picture's length).
157 pub(crate) fn write_sound(&mut self, samples: &[i32], rate: u32, channels: u16, bits: u8) -> crate::Result<()> {
158 let channels = usize::from(channels.max(1));
159 // 24-bit is big-endian `in24` (ffmpeg `pcm_s24be`), what a ProRes master carries.
160 let mut params = CodecParameters::new(if bits == 16 { CodecId::PcmS16Le } else { CodecId::PcmS24Be });
161 params.media = MediaParameters::Audio(AudioParameters {
162 sample_rate: rate,
163 layout: ChannelLayout::from_count(channels),
164 ..Default::default()
165 });
166 let tb = TimeBase::from_rate(rate);
167 let stream = self.writer.add_stream(StreamInfo::new(1, tb, params)).map_err(crate::demux::mp4_error)?;
168 let mut at = 0i64;
169 for chunk in samples.chunks(PCM_CHUNK * channels) {
170 let bytes: Vec<u8> = if bits == 16 {
171 chunk.iter().flat_map(|&s| (s.clamp(-32768, 32767) as i16).to_le_bytes()).collect()
172 } else {
173 chunk
174 .iter()
175 .flat_map(|&s| {
176 let b = s.clamp(-8_388_608, 8_388_607).to_be_bytes();
177 [b[1], b[2], b[3]]
178 })
179 .collect()
180 };
181 let n = (chunk.len() / channels) as i64;
182 let mut p = Packet::new(stream, tb, bytes);
183 p.pts = Some(at);
184 p.dts = Some(at);
185 p.duration = Some(n);
186 p.flags.keyframe = true;
187 self.writer.write_packet(&p).map_err(crate::demux::mp4_error)?;
188 at += n;
189 }
190 Ok(())
191 }
192
193 pub(crate) fn finish(mut self) -> crate::Result<()> {
194 if self.frames == 0 {
195 return Err("export produced no coded pictures".into());
196 }
197 self.writer.finish().map_err(crate::demux::mp4_error)?;
198 self.writer.into_inner().flush()?;
199 Ok(())
200 }
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206
207 fn le(plane: &Plane) -> Vec<u16> {
208 plane.data.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect()
209 }
210
211 #[test]
212 fn flat_chroma_stays_flat_in_both_upsamplings() {
213 let (w, h) = (6, 4);
214 let y = vec![500u16; w * h];
215 let c = vec![600u16; (w / 2) * (h / 2)];
216 for full in [false, true] {
217 let f = upsampled_frame(&y, &c, &c, w, h, full).unwrap();
218 assert!(le(&f.planes[1]).iter().all(|&s| s == 600), "full={full}");
219 }
220 }
221
222 #[test]
223 fn vertical_filter_is_three_quarters_own_plus_a_quarter_neighbour() {
224 // Two chroma rows, 400 and 800: rows come out 400, 500, 700, 800 (edges clamp).
225 let up = up_vertical(&[400, 800], 1, 2, 4);
226 assert_eq!(up, vec![400, 500, 700, 800]);
227 }
228
229 #[test]
230 fn horizontal_filter_copies_even_and_averages_odd() {
231 let up = up_horizontal(&[100, 300], 2, 1, 4);
232 assert_eq!(up, vec![100, 200, 300, 300]);
233 }
234
235 #[test]
236 fn eight_bit_white_widens_to_1023() {
237 assert_eq!(widen(255), 1023);
238 assert_eq!(widen(0), 0);
239 }
240}