forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.2 MiB74a46ceTahinli3 hours ago4145 commits

encode_video.rs491 lines, 14.7 KiBHistoryRawDownload
1use ec_av1::encode::Picture;
2use ec_av1::encoder::{Av1Encoder, Colour, EncoderConfig as Av1Config, Pyramid, RateTarget};
3use ec_core::color::ContentLight;
4use ec_core::frame::{PixelFormat, Plane, VideoFrame};
5use ec_h264::{Encoder as H264Encoder, EncoderConfig as H264Config, PictureView, Preset as H264Preset};
6use ec_h265::encoder::{Encoder as H265Encoder, EncoderConfig as H265Config, Preset as H265Preset};
7use ec_h265_syntax::sei::MasteringDisplay;
8use ec_h265_syntax::vui::{ColourDescription, VideoSignalType};
9use ec_prores::{AlphaPlane, EncoderConfig as ProresConfig, ProResEncoder, Profile};
10
11use crate::{error, guard, hash};
12
13const WIDTH: usize = 176;
14const HEIGHT: usize = 144;
15const FRAMES: usize = 6;
16const AV1_FRAMES: usize = 8;
17
18const AV1_MODES: [Av1Mode; 4] = [Av1Mode::KeyOnly, Av1Mode::Flat, Av1Mode::Pyramid3, Av1Mode::Pyramid4];
19const AV1_RATES: [RateTarget; 2] = [
20 RateTarget::Quality(40),
21 RateTarget::Bitrate {
22 bits_per_second: 300_000,
23 frames_per_second: 25.0,
24 },
25];
26const AV1_TILES: [(u32, u32); 2] = [(0, 0), (1, 1)];
27const AV1_SIZES: [(usize, usize); 2] = [(176, 144), (151, 91)];
28
29#[derive(Clone, Copy, Debug)]
30enum Av1Mode {
31 KeyOnly,
32 Flat,
33 Pyramid3,
34 Pyramid4,
35}
36
37#[derive(Clone, Copy, Debug)]
38struct Av1Case {
39 mode: Av1Mode,
40 rate: RateTarget,
41 tiles: (u32, u32),
42 screen: bool,
43 w: usize,
44 h: usize,
45 speed: u8,
46}
47
48impl Av1Case {
49 fn name(&self) -> String {
50 let content = if self.screen { "screen" } else { "natural" };
51 format!(
52 "{:?}-{:?}-tiles{}x{}-{content}-{}x{}-s{}",
53 self.mode, self.rate, self.tiles.0, self.tiles.1, self.w, self.h, self.speed
54 )
55 }
56}
57
58fn case_name(codec: &str, config: &str, index: usize) -> String {
59 format!("encode_video/{codec}/{config}/{index}")
60}
61
62fn outcome(case: &str, result: Result<Vec<u8>, String>) {
63 match result {
64 Ok(bytes) => hash(case, &bytes),
65 Err(err) => error(case, err),
66 }
67}
68
69fn clamp8(v: i32) -> u8 {
70 v.clamp(0, 255) as u8
71}
72
73fn natural_frame(w: usize, h: usize, t: usize) -> Vec<u8> {
74 let mut seed = ((w * 1_000_003 + h * 1009 + t * 7919) as u64) | 1;
75 let mut noise = || {
76 seed = seed
77 .wrapping_mul(6364136223846793005)
78 .wrapping_add(1442695040888963407);
79 ((seed >> 33) % 9) as i32 - 4
80 };
81 let sq = w / 4;
82 let x0 = (4 * t) % (w - sq);
83 let y0 = (2 * t) % (h - sq);
84 let mut out = Vec::with_capacity(w * h * 3 / 2);
85 for y in 0..h {
86 for x in 0..w {
87 let inside = (x0..x0 + sq).contains(&x) && (y0..y0 + sq).contains(&y);
88 let base: i32 = if inside {
89 230
90 } else {
91 (x * 200 / w + y * 40 / h) as i32
92 };
93 out.push(clamp8(base + noise()));
94 }
95 }
96 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
97 for _ in 0..ch {
98 for x in 0..cw {
99 out.push(clamp8(64 + (x * 128 / cw) as i32 + noise()));
100 }
101 }
102 for y in 0..ch {
103 for _ in 0..cw {
104 out.push(clamp8(64 + (y * 128 / ch) as i32 + noise()));
105 }
106 }
107 out
108}
109
110fn screen_frame(w: usize, h: usize, t: usize) -> Vec<u8> {
111 let mut out = Vec::with_capacity(w * h * 3 / 2);
112 for y in 0..h {
113 for x in 0..w {
114 let v = if (y + t).is_multiple_of(6) {
115 16
116 } else if ((x + 2 * t) / 8 + y / 8).is_multiple_of(3) {
117 235
118 } else {
119 81
120 };
121 out.push(v);
122 }
123 }
124 let chroma = w.div_ceil(2) * h.div_ceil(2) * 2;
125 out.resize(w * h + chroma, 128);
126 out
127}
128
129fn split(buf: &[u8], w: usize, h: usize) -> (&[u8], &[u8], &[u8]) {
130 let (ys, cs) = (w * h, w.div_ceil(2) * h.div_ceil(2));
131 (&buf[..ys], &buf[ys..ys + cs], &buf[ys + cs..ys + 2 * cs])
132}
133
134fn resample(src: &[u8], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<u8> {
135 let mut out = Vec::with_capacity(dw * dh);
136 for y in 0..dh {
137 for x in 0..dw {
138 out.push(src[(y * sh / dh) * sw + x * sw / dw]);
139 }
140 }
141 out
142}
143
144fn to_bytes(samples: &[u8], bits: u32) -> Vec<u8> {
145 if bits == 8 {
146 return samples.to_vec();
147 }
148 samples
149 .iter()
150 .flat_map(|&s| (u16::from(s) << (bits - 8)).to_le_bytes())
151 .collect()
152}
153
154fn frame_in(format: PixelFormat, w: usize, h: usize, buf: &[u8]) -> Result<VideoFrame, String> {
155 let (y, u, v) = split(buf, w, h);
156 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
157 let src = [(y, w, h), (u, cw, ch), (v, cw, ch)];
158 let bits = format.bits_per_component();
159 let bytes = format.bytes_per_component();
160 let mut planes = Vec::new();
161 for ((s, sw, sh), (row, rows)) in src.iter().zip(format.plane_geometry(w as u32, h as u32)) {
162 let data = to_bytes(&resample(s, *sw, *sh, row / bytes, rows), bits);
163 planes.push(Plane::new(data, row));
164 }
165 VideoFrame::try_new(format, w as u32, h as u32, planes).map_err(|e| e.to_string())
166}
167
168fn alpha_plane(w: usize, h: usize, t: usize) -> AlphaPlane {
169 AlphaPlane {
170 width: w as u32,
171 height: h as u32,
172 stride: w,
173 data: (0..w * h).map(|i| ((i * 257 + t * 4099) % 65536) as u16).collect(),
174 }
175}
176
177fn h264_config(
178 preset: H264Preset,
179 cabac: bool,
180 t8: bool,
181 qp: i32,
182 bitrate: u32,
183 threads: usize,
184) -> H264Config {
185 let mut cfg = H264Config::new(WIDTH as u32, HEIGHT as u32);
186 cfg.preset = preset;
187 cfg.cabac = cabac;
188 cfg.transform_8x8 = t8;
189 cfg.qp = qp;
190 cfg.bitrate = bitrate;
191 cfg.threads = threads;
192 cfg.gop_size = 4;
193 cfg
194}
195
196fn h264_stream(cfg: H264Config) -> Result<Vec<u8>, String> {
197 let mut enc = H264Encoder::new(cfg).map_err(|e| e.to_string())?;
198 let mut out = Vec::new();
199 for t in 0..FRAMES {
200 let buf = natural_frame(WIDTH, HEIGHT, t);
201 let (y, u, v) = split(&buf, WIDTH, HEIGHT);
202 let view = PictureView::i420(WIDTH as u32, HEIGHT as u32, y, u, v);
203 let pic = enc.encode(&view).map_err(|e| e.to_string())?;
204 out.extend_from_slice(&pic.au);
205 }
206 Ok(out)
207}
208
209fn h264() {
210 let mut index = 0;
211 for preset in [H264Preset::Fast, H264Preset::Balanced] {
212 for cabac in [true, false] {
213 for t8 in [true, false] {
214 for (qp, bitrate) in [(20, 0), (36, 0), (26, 400_000)] {
215 for threads in [1, 2, 4] {
216 index += 1;
217 let config = format!(
218 "{preset:?}-cabac{cabac}-t8{t8}-qp{qp}-br{bitrate}-th{threads}"
219 );
220 let case = case_name("h264", &config, index);
221 guard(&case, || {
222 let cfg = h264_config(preset, cabac, t8, qp, bitrate, threads);
223 outcome(&case, h264_stream(cfg));
224 });
225 }
226 }
227 }
228 }
229 }
230}
231
232fn h265_config(
233 preset: H265Preset,
234 bit10: bool,
235 keyint: usize,
236 threads: usize,
237 ctb: usize,
238 hdr: bool,
239) -> H265Config {
240 let mut cfg = H265Config::new(WIDTH as u32, HEIGHT as u32);
241 cfg.speed = preset;
242 cfg.bit_depth = if bit10 { 10 } else { 8 };
243 cfg.keyint = keyint;
244 cfg.threads = threads;
245 cfg.ctb_size = ctb;
246 if hdr {
247 cfg.video_signal_type = Some(VideoSignalType {
248 video_format: 5,
249 video_full_range_flag: false,
250 colour_description: Some(ColourDescription {
251 colour_primaries: 9,
252 transfer_characteristics: 16,
253 matrix_coeffs: 9,
254 }),
255 });
256 cfg.chroma_sample_loc = Some((2, 2));
257 cfg.mastering_display = Some(MasteringDisplay {
258 display_primaries: [(13250, 34500), (7500, 3000), (34000, 16000)],
259 white_point: (15635, 16450),
260 max_luminance: 10_000_000,
261 min_luminance: 50,
262 });
263 cfg.content_light = ContentLight {
264 max_cll: Some(1000.0),
265 max_fall: Some(400.0),
266 ..ContentLight::default()
267 };
268 }
269 cfg
270}
271
272fn h265_stream(cfg: H265Config) -> Result<Vec<u8>, String> {
273 let format = if cfg.bit_depth == 10 {
274 PixelFormat::I010
275 } else {
276 PixelFormat::I420
277 };
278 let mut frames = Vec::new();
279 for t in 0..FRAMES {
280 frames.push(frame_in(format, WIDTH, HEIGHT, &natural_frame(WIDTH, HEIGHT, t))?);
281 }
282 let enc = H265Encoder::new(cfg).map_err(|e| e.to_string())?;
283 let pics = enc.encode_sequence(&frames).map_err(|e| e.to_string())?;
284 Ok(pics.iter().flat_map(|p| p.au.clone()).collect())
285}
286
287fn h265() {
288 let mut index = 0;
289 for preset in [H265Preset::Default, H265Preset::Fast, H265Preset::Faster] {
290 for bit10 in [false, true] {
291 for keyint in [1, 30] {
292 for threads in [1, 4] {
293 for ctb in [32, 64] {
294 for hdr in [false, true] {
295 index += 1;
296 let config = format!(
297 "{preset:?}-{}bit-keyint{keyint}-th{threads}-ctb{ctb}-hdr{hdr}",
298 if bit10 { 10 } else { 8 }
299 );
300 let case = case_name("h265", &config, index);
301 guard(&case, || {
302 let cfg = h265_config(preset, bit10, keyint, threads, ctb, hdr);
303 outcome(&case, h265_stream(cfg));
304 });
305 }
306 }
307 }
308 }
309 }
310 }
311}
312
313fn pyramid(mode: Av1Mode) -> Pyramid {
314 let (mini_gop, quarter) = match mode {
315 Av1Mode::Pyramid4 => (8, Some(-4)),
316 _ => (4, None),
317 };
318 Pyramid {
319 mini_gop,
320 mid_q_offset: Some(-8),
321 quarter_q_offset: quarter,
322 ..Pyramid::default()
323 }
324}
325
326fn av1_picture(c: &Av1Case, t: usize) -> Picture {
327 let buf = if c.screen {
328 screen_frame(c.w, c.h, t)
329 } else {
330 natural_frame(c.w, c.h, t)
331 };
332 let (y, u, v) = split(&buf, c.w, c.h);
333 let wide = |p: &[u8]| p.iter().map(|&s| u16::from(s)).collect::<Vec<u16>>();
334 Picture {
335 width: c.w,
336 height: c.h,
337 y: wide(y),
338 u: wide(u),
339 v: wide(v),
340 }
341}
342
343fn av1_stream(c: &Av1Case) -> Result<Vec<u8>, String> {
344 ec_av1::speed::set_speed(c.speed);
345 let gop = if matches!(c.mode, Av1Mode::KeyOnly) { 1 } else { 8 };
346 let mut cfg = Av1Config::new(c.w, c.h, 100, gop, Colour::default());
347 cfg.tile_cols_log2 = c.tiles.0;
348 cfg.tile_rows_log2 = c.tiles.1;
349 let built = match c.mode {
350 Av1Mode::KeyOnly | Av1Mode::Flat => Av1Encoder::with_rate_target(cfg, c.rate),
351 Av1Mode::Pyramid3 | Av1Mode::Pyramid4 => {
352 Av1Encoder::with_pyramid_and_rate_target(cfg, pyramid(c.mode), c.rate)
353 }
354 };
355 let mut enc = built.map_err(|e| e.to_string())?;
356 let mut out = Vec::new();
357 for t in 0..AV1_FRAMES {
358 let pic = av1_picture(c, t);
359 for packet in enc.encode_frames(&pic).map_err(|e| e.to_string())? {
360 out.extend_from_slice(&packet.data);
361 }
362 }
363 for packet in enc.flush().map_err(|e| e.to_string())? {
364 out.extend_from_slice(&packet.data);
365 }
366 Ok(out)
367}
368
369fn av1_cases() -> Vec<Av1Case> {
370 let mut cases = Vec::new();
371 for mode in AV1_MODES {
372 for rate in AV1_RATES {
373 for tiles in AV1_TILES {
374 for screen in [false, true] {
375 for (w, h) in AV1_SIZES {
376 cases.push(Av1Case {
377 mode,
378 rate,
379 tiles,
380 screen,
381 w,
382 h,
383 speed: 0,
384 });
385 }
386 }
387 }
388 }
389 }
390 for mode in AV1_MODES {
391 for speed in 0..=10 {
392 cases.push(Av1Case {
393 mode,
394 rate: AV1_RATES[0],
395 tiles: (1, 1),
396 screen: true,
397 w: AV1_SIZES[1].0,
398 h: AV1_SIZES[1].1,
399 speed,
400 });
401 if speed > 0 {
402 cases.push(Av1Case {
403 mode,
404 rate: AV1_RATES[0],
405 tiles: (0, 0),
406 screen: false,
407 w: WIDTH,
408 h: HEIGHT,
409 speed,
410 });
411 }
412 }
413 }
414 cases
415}
416
417fn av1() {
418 for (i, c) in av1_cases().iter().enumerate() {
419 let case = case_name("av1", &c.name(), i + 1);
420 guard(&case, || outcome(&case, av1_stream(c)));
421 }
422}
423
424fn prores_stream(
425 profile: Profile,
426 format: PixelFormat,
427 qscale: Option<u8>,
428 threads: usize,
429 alpha_bits: u8,
430) -> Result<Vec<u8>, String> {
431 let mut cfg = ProresConfig::new(profile, WIDTH as u32, HEIGHT as u32);
432 cfg.threads = threads;
433 cfg.qscale = qscale;
434 cfg.alpha_bits = alpha_bits;
435 let enc = ProResEncoder::new(cfg).map_err(|e| e.to_string())?;
436 let mut out = Vec::new();
437 for t in 0..FRAMES {
438 let frame = frame_in(format, WIDTH, HEIGHT, &natural_frame(WIDTH, HEIGHT, t))?;
439 let alpha = (alpha_bits > 0).then(|| alpha_plane(WIDTH, HEIGHT, t));
440 let bytes = enc
441 .encode_with_alpha(&frame, alpha.as_ref())
442 .map_err(|e| e.to_string())?;
443 out.extend_from_slice(&bytes);
444 }
445 Ok(out)
446}
447
448fn prores() {
449 let mut index = 0;
450 for profile in [
451 Profile::Proxy,
452 Profile::Lt,
453 Profile::Standard,
454 Profile::Hq,
455 Profile::P4444,
456 Profile::P4444Xq,
457 ] {
458 let formats = if profile.is_444() {
459 [PixelFormat::I444, PixelFormat::I412]
460 } else {
461 [PixelFormat::I422, PixelFormat::I210]
462 };
463 let alphas: &[u8] = if profile.is_444() { &[0, 16] } else { &[0] };
464 for format in formats {
465 for qscale in [None, Some(8)] {
466 for threads in [1, 4] {
467 for &alpha_bits in alphas {
468 index += 1;
469 let config = format!(
470 "{profile:?}-{format:?}-q{qscale:?}-th{threads}-a{alpha_bits}"
471 );
472 let case = case_name("prores", &config, index);
473 guard(&case, || {
474 outcome(
475 &case,
476 prores_stream(profile, format, qscale, threads, alpha_bits),
477 );
478 });
479 }
480 }
481 }
482 }
483 }
484}
485
486pub fn run() {
487 h264();
488 h265();
489 av1();
490 prores();
491}