forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

encode.rs1067 lines, 38.4 KiBHistoryRawDownload
1//! ProRes encoder (RDD 36 bitstream, progressive or interlaced, optional alpha): forward DCT, per-slice rate control,
2//! entropy coding, slice-parallel.
3
4use std::collections::VecDeque;
5use std::sync::atomic::{AtomicUsize, Ordering};
6use std::sync::{Mutex, OnceLock};
7
8use wide::f32x8;
9
10use ec_core::error::{Error, Result};
11use ec_core::frame::{ColorInfo, Frame, Interlace, PixelFormat, VideoFrame};
12use ec_core::packet::Packet;
13use ec_core::registry::{CodecId, CodecParameters, Encoder, MediaParameters};
14
15use crate::frame::AlphaPlane;
16use crate::header::MAX_DIM;
17use crate::tables::*;
18
19/// ProRes profile (the sample-entry fourcc follows it).
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum Profile {
22 /// 422 Proxy (`apco`).
23 Proxy,
24 /// 422 LT (`apcs`).
25 Lt,
26 /// 422 (`apcn`).
27 Standard,
28 /// 422 HQ (`apch`).
29 Hq,
30 /// 4444 (`ap4h`), no alpha.
31 P4444,
32 /// 4444 XQ (`ap4x`), no alpha.
33 P4444Xq,
34}
35
36const QM_PROXY_LUMA: [u8; 64] = [
37 4, 7, 9, 11, 13, 14, 15, 63, 7, 7, 11, 12, 14, 15, 63, 63, 9, 11, 13, 14, 15, 63, 63, 63, 11,
38 11, 13, 14, 63, 63, 63, 63, 11, 13, 14, 63, 63, 63, 63, 63, 13, 14, 63, 63, 63, 63, 63, 63, 13,
39 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
40];
41const QM_PROXY_CHROMA: [u8; 64] = [
42 4, 7, 9, 11, 13, 14, 63, 63, 7, 7, 11, 12, 14, 63, 63, 63, 9, 11, 13, 14, 63, 63, 63, 63, 11,
43 11, 13, 14, 63, 63, 63, 63, 11, 13, 14, 63, 63, 63, 63, 63, 13, 14, 63, 63, 63, 63, 63, 63, 13,
44 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
45];
46const QM_LT: [u8; 64] = [
47 4, 5, 6, 7, 9, 11, 13, 15, 5, 5, 7, 8, 11, 13, 15, 17, 6, 7, 9, 11, 13, 15, 15, 17, 7, 7, 9,
48 11, 13, 15, 17, 19, 7, 9, 11, 13, 14, 16, 19, 23, 9, 11, 13, 14, 16, 19, 23, 29, 9, 11, 13,
49 15, 17, 21, 28, 35, 11, 13, 16, 17, 21, 28, 35, 41,
50];
51const QM_STD: [u8; 64] = [
52 4, 4, 5, 5, 6, 7, 7, 9, 4, 4, 5, 6, 7, 7, 9, 9, 5, 5, 6, 7, 7, 9, 9, 10, 5, 5, 6, 7, 7, 9, 9,
53 10, 5, 6, 7, 7, 8, 9, 10, 12, 6, 7, 7, 8, 9, 10, 12, 15, 6, 7, 7, 9, 10, 11, 14, 17, 7, 7, 9,
54 10, 11, 14, 17, 21,
55];
56const QM_HQ: [u8; 64] = [
57 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
58 5, 4, 4, 4, 4, 4, 4, 5, 5, 4, 4, 4, 4, 4, 5, 5, 6, 4, 4, 4, 4, 5, 5, 6, 7, 4, 4, 4, 4, 5, 6,
59 7, 7,
60];
61
62impl Profile {
63 /// The QuickTime / MP4 sample-entry fourcc.
64 pub fn fourcc(self) -> [u8; 4] {
65 match self {
66 Profile::Proxy => *b"apco",
67 Profile::Lt => *b"apcs",
68 Profile::Standard => *b"apcn",
69 Profile::Hq => *b"apch",
70 Profile::P4444 => *b"ap4h",
71 Profile::P4444Xq => *b"ap4x",
72 }
73 }
74
75 /// The profile a sample-entry fourcc names.
76 pub fn from_fourcc(f: [u8; 4]) -> Option<Profile> {
77 [Profile::Proxy, Profile::Lt, Profile::Standard, Profile::Hq, Profile::P4444, Profile::P4444Xq]
78 .into_iter()
79 .find(|p| p.fourcc() == f)
80 }
81
82 /// True for the 4:4:4 profiles.
83 pub fn is_444(self) -> bool {
84 matches!(self, Profile::P4444 | Profile::P4444Xq)
85 }
86
87 /// Apple's nominal frame size at 1920x1080 (29.97 fps), in bytes.
88 fn nominal_1080(self) -> f64 {
89 let mbps = match self {
90 Profile::Proxy => 45.0,
91 Profile::Lt => 102.0,
92 Profile::Standard => 147.0,
93 Profile::Hq => 220.0,
94 Profile::P4444 => 330.0,
95 Profile::P4444Xq => 500.0,
96 };
97 mbps * 1e6 / 29.97 / 8.0
98 }
99
100 fn qmats(self) -> (&'static [u8; 64], &'static [u8; 64]) {
101 match self {
102 Profile::Proxy => (&QM_PROXY_LUMA, &QM_PROXY_CHROMA),
103 Profile::Lt => (&QM_LT, &QM_LT),
104 Profile::Standard => (&QM_STD, &QM_STD),
105 _ => (&QM_HQ, &QM_HQ),
106 }
107 }
108
109 /// A starting slice quantiser for the rate search.
110 fn start_q(self) -> usize {
111 match self {
112 Profile::Proxy => 12,
113 Profile::Lt => 8,
114 Profile::Standard => 5,
115 _ => 3,
116 }
117 }
118}
119
120/// Apple's nominal size of one frame of `mbs` macroblocks (16x16 luma blocks), in bytes: the
121/// 1080p29.97 rate scaled by `(mbs / 8160) ^ 0.846`, which lands on Apple's UHD figures (3.21x
122/// for 4x the area) and on the SD ones.
123pub fn nominal_frame_bytes(profile: Profile, mbs: usize) -> usize {
124 (profile.nominal_1080() * (mbs as f64 / 8160.0).powf(0.846)) as usize
125}
126
127/// Encoder settings.
128#[derive(Debug, Clone)]
129pub struct EncoderConfig {
130 /// Profile to produce.
131 pub profile: Profile,
132 /// Frame size in pixels.
133 pub width: u32,
134 /// Frame size in pixels.
135 pub height: u32,
136 /// Colour tags written in the frame header (and the stream parameters).
137 pub color: ColorInfo,
138 /// Worker threads, 1..=6 (default: available cores, at most 6).
139 pub threads: usize,
140 /// Target bits per macroblock; `None` = Apple's nominal rate for the profile and size.
141 pub bits_per_mb: Option<u32>,
142 /// Fixed slice quantiser index (1..=224) instead of rate control.
143 pub qscale: Option<u8>,
144 /// Four-byte encoder id written in the frame header.
145 pub creator: [u8; 4],
146 /// Coded alpha depth for the 4444 profiles: 0 = none, 8 or 16 bits. See
147 /// [`ProResEncoder::encode_with_alpha`].
148 pub alpha_bits: u8,
149}
150
151impl EncoderConfig {
152 /// Defaults for `profile` at `width` x `height`.
153 pub fn new(profile: Profile, width: u32, height: u32) -> EncoderConfig {
154 EncoderConfig {
155 profile,
156 width,
157 height,
158 color: ColorInfo::default(),
159 threads: std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 6),
160 bits_per_mb: None,
161 qscale: None,
162 creator: *b"edth",
163 alpha_bits: 0,
164 }
165 }
166}
167
168// --- bit sinks -------------------------------------------------------------------------
169
170trait Sink {
171 fn cw(&mut self, cb: u8, v: u32);
172 fn coef(&mut self, run_ctx: usize, lvl_ctx: usize, zeros: u32, a: u32, neg: bool);
173}
174
175#[inline(always)]
176fn cw_bits(cb: u8, v: u32) -> u32 {
177 let sw = u32::from(cb & 3) + 1;
178 let rice = u32::from(cb >> 5);
179 let exp = u32::from((cb >> 2) & 7);
180 if v < (sw << rice) {
181 (v >> rice) + 1 + rice
182 } else {
183 let vv = v - (sw << rice) + (1 << exp);
184 let nb = 31 - vv.leading_zeros();
185 2 * nb + sw - exp + 1
186 }
187}
188
189/// `(code, length)` of codeword `v` when it fits 32 bits.
190fn cw_code(cb: u8, v: u32) -> (u32, u32) {
191 let sw = u32::from(cb & 3) + 1;
192 let rice = u32::from(cb >> 5);
193 let exp = u32::from((cb >> 2) & 7);
194 if v < (sw << rice) {
195 let q = v >> rice;
196 ((1 << rice) | (v & ((1 << rice) - 1)), q + 1 + rice)
197 } else {
198 let vv = v - (sw << rice) + (1 << exp);
199 let nb = 31 - vv.leading_zeros();
200 (vv, 2 * nb + sw - exp + 1)
201 }
202}
203
204const TAB: usize = 64;
205
206/// Code / length lookup for the small run and level values.
207struct Tabs {
208 run: [[(u32, u8); TAB]; 16],
209 lvl: [[(u32, u8); TAB]; 10],
210}
211
212fn tabs() -> &'static Tabs {
213 static T: OnceLock<Tabs> = OnceLock::new();
214 T.get_or_init(|| {
215 let mut t = Tabs { run: [[(0, 0); TAB]; 16], lvl: [[(0, 0); TAB]; 10] };
216 for (i, &cb) in RUN_CB.iter().enumerate() {
217 for v in 0..TAB {
218 let (c, l) = cw_code(cb, v as u32);
219 t.run[i][v] = (c, l as u8);
220 }
221 }
222 for (i, &cb) in LEVEL_CB.iter().enumerate() {
223 for v in 0..TAB {
224 let (c, l) = cw_code(cb, v as u32);
225 t.lvl[i][v] = (c, l as u8);
226 }
227 }
228 t
229 })
230}
231
232struct Counter {
233 bits: u32,
234 t: &'static Tabs,
235}
236impl Sink for Counter {
237 #[inline(always)]
238 fn cw(&mut self, cb: u8, v: u32) {
239 self.bits += cw_bits(cb, v);
240 }
241 #[inline(always)]
242 fn coef(&mut self, run_ctx: usize, lvl_ctx: usize, zeros: u32, a: u32, _neg: bool) {
243 let (rc, lc) = (run_ctx.min(15), lvl_ctx.min(9));
244 let r = if (zeros as usize) < TAB { u32::from(self.t.run[rc][zeros as usize].1) } else { cw_bits(RUN_CB[rc], zeros) };
245 let l = if ((a - 1) as usize) < TAB { u32::from(self.t.lvl[lc][(a - 1) as usize].1) } else { cw_bits(LEVEL_CB[lc], a - 1) };
246 self.bits += r + l + 1;
247 }
248}
249
250struct BitW {
251 out: Vec<u8>,
252 acc: u64,
253 n: u32,
254 t: &'static Tabs,
255}
256impl BitW {
257 fn new() -> BitW {
258 BitW { out: Vec::with_capacity(4096), acc: 0, n: 0, t: tabs() }
259 }
260 /// `n <= 32` bits of `v`.
261 #[inline(always)]
262 fn put(&mut self, v: u32, n: u32) {
263 debug_assert!(n <= 32);
264 let mask = if n >= 32 { u32::MAX } else { (1u32 << n) - 1 };
265 self.acc = (self.acc << n) | u64::from(v & mask);
266 self.n += n;
267 if self.n >= 32 {
268 self.n -= 32;
269 self.out.extend_from_slice(&((self.acc >> self.n) as u32).to_be_bytes());
270 }
271 }
272 fn finish(mut self) -> Vec<u8> {
273 while self.n >= 8 {
274 self.n -= 8;
275 self.out.push((self.acc >> self.n) as u8);
276 }
277 if self.n > 0 {
278 self.out.push(((self.acc << (8 - self.n)) & 0xff) as u8);
279 }
280 self.out
281 }
282}
283impl Sink for BitW {
284 #[inline(always)]
285 fn cw(&mut self, cb: u8, v: u32) {
286 let sw = u32::from(cb & 3) + 1;
287 let rice = u32::from(cb >> 5);
288 let exp = u32::from((cb >> 2) & 7);
289 if v < (sw << rice) {
290 let q = v >> rice;
291 self.put(0, q);
292 self.put((1 << rice) | (v & ((1 << rice) - 1)), rice + 1);
293 } else {
294 let vv = v - (sw << rice) + (1 << exp);
295 let nb = 31 - vv.leading_zeros();
296 self.put(0, nb + sw - exp);
297 self.put(vv, nb + 1); // the leading one of vv is the stop bit
298 }
299 }
300 #[inline(always)]
301 fn coef(&mut self, run_ctx: usize, lvl_ctx: usize, zeros: u32, a: u32, neg: bool) {
302 let (rc, lc) = (run_ctx.min(15), lvl_ctx.min(9));
303 if (zeros as usize) < TAB && ((a - 1) as usize) < TAB {
304 let (rcode, rl) = self.t.run[rc][zeros as usize];
305 let (lcode, ll) = self.t.lvl[lc][(a - 1) as usize];
306 let (rl, ll) = (u32::from(rl), u32::from(ll));
307 if rl + ll < 32 {
308 self.put((rcode << (ll + 1)) | (lcode << 1) | u32::from(neg), rl + ll + 1);
309 return;
310 }
311 }
312 self.cw(RUN_CB[rc], zeros);
313 self.cw(LEVEL_CB[lc], a - 1);
314 self.put(u32::from(neg), 1);
315 }
316}
317
318fn code_component<S: Sink>(s: &mut S, q: &[i16], nb: usize) {
319 // DC.
320 let first = i32::from(q[0]);
321 s.cw(FIRST_DC_CB, ((first << 1) ^ (first >> 31)) as u32);
322 let mut prev = first;
323 let mut prev_neg = false;
324 let mut cbi = 5usize;
325 for b in 1..nb {
326 let cur = i32::from(q[b]);
327 let d = cur - prev;
328 let neg = d < 0;
329 let code = if d == 0 { 0 } else { 2 * d.unsigned_abs() - u32::from(neg != prev_neg) };
330 s.cw(DC_CB[cbi], code);
331 cbi = (code as usize).min(6);
332 prev_neg = neg;
333 prev = cur;
334 }
335 // AC, scan-index major, block minor.
336 let mut run_ctx = 4usize;
337 let mut lvl_ctx = 2usize;
338 let mut zeros = 0u32;
339 let ac = &q[nb..];
340 let mut i = 0;
341 while i < ac.len() {
342 // Skip zeros four at a time.
343 while i + 4 <= ac.len() && (ac[i] | ac[i + 1] | ac[i + 2] | ac[i + 3]) == 0 {
344 zeros += 4;
345 i += 4;
346 }
347 if i >= ac.len() {
348 break;
349 }
350 let v = ac[i];
351 i += 1;
352 if v == 0 {
353 zeros += 1;
354 continue;
355 }
356 let a = u32::from(v.unsigned_abs());
357 s.coef(run_ctx, lvl_ctx, zeros, a, v < 0);
358 run_ctx = zeros as usize;
359 lvl_ctx = a as usize;
360 zeros = 0;
361 }
362}
363
364// --- transform -------------------------------------------------------------------------
365
366/// `0.5 * cos(k * pi / 16)`.
367fn ck(k: u32) -> f32 {
368 (0.5 * (f64::from(k) * std::f64::consts::PI / 16.0).cos()) as f32
369}
370
371/// Orthonormal 8-point DCT along the array index; the eight lanes are independent columns.
372#[inline(always)]
373fn dct8(x: [f32x8; 8]) -> [f32x8; 8] {
374 let (c1, c2, c3, c4, c5, c6, c7) =
375 (f32x8::splat(ck(1)), f32x8::splat(ck(2)), f32x8::splat(ck(3)), f32x8::splat(ck(4)), f32x8::splat(ck(5)), f32x8::splat(ck(6)), f32x8::splat(ck(7)));
376 let s0 = x[0] + x[7];
377 let s1 = x[1] + x[6];
378 let s2 = x[2] + x[5];
379 let s3 = x[3] + x[4];
380 let d0 = x[0] - x[7];
381 let d1 = x[1] - x[6];
382 let d2 = x[2] - x[5];
383 let d3 = x[3] - x[4];
384 let e0 = s0 + s3;
385 let e1 = s1 + s2;
386 let f0 = s0 - s3;
387 let f1 = s1 - s2;
388 [
389 c4 * (e0 + e1),
390 c1 * d0 + c3 * d1 + c5 * d2 + c7 * d3,
391 c2 * f0 + c6 * f1,
392 c3 * d0 - c7 * d1 - c1 * d2 - c5 * d3,
393 c4 * (e0 - e1),
394 c5 * d0 - c1 * d1 + c7 * d2 + c3 * d3,
395 c6 * f0 - c2 * f1,
396 c7 * d0 - c5 * d1 + c3 * d2 - c1 * d3,
397 ]
398}
399
400#[inline(always)]
401fn transpose(x: &[f32x8; 8]) -> [f32x8; 8] {
402 let a: [[f32; 8]; 8] = [
403 x[0].to_array(), x[1].to_array(), x[2].to_array(), x[3].to_array(),
404 x[4].to_array(), x[5].to_array(), x[6].to_array(), x[7].to_array(),
405 ];
406 let mut o = [f32x8::splat(0.0); 8];
407 for c in 0..8 {
408 o[c] = f32x8::new([a[0][c], a[1][c], a[2][c], a[3][c], a[4][c], a[5][c], a[6][c], a[7][c]]);
409 }
410 o
411}
412
413/// Forward DCT of the 8x8 block at `src[at..]` (row pitch `stride`). `r[u]` holds the
414/// coefficients of horizontal frequency `u`, lane `v` = vertical frequency.
415#[inline(always)]
416fn fdct(src: &[f32], at: usize, stride: usize) -> [f32x8; 8] {
417 let mut x = [f32x8::splat(0.0); 8];
418 for (r, row) in x.iter_mut().enumerate() {
419 let o = at + r * stride;
420 *row = f32x8::new(src[o..o + 8].try_into().unwrap());
421 }
422 dct8(transpose(&dct8(x)))
423}
424
425// --- slice encoding --------------------------------------------------------------------
426
427#[derive(Clone, Copy)]
428struct Geom {
429 is_444: bool,
430 mb_w: usize,
431 /// Visible sizes of the three planes.
432 pw: [usize; 3],
433 ph: [usize; 3],
434}
435
436struct Src<'a> {
437 planes: [&'a [u8]; 3],
438 strides: [usize; 3],
439 bytes2: bool,
440 /// Left shift to the 12-bit domain (8-bit: widened first).
441 fmt_bits: u32,
442}
443
444impl Src<'_> {
445 /// One row of plane `p` as 12-bit-domain samples minus 2048.
446 fn row(&self, p: usize, y: usize, w: usize, dst: &mut [f32]) {
447 let at = y * self.strides[p];
448 if self.bytes2 {
449 let src = &self.planes[p][at..at + w * 2];
450 let (sh, bias) = match self.fmt_bits {
451 10 => (2u32, 2048i32),
452 _ => (0, 2048),
453 };
454 for (d, s) in dst.iter_mut().zip(src.as_chunks::<2>().0) {
455 *d = (((u32::from(u16::from_le_bytes([s[0], s[1]])) << sh) as i32) - bias) as f32;
456 }
457 } else {
458 let src = &self.planes[p][at..at + w];
459 for (d, &s) in dst.iter_mut().zip(src) {
460 let v = u32::from(s);
461 *d = (((v << 4) | (v >> 4)) as i32 - 2048) as f32;
462 }
463 }
464 }
465}
466
467fn qscale_of(idx: usize) -> f32 {
468 if idx > 128 { ((idx - 96) << 2) as f32 } else { idx as f32 }
469}
470
471struct Params {
472 g: Geom,
473 scan_pos: [usize; 64],
474 /// 1 / qmat at each scan index (luma, chroma).
475 rinv: [[f32; 64]; 2],
476 rnd: f32,
477 /// Slices carry an alpha payload (and the 8-byte slice header).
478 alpha: bool,
479}
480
481/// The DCT coefficients of one slice, scan-index major / block minor, per component, and its
482/// coded alpha (empty without an alpha channel).
483struct SliceCoefs {
484 coef: [Vec<f32>; 3],
485 alpha: Vec<u8>,
486}
487
488/// One field's (or frame's) alpha samples, 16-bit full scale.
489struct AlphaSrc<'a> {
490 data: &'a [u16],
491 stride: usize,
492 w: usize,
493 h: usize,
494 bits: u8,
495}
496
497/// Run-length alpha coding (RDD 36 section 7.3) of `px` (raster order, 16-bit full scale), the
498/// inverse of the decoder's `unpack_alpha`.
499fn encode_alpha(px: &[u16], bits: u8) -> Vec<u8> {
500 let mask: i32 = (1 << bits) - 1;
501 let v: Vec<i32> = px.iter().map(|&a| if bits == 16 { i32::from(a) } else { i32::from(a >> 8) }).collect();
502 let mut w = BitW::new();
503 let (short_bits, max_short) = if bits == 16 { (7, 64) } else { (4, 8) };
504 let mut prev = mask;
505 let mut i = 0;
506 let n = v.len();
507 while i < n {
508 loop {
509 let d = (v[i] - prev) & mask;
510 let sd = if d > mask / 2 { d - (mask + 1) } else { d };
511 if sd != 0 && sd.abs() <= max_short {
512 let m = sd.abs();
513 w.put(0, 1);
514 w.put((2 * m - 2 + i32::from(sd < 0)) as u32, short_bits);
515 } else {
516 w.put(1, 1);
517 w.put(d as u32, u32::from(bits));
518 }
519 prev = v[i];
520 i += 1;
521 if i >= n {
522 return w.finish();
523 }
524 if v[i] == prev {
525 w.put(0, 1);
526 break;
527 }
528 w.put(1, 1);
529 }
530 let mut run = 0;
531 while i + run < n && v[i + run] == prev && run < 2047 {
532 run += 1;
533 }
534 if run < 16 {
535 w.put(run as u32, 4);
536 } else {
537 w.put(0, 4);
538 w.put(run as u32, 11);
539 }
540 i += run;
541 }
542 w.finish()
543}
544
545/// Per-thread scratch: quantised coefficients.
546struct Scratch {
547 q: [Vec<i16>; 3],
548}
549
550impl Scratch {
551 fn new() -> Scratch {
552 Scratch { q: [Vec::new(), Vec::new(), Vec::new()] }
553 }
554}
555
556fn load_row(g: &Geom, src: &Src, mb_y: usize, rows: &mut [Vec<f32>; 3]) {
557 for p in 0..3 {
558 let pitch = if p == 0 || g.is_444 { g.mb_w * 16 } else { g.mb_w * 8 };
559 let (w, h) = (g.pw[p], g.ph[p]);
560 rows[p].resize(pitch * 16, 0.0);
561 for yy in 0..16 {
562 let sy = (mb_y * 16 + yy).min(h - 1);
563 let dst = &mut rows[p][yy * pitch..(yy + 1) * pitch];
564 src.row(p, sy, w, &mut dst[..w]);
565 let last = dst[w - 1];
566 dst[w..].fill(last);
567 }
568 }
569}
570
571/// Slice layout of one macroblock row: (first macroblock, macroblock count) per slice.
572fn row_slices(mb_w: usize) -> Vec<(usize, usize)> {
573 let mut v = Vec::new();
574 let mut mb_x = 0;
575 while mb_x < mb_w {
576 let mut cnt = 8usize;
577 while mb_w - mb_x < cnt {
578 cnt >>= 1;
579 }
580 v.push((mb_x, cnt));
581 mb_x += cnt;
582 }
583 v
584}
585
586/// DCT every slice of macroblock row `mb_y`.
587fn transform_row(pr: &Params, src: &Src, alpha: Option<&AlphaSrc>, mb_y: usize) -> Vec<SliceCoefs> {
588 let g = &pr.g;
589 let mut rows: [Vec<f32>; 3] = [Vec::new(), Vec::new(), Vec::new()];
590 load_row(g, src, mb_y, &mut rows);
591 let mut out = Vec::new();
592 for (mb_x, mbs) in row_slices(g.mb_w) {
593 let mut coef: [Vec<f32>; 3] = [Vec::new(), Vec::new(), Vec::new()];
594 for p in 0..3 {
595 let luma_like = p == 0 || g.is_444;
596 let nbk = if luma_like { 4 } else { 2 };
597 let nb = mbs * nbk;
598 let pitch = if luma_like { g.mb_w * 16 } else { g.mb_w * 8 };
599 let c = &mut coef[p];
600 c.resize(64 * nb, 0.0);
601 let mbw_px = if luma_like { 16 } else { 8 };
602 for mi in 0..mbs {
603 for k in 0..nbk {
604 let (bx, by) = if p == 0 {
605 ((k & 1) * 8, (k >> 1) * 8)
606 } else if g.is_444 {
607 ((k >> 1) * 8, (k & 1) * 8)
608 } else {
609 (0, k * 8)
610 };
611 let x0 = (mb_x + mi) * mbw_px + bx;
612 let blk = fdct(&rows[p], by * pitch + x0, pitch);
613 let b = mi * nbk + k;
614 for u in 0..8 {
615 let col = blk[u].to_array();
616 for v in 0..8 {
617 c[pr.scan_pos[v * 8 + u] * nb + b] = col[v];
618 }
619 }
620 }
621 }
622 }
623 let alpha = alpha.map_or_else(Vec::new, |a| {
624 let w = mbs * 16;
625 let mut px = Vec::with_capacity(w * 16);
626 for r in 0..16 {
627 let sy = (mb_y * 16 + r).min(a.h - 1);
628 for x in 0..w {
629 px.push(a.data[sy * a.stride + (mb_x * 16 + x).min(a.w - 1)]);
630 }
631 }
632 encode_alpha(&px, a.bits)
633 });
634 out.push(SliceCoefs { coef, alpha });
635 }
636 out
637}
638
639fn quantize(pr: &Params, coef: &[f32], p: usize, qidx: usize, q: &mut Vec<i16>) {
640 let qs = 1.0 / qscale_of(qidx);
641 let rinv = &pr.rinv[usize::from(p != 0)];
642 let nb = coef.len() / 64;
643 q.resize(coef.len(), 0);
644 let rnd = pr.rnd;
645 for i in 0..64 {
646 let inv = rinv[i] * qs;
647 let src = &coef[i * nb..(i + 1) * nb];
648 let dst = &mut q[i * nb..(i + 1) * nb];
649 for (d, &c) in dst.iter_mut().zip(src) {
650 let t = c * inv;
651 let a = (t.abs() + rnd) as i32 as i16;
652 *d = if t < 0.0 { -a } else { a };
653 }
654 }
655}
656
657fn slice_cost(pr: &Params, sc: &mut Scratch, s: &SliceCoefs, qidx: usize) -> usize {
658 let mut total = if pr.alpha { 8 } else { 6 } + s.alpha.len();
659 for p in 0..3 {
660 quantize(pr, &s.coef[p], p, qidx, &mut sc.q[p]);
661 let nb = s.coef[p].len() / 64;
662 let mut c = Counter { bits: 0, t: tabs() };
663 code_component(&mut c, &sc.q[p], nb);
664 total += (c.bits as usize).div_ceil(8);
665 }
666 total
667}
668
669fn write_slice(pr: &Params, sc: &mut Scratch, s: &SliceCoefs, qidx: usize) -> Result<Vec<u8>> {
670 let mut comps: Vec<Vec<u8>> = Vec::with_capacity(3);
671 for p in 0..3 {
672 quantize(pr, &s.coef[p], p, qidx, &mut sc.q[p]);
673 let nb = s.coef[p].len() / 64;
674 let mut w = BitW::new();
675 code_component(&mut w, &sc.q[p], nb);
676 comps.push(w.finish());
677 }
678 if comps.iter().any(|c| c.len() > 65535) {
679 return Err(Error::unsupported("ProRes slice over 64 KiB per component", "lower the rate"));
680 }
681 let mut out = Vec::with_capacity(8 + s.alpha.len() + comps.iter().map(Vec::len).sum::<usize>());
682 out.push(if pr.alpha { 8 << 3 } else { 6 << 3 });
683 out.push(qidx as u8);
684 out.extend_from_slice(&(comps[0].len() as u16).to_be_bytes());
685 out.extend_from_slice(&(comps[1].len() as u16).to_be_bytes());
686 if pr.alpha {
687 out.extend_from_slice(&(comps[2].len() as u16).to_be_bytes());
688 }
689 for c in &comps {
690 out.extend_from_slice(c);
691 }
692 out.extend_from_slice(&s.alpha);
693 if out.len() > 65535 {
694 return Err(Error::unsupported("ProRes slice over 64 KiB", "lower the rate"));
695 }
696 Ok(out)
697}
698
699/// Run `f(chunk_index)` for `0..n` over up to `threads` scoped threads, results in order.
700fn par_map<R: Send>(n: usize, threads: usize, f: impl Fn(usize) -> R + Sync) -> Vec<R> {
701 if threads <= 1 || n <= 1 {
702 return (0..n).map(f).collect();
703 }
704 let next = AtomicUsize::new(0);
705 let results: Mutex<Vec<Option<R>>> = Mutex::new((0..n).map(|_| None).collect());
706 std::thread::scope(|s| {
707 for _ in 0..threads.min(n) {
708 s.spawn(|| {
709 loop {
710 let i = next.fetch_add(1, Ordering::Relaxed);
711 if i >= n {
712 break;
713 }
714 let r = f(i);
715 results.lock().unwrap()[i] = Some(r);
716 }
717 });
718 }
719 });
720 results.into_inner().unwrap().into_iter().map(|r| r.unwrap()).collect()
721}
722
723const MAXQ: usize = 224;
724
725/// Smallest quantiser index whose estimated frame cost fits `budget`, by a secant search on
726/// (ln qscale, ln bytes) inside a shrinking bracket. Returns (`hi` fits, `lo` over budget or 0,
727/// every cost evaluated).
728fn search_q(cost: &impl Fn(usize) -> f64, budget: f64, start: usize) -> (usize, usize, std::collections::HashMap<usize, f64>) {
729 let mut costs: Vec<(usize, f64)> = Vec::new();
730 let (mut lo, mut hi) = (0usize, MAXQ + 1);
731 let mut q = start.clamp(1, MAXQ);
732 while hi - lo > 1 {
733 let c = cost(q);
734 costs.push((q, c));
735 if c <= budget {
736 hi = q;
737 } else {
738 lo = q;
739 }
740 if hi - lo <= 1 {
741 break;
742 }
743 let mut alpha = 0.8;
744 if costs.len() >= 2 {
745 let (qa, ca) = costs[costs.len() - 2];
746 let (qb, cb) = costs[costs.len() - 1];
747 let d = f64::from(qscale_of(qb) / qscale_of(qa)).ln();
748 if d.abs() > 1e-6 && ca > 0.0 && cb > 0.0 {
749 alpha = (-(cb / ca).ln() / d).clamp(0.3, 2.0);
750 }
751 }
752 let want = f64::from(qscale_of(q)).ln() + (c.max(1.0) / budget.max(1.0)).ln() / alpha;
753 let s = want.exp();
754 let guess = if s <= 128.0 { s.round() as usize } else { (s / 4.0).round() as usize + 96 };
755 let mut next = guess.clamp(lo + 1, hi - 1);
756 if next == q {
757 next = if c <= budget { q - 1 } else { q + 1 }.clamp(lo + 1, hi - 1);
758 }
759 q = next;
760 }
761 (hi, lo, costs.into_iter().collect())
762}
763
764/// Apple ProRes encoder. One call to [`ProResEncoder::encode`] turns a picture into one frame
765/// (the sample a QuickTime / MP4 track holds).
766///
767/// Input: 4:2:2 profiles take [`PixelFormat::I210`] or [`PixelFormat::I422`]; 4444 profiles take
768/// [`PixelFormat::I410`], [`PixelFormat::I412`] or [`PixelFormat::I444`]. The frame is coded
769/// progressive or, when the frame says so, as two fields, and with an alpha channel only through
770/// [`ProResEncoder::encode_with_alpha`].
771pub struct ProResEncoder {
772 cfg: EncoderConfig,
773 params: CodecParameters,
774 out: VecDeque<Packet>,
775 eof: bool,
776}
777
778impl ProResEncoder {
779 /// A new encoder.
780 pub fn new(mut cfg: EncoderConfig) -> Result<ProResEncoder> {
781 if cfg.width == 0 || cfg.height == 0 || cfg.width > MAX_DIM || cfg.height > MAX_DIM {
782 return Err(Error::unsupported(
783 format!("ProRes picture size {}x{}", cfg.width, cfg.height),
784 "sizes 1..=16384 on each side",
785 ));
786 }
787 if !matches!(cfg.alpha_bits, 0 | 8 | 16) || (cfg.alpha_bits != 0 && !cfg.profile.is_444()) {
788 return Err(Error::unsupported(
789 format!("ProRes alpha_bits {} for {:?}", cfg.alpha_bits, cfg.profile),
790 "alpha is 8 or 16 bits and only the 4444 profiles carry it",
791 ));
792 }
793 cfg.threads = cfg.threads.clamp(1, 6);
794 let mut params = CodecParameters::new(CodecId::ProRes);
795 params.extradata = Some(cfg.profile.fourcc().to_vec().into());
796 if let MediaParameters::Video(v) = &mut params.media {
797 v.width = cfg.width;
798 v.height = cfg.height;
799 v.format = Some(if cfg.profile.is_444() { PixelFormat::I412 } else { PixelFormat::I210 });
800 v.color = cfg.color;
801 }
802 Ok(ProResEncoder { cfg, params, out: VecDeque::new(), eof: false })
803 }
804
805 /// The configuration in force.
806 pub fn config(&self) -> &EncoderConfig {
807 &self.cfg
808 }
809
810 /// Encode one picture into a ProRes frame. With [`EncoderConfig::alpha_bits`] set the alpha
811 /// channel is coded fully opaque; see [`ProResEncoder::encode_with_alpha`].
812 pub fn encode(&self, frame: &VideoFrame) -> Result<Vec<u8>> {
813 self.encode_with_alpha(frame, None)
814 }
815
816 /// Encode one picture and its alpha plane (16-bit full scale, as the decoder returns it).
817 /// `alpha` must match the picture size and requires [`EncoderConfig::alpha_bits`] to be 8 or
818 /// 16; with `None` the coded alpha is fully opaque. A frame whose
819 /// [`interlace`](VideoFrame::interlace) is not progressive is coded as two field pictures.
820 pub fn encode_with_alpha(&self, frame: &VideoFrame, alpha: Option<&AlphaPlane>) -> Result<Vec<u8>> {
821 let cfg = &self.cfg;
822 let is_444 = cfg.profile.is_444();
823 let (fmt_bits, bytes2) = match (frame.format, is_444) {
824 (PixelFormat::I422, false) => (8, false),
825 (PixelFormat::I210, false) => (10, true),
826 (PixelFormat::I444, true) => (8, false),
827 (PixelFormat::I410, true) => (10, true),
828 (PixelFormat::I412, true) => (12, true),
829 (f, _) => {
830 return Err(Error::unsupported(
831 format!("ProRes {:?} from {f:?}", cfg.profile),
832 "422 profiles take I210 or I422, 4444 profiles take I410, I412 or I444",
833 ));
834 }
835 };
836 if frame.width != cfg.width || frame.height != cfg.height {
837 return Err(Error::unsupported(
838 format!("frame {}x{} against an encoder for {}x{}", frame.width, frame.height, cfg.width, cfg.height),
839 "create one encoder per picture size",
840 ));
841 }
842 let interlaced = frame.interlace != Interlace::Progressive;
843 let npics = if interlaced { 2 } else { 1 };
844 if interlaced && cfg.height < 2 {
845 return Err(Error::unsupported("interlaced ProRes picture one line tall", "use a progressive frame"));
846 }
847 if let Some(a) = alpha {
848 if cfg.alpha_bits == 0 {
849 return Err(Error::unsupported("an alpha plane", "set EncoderConfig::alpha_bits to 8 or 16"));
850 }
851 if a.width != cfg.width || a.height != cfg.height || a.data.len() < (cfg.height as usize - 1) * a.stride + cfg.width as usize {
852 return Err(Error::unsupported("an alpha plane of another size", "match the picture size"));
853 }
854 }
855 let (w, h) = (cfg.width as usize, cfg.height as usize);
856 let cw = if is_444 { w } else { w.div_ceil(2) };
857 let mb_w = w.div_ceil(16);
858 // Rows of macroblocks per picture: a field is padded up to whole 32-line frame pairs.
859 let mb_h = if interlaced { h.div_ceil(32) } else { h.div_ceil(16) };
860 let scan_table = if interlaced { &INTERLACED_SCAN } else { &PROGRESSIVE_SCAN };
861 let coded_alpha = cfg.alpha_bits != 0;
862 let qmat = cfg.profile.qmats();
863 let mut scan_pos = [0usize; 64];
864 let mut rinv = [[0f32; 64]; 2];
865 for (i, &r) in scan_table.iter().enumerate() {
866 scan_pos[r as usize] = i;
867 rinv[0][i] = 1.0 / f32::from(qmat.0[r as usize]);
868 rinv[1][i] = 1.0 / f32::from(qmat.1[r as usize]);
869 }
870 let g = Geom { is_444, mb_w, pw: [w, cw, cw], ph: [h, h, h] };
871 let pr = Params { g, scan_pos, rinv, rnd: 0.5, alpha: coded_alpha };
872 let threads = cfg.threads;
873
874 let t0 = std::time::Instant::now();
875 // Phase 1: DCT of every slice of every picture (a field is every other line, starting
876 // with the first field in display order), rows in parallel.
877 let first_parity = usize::from(frame.interlace == Interlace::BottomFieldFirst);
878 let mut slices: Vec<SliceCoefs> = Vec::new();
879 for pic in 0..npics {
880 let parity = if interlaced { (first_parity + pic) & 1 } else { 0 };
881 let step = npics;
882 let fh = (h - parity).div_ceil(step);
883 let mut pg = pr.g;
884 pg.ph = [fh; 3];
885 let prp = Params { g: pg, scan_pos: pr.scan_pos, rinv: pr.rinv, rnd: pr.rnd, alpha: pr.alpha };
886 let pl = |p: usize| &frame.planes[p].data[parity * frame.planes[p].stride..];
887 let src = Src {
888 planes: [pl(0), pl(1), pl(2)],
889 strides: [frame.planes[0].stride * step, frame.planes[1].stride * step, frame.planes[2].stride * step],
890 bytes2,
891 fmt_bits,
892 };
893 let asrc = coded_alpha.then(|| {
894 static OPAQUE: [u16; 1] = [0xFFFF];
895 match alpha {
896 Some(a) => AlphaSrc { data: &a.data[parity * a.stride..], stride: a.stride * step, w, h: fh, bits: cfg.alpha_bits },
897 None => AlphaSrc { data: &OPAQUE, stride: 0, w: 1, h: fh, bits: cfg.alpha_bits },
898 }
899 });
900 slices.extend(par_map(mb_h, threads, |r| transform_row(&prp, &src, asrc.as_ref(), r)).into_iter().flatten());
901 }
902 let n_slices = slices.len();
903 let t1 = t0.elapsed();
904
905 // Phase 2: one quantiser for the whole frame (equal step everywhere is the MSE optimum),
906 // the smallest that fits the frame budget, found on a sample of the slices; a fraction
907 // of the slices takes the next finer step so the frame lands on the budget.
908 let (q_coarse, q_fine, frac) = match cfg.qscale {
909 Some(q) => {
910 let q = usize::from(q).clamp(1, MAXQ);
911 (q, q, 0.0)
912 }
913 None => {
914 let mbs = mb_w * mb_h * npics;
915 let bits_per_mb = cfg
916 .bits_per_mb
917 .map_or_else(|| nominal_frame_bytes(cfg.profile, mbs) * 8 / mbs, |b| b as usize);
918 // Tiny pictures: the headers alone would eat Apple's proportional rate.
919 let total = (bits_per_mb * mbs / 8).max(3000usize.saturating_sub(28 * mbs));
920 let budget = total.saturating_sub(8 + 148 + 8 * npics + 2 * n_slices).max(16 * mbs);
921 let budget_f = budget as f64;
922 let (pr_ref, slices_ref) = (&pr, &slices);
923 let cost_at = |stride: usize| {
924 let sample: Vec<usize> = (0..n_slices).step_by(stride).collect();
925 let scale = n_slices as f64 / sample.len() as f64;
926 let chunk = sample.len().div_ceil(threads * 2).max(1);
927 let nchunks = sample.len().div_ceil(chunk);
928 move |q: usize| -> f64 {
929 let parts = par_map(nchunks, threads, |c| {
930 let mut sc = Scratch::new();
931 sample[c * chunk..((c + 1) * chunk).min(sample.len())]
932 .iter()
933 .map(|&i| slice_cost(pr_ref, &mut sc, &slices_ref[i], q))
934 .sum::<usize>()
935 });
936 parts.iter().sum::<usize>() as f64 * scale
937 }
938 };
939 // A cheap sample finds the neighbourhood, a larger one the exact step.
940 let (coarse, _, _) = search_q(&cost_at((n_slices / 24).clamp(1, 40)), budget_f, cfg.profile.start_q());
941 let (hi, lo, costs) = search_q(&cost_at((n_slices / 128).clamp(1, 8)), budget_f, coarse.min(MAXQ));
942 let q = hi.min(MAXQ);
943 if lo >= 1 && lo + 1 == q {
944 // Mix: fraction of slices at the finer step `lo`.
945 let c_hi = costs[&q];
946 let c_lo = costs[&lo];
947 let f = ((budget_f - c_hi) / (c_lo - c_hi)).clamp(0.0, 1.0);
948 (q, lo, f)
949 } else {
950 (q, q, 0.0)
951 }
952 }
953 };
954
955 let t2 = t0.elapsed();
956 // Phase 3: entropy-code the slices.
957 let per_row = row_slices(mb_w).len();
958 let q_of = |i: usize| -> usize {
959 // Bresenham spread of the finer step over the slice index.
960 if q_fine != q_coarse && ((i + 1) as f64 * frac).floor() > (i as f64 * frac).floor() {
961 q_fine
962 } else {
963 q_coarse
964 }
965 };
966 let chunk = per_row.max(1);
967 let nchunks = n_slices.div_ceil(chunk);
968 let parts = par_map(nchunks, threads, |c| -> Result<Vec<Vec<u8>>> {
969 let mut sc = Scratch::new();
970 (c * chunk..((c + 1) * chunk).min(n_slices))
971 .map(|i| write_slice(&pr, &mut sc, &slices[i], q_of(i)))
972 .collect()
973 });
974 let mut all: Vec<Vec<u8>> = Vec::with_capacity(n_slices);
975 for p in parts {
976 all.extend(p?);
977 }
978 if std::env::var_os("EC_TRACE").is_some() { eprintln!("dct {:?} search {:?} write {:?}", t1, t2 - t1, t0.elapsed() - t2); }
979 // Frame.
980 let per_pic = all.len() / npics;
981 let (ql, qc) = cfg.profile.qmats();
982 let hdr_size = 20 + 128;
983 let pic_hdr = 8;
984 let pic_sizes: Vec<usize> = all
985 .chunks(per_pic)
986 .map(|c| pic_hdr + c.len() * 2 + c.iter().map(Vec::len).sum::<usize>())
987 .collect();
988 let total = 8 + hdr_size + pic_sizes.iter().sum::<usize>();
989 let mut f = Vec::with_capacity(total);
990 f.extend_from_slice(&(total as u32).to_be_bytes());
991 f.extend_from_slice(b"icpf");
992 f.extend_from_slice(&(hdr_size as u16).to_be_bytes());
993 f.extend_from_slice(&(u16::from(is_444)).to_be_bytes()); // version: 1 for 4444 as ffmpeg writes
994 f.extend_from_slice(&cfg.creator);
995 f.extend_from_slice(&(cfg.width as u16).to_be_bytes());
996 f.extend_from_slice(&(cfg.height as u16).to_be_bytes());
997 let frame_type: u8 = match frame.interlace {
998 Interlace::Progressive => 0,
999 Interlace::TopFieldFirst => 1,
1000 Interlace::BottomFieldFirst => 2,
1001 };
1002 f.push((if is_444 { 3 << 6 } else { 2 << 6 }) | frame_type << 2);
1003 f.push(0);
1004 f.push(cfg.color.primaries);
1005 f.push(cfg.color.transfer);
1006 f.push(cfg.color.matrix);
1007 f.push(match cfg.alpha_bits {
1008 0 => 0,
1009 8 => 1,
1010 _ => 2,
1011 });
1012 f.push(0);
1013 f.push(3); // both quantisation matrices present
1014 f.extend_from_slice(ql);
1015 f.extend_from_slice(qc);
1016 for (chunk, &pic_size) in all.chunks(per_pic).zip(&pic_sizes) {
1017 f.push((pic_hdr as u8) << 3);
1018 f.extend_from_slice(&(pic_size as u32).to_be_bytes());
1019 f.extend_from_slice(&(chunk.len() as u16).to_be_bytes());
1020 f.push(3 << 4); // 8 macroblocks per slice
1021 for s in chunk {
1022 f.extend_from_slice(&(s.len() as u16).to_be_bytes());
1023 }
1024 for s in chunk {
1025 f.extend_from_slice(s);
1026 }
1027 }
1028 debug_assert_eq!(f.len(), total);
1029 Ok(f)
1030 }
1031}
1032
1033impl Encoder for ProResEncoder {
1034 fn codec_parameters(&self) -> &CodecParameters {
1035 &self.params
1036 }
1037
1038 fn send_frame(&mut self, frame: &Frame) -> Result<()> {
1039 let Frame::Video(v) = frame else {
1040 return Err(Error::unsupported("a non-video frame", "the ProRes encoder takes video"));
1041 };
1042 let data = self.encode(v)?;
1043 let (tb, pts) = match v.pts {
1044 Some(t) => (t.base, Some(t.ticks)),
1045 None => (ec_core::timebase::TimeBase::try_new(1, 1)?, None),
1046 };
1047 let mut p = Packet::new(0, tb, data);
1048 p.pts = pts;
1049 p.dts = pts;
1050 p.flags.keyframe = true;
1051 self.out.push_back(p);
1052 Ok(())
1053 }
1054
1055 fn receive_packet(&mut self) -> Result<Packet> {
1056 match self.out.pop_front() {
1057 Some(p) => Ok(p),
1058 None if self.eof => Err(Error::Eof),
1059 None => Err(Error::NeedMore),
1060 }
1061 }
1062
1063 fn flush(&mut self) -> Result<()> {
1064 self.eof = true;
1065 Ok(())
1066 }
1067}