Repository navigation
Expand file tree
/
Copy pathrender.test.ts
More file actions
1751 lines (1694 loc) · 71.1 KB
/
Copy pathrender.test.ts
File metadata and controls
1751 lines (1694 loc) · 71.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Renders synthetic footage end to end with the pinned FFmpeg, small enough to run in CI.
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
import { test } from "node:test";
import { promisify } from "node:util";
import { COLORS, catalog, type renderOverlays, templateIds } from "@video-editor/effects";
import {
type CropPath,
type FaceBox,
type FramedShot,
loadJson,
type Project,
type ScalePath,
type Source,
validateMediaIndex,
validateProject,
} from "@video-editor/schema";
import { family, fontFile } from "./captions/fonts.ts";
import { buildCaptions, PRESETS, stageFonts } from "./captions/index.ts";
import type { Rgb } from "./colour.ts";
import { ffmpeg, QUIET, run } from "./ffmpeg.ts";
import { everyKind, makeSource, projectOf } from "./fixtures.ts";
import { cropPath } from "./framing.ts";
import { captionFilter, RAW_AUDIO, RAW_VIDEO } from "./graph/encode.ts";
import {
masterAudio,
measureLoudness,
parseMeasurement,
parseTruePeak,
truePeakFilter,
} from "./graph/master.ts";
import { pieceAudio } from "./graph/piece.ts";
import { gradeColour } from "./looks.ts";
import { cutPieces } from "./pieces.ts";
import { limitPeak, render, unrendered } from "./render.ts";
import { loadSources } from "./sources.ts";
import { project as fakeProject, SECOND, scratch } from "./testing.ts";
import { buildTimeline } from "./timeline.ts";
const execFileAsync = promisify(execFile);
const tiny = { aspect: "16:9", width: 160, height: 90, fps: { num: 30, den: 1 } } as const;
const clip = (source: string, start: number, seconds: number): Project["main"][number] => ({
source,
in: Math.round(start * SECOND),
out: Math.round((start + seconds) * SECOND),
});
async function write(dir: string, project: Project): Promise<string> {
const path = join(dir, "project.json");
await writeFile(path, JSON.stringify(project));
return path;
}
/** The left channel of every piece's sound, back to back, before the loudness pass. */
async function pieceSound(dir: string, project: Project): Promise<Float32Array> {
const timeline = buildTimeline(project, await loadSources(project, await write(dir, project)));
const parts: Buffer[] = [];
for (const piece of cutPieces(timeline)) {
const file = join(dir, "piece.f32");
await run(await ffmpeg(), [...pieceAudio(piece, timeline).slice(0, -1), "-y", file]);
parts.push(await readFile(file));
}
const bytes = Buffer.concat(parts);
const stereo = new Float32Array(bytes.buffer, bytes.byteOffset, bytes.length / 4);
return stereo.filter((_, i) => i % 2 === 0);
}
/** A still image source, which has no media index. */
async function still(dir: string, id: string): Promise<Source> {
const path = join(dir, `${id}.png`);
await run(await ffmpeg(), [
...QUIET,
"-f",
"lavfi",
"-i",
"smptebars=s=320x240",
"-frames:v",
"1",
path,
]);
const bytes = await readFile(path);
const sha256 = createHash("sha256").update(bytes).digest("hex");
return { id, kind: "image", path: `${id}.png`, fingerprint: { bytes: bytes.length, sha256 } };
}
/** Frames, samples and stream descriptions of a rendered file, as FFmpeg decodes it. */
async function inspect(file: string) {
const bin = await ffmpeg();
const frames = await run(bin, [
...QUIET,
"-i",
file,
"-map",
"0:v",
"-c",
"copy",
"-f",
"framecrc",
"-",
]);
const pcm = `${file}.f32`;
await run(bin, [...QUIET, "-y", "-i", file, "-map", "0:a", "-ac", "1", "-f", "f32le", pcm]);
const bytes = await readFile(pcm);
const samples = new Float32Array(bytes.buffer, bytes.byteOffset, bytes.length / 4);
const info = await run(bin, ["-hide_banner", "-i", file, "-frames:v", "1", "-f", "null", "-"]);
return {
frames: frames.stdout.split("\n").filter((line) => /^\d/.test(line)).length,
samples,
info: info.stderr,
};
}
/** Each output frame as 8-bit grey, `width` × `height`. */
async function grey(file: string, width: number, height: number): Promise<Uint8Array[]> {
const raw = `${file}.gray`;
await run(await ffmpeg(), [
...QUIET,
"-y",
"-i",
file,
"-f",
"rawvideo",
"-pix_fmt",
"gray",
raw,
]);
const bytes = await readFile(raw);
const size = width * height;
return Array.from({ length: bytes.length / size }, (_, i) =>
bytes.subarray(i * size, (i + 1) * size),
);
}
test("an edit across every kind of source renders every frame and sample exactly", async (t) => {
const dir = await scratch(t, "render-");
const sources: Source[] = [];
for (const spec of everyKind(160, 90, 4)) sources.push(await makeSource(dir, spec));
sources.push(await still(dir, "title"));
const project = projectOf(
sources,
[
clip("a30", 0.513, 0.47),
clip("b25", 1.21, 0.33),
clip("c24", 0.517, 0.42),
clip("d60", 1.33, 0.31),
clip("e-phone", 0.7, 0.44),
clip("f-vfr", 2.05, 0.46),
clip("g-hdr", 1.6, 0.37),
clip("h-mute", 2.5, 0.38),
{ ...clip("a30", 2.31, 0.59), transition: { type: "dissolve", duration: SECOND / 5 } },
clip("i-silent", 1.9, 0.34),
{
...clip("b25", 2.77, 0.51),
transition: { type: "dip", duration: SECOND / 5, color: "#000000" },
},
clip("c24", 3.2, 0.36),
clip("d60", 2.15, 0.42),
clip("title", 0, 0.4),
clip("f-vfr", 0.9, 0.45),
] as Project["main"],
tiny,
);
project.broll = [
{
source: "d60",
in: SECOND,
out: 2 * SECOND,
start: 2 * SECOND,
gainDb: -6,
fade: SECOND / 10,
},
];
const path = await write(dir, project);
const result = await render(path, join(dir, "out", "edit.mp4"));
const timeline = buildTimeline(project, await loadSources(project, path));
assert.equal(result.frames, timeline.frames);
const { frames, samples, info } = await inspect(result.video);
assert.equal(frames, timeline.frames);
// The sound decodes to exactly the picture's length: 1600 samples per 30 fps frame.
assert.equal(samples.length, timeline.frames * 1600);
assert.match(info, /Video: h264 \(High\).*yuv420p\(tv, bt709, progressive\), 160x90/);
assert.match(info, /Audio: aac \(LC\).*48000 Hz, stereo/);
const cuts = JSON.parse(await readFile(result.cuts, "utf8"));
assert.equal(cuts.cuts.length, 14);
assert.deepEqual(
cuts.cuts,
timeline.cuts.map((t) => Number(t.toFixed(6))),
);
assert.equal(result.cuts, join(dir, "out", "edit_cuts.json"));
// The copy beside the video renders the same edit: its paths lead to the same files.
const copy = await loadJson(result.project, validateProject);
assert.equal(result.project, join(dir, "out", "edit.project.json"));
for (const source of copy.sources) {
const path = resolve(dirname(result.project), source.path);
await access(path);
assert.equal(path, join(dir, `${source.id}.${source.kind === "image" ? "png" : "mp4"}`));
}
assert.deepEqual(copy.main, project.main);
});
test("picture and sound stay in step whatever the source's frame rate", async (t) => {
const dir = await scratch(t, "sync-");
// [frame rate, variable, how far the sound may lead or trail the picture]: a frame rate that
// differs from the output's shows each source frame up to one output frame late.
const rates = [
[30, false, 0],
[25, false, 1 / 30],
[30, true, 1 / 30],
] as const;
for (const [fps, variable, tolerance] of rates) {
const id = `marks${fps}${variable ? "v" : ""}`;
// A white frame where each beep starts, 0.6 s into every second.
const flash = "geq=lum='if(gte(mod(T,1),0.599)*lt(mod(T,1),0.62),235,16)':cb=128:cr=128";
const spec = { id, pattern: "color", width: 64, height: 36, fps, seconds: 4, variable };
const source = await makeSource(dir, { ...spec, sound: "beeps", filter: flash });
const project = projectOf([source], [clip(id, 1.13, 1.5)], { ...tiny, width: 64, height: 36 });
const result = await render(await write(dir, project), join(dir, `${id}.out.mp4`));
const picture = await grey(result.video, 64, 36);
const white = picture.findIndex((frame) => (frame[0] ?? 0) > 128);
const { samples } = await inspect(result.video);
const loudest = samples.reduce((max, value) => Math.max(max, Math.abs(value)), 0);
const beep = samples.findIndex((value) => Math.abs(value) > loudest * 0.3);
assert.ok(white > 0 && beep > 0, `${id}: flash at frame ${white}, beep at sample ${beep}`);
const lead = white / 30 - beep / 48000;
assert.ok(lead >= -0.002 && lead <= tolerance + 0.002, `${id}: picture - sound = ${lead} s`);
}
});
test("a clip that starts where its source's picture ends holds the last frame", async (t) => {
const dir = await scratch(t, "held-");
const sources: Source[] = [];
for (const spec of everyKind(64, 36, 3).slice(0, 2)) sources.push(await makeSource(dir, spec));
// a30's last frame starts at 2.967 s; the timeline allows a clip to run past a source's end.
const project = projectOf(sources, [clip("b25", 0, 1), clip("a30", 3, 0.3), clip("b25", 1, 1)], {
...tiny,
width: 64,
height: 36,
});
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const { frames, samples } = await inspect(result.video);
assert.equal(result.frames, 69);
assert.equal(frames, 69);
assert.equal(samples.length, 69 * 1600);
});
test("sound split between pieces joins sample for sample", async (t) => {
const dir = await scratch(t, "seams-");
const [tone, , , , , , , mute] = everyKind(64, 36, 4);
assert.ok(tone && mute);
const talk = { ...tone, id: "talk", noisy: 0.05 };
const sources = [
await makeSource(dir, tone),
await makeSource(dir, mute),
await makeSource(dir, talk),
];
const edit = (main: Project["main"], broll: Project["broll"] = []) => ({
...projectOf(sources, main, { ...tiny, width: 64, height: 36 }),
broll,
});
const sound = (project: Project) => pieceSound(dir, project);
/** The split sound matches the sound decoded in one piece around a seam. */
const joins = (split: Float32Array, whole: Float32Array, seam: number) => {
for (let i = seam - 32; i < seam + 32; i++) {
const error = Math.abs((split[i] ?? 0) - (whole[i] ?? 0));
assert.ok(error < 1e-5, `sample ${i}: ${split[i]} against ${whole[i]}`);
}
};
// In points whose seeks split a sample, so a seek of their own would shift the sound.
const tonal = { source: "a30", in: 20_000, out: 140_000 };
const dissolve = { type: "dissolve", duration: SECOND / 5 } as const;
// The tone's body, then its tail under a dissolve to a clip without sound, which begins with
// the tone at full level; against the tone cut straight to that clip.
joins(
await sound(edit([tonal, { ...clip("h-mute", 0, 1), transition: dissolve }])),
await sound(edit([tonal, clip("h-mute", 0, 1)])),
0.8 * 48_000,
);
// B-roll of the tone across a cut between two clips without sound, against one such clip.
const broll = [{ source: "a30", in: 20_000, out: 140_000, start: SECOND / 2, gainDb: 0 }];
joins(
await sound(edit([clip("h-mute", 0, 1), clip("h-mute", 2, 1)], broll)),
await sound(edit([clip("h-mute", 0, 2)], broll)),
48_000,
);
// The same through every stage of a voice chain, whose filters carry state: each piece runs
// the chain from the clip's first instant, so the tail still joins its body exactly.
const voiced = (main: Project["main"]) => {
const project = edit(main);
project.audio.voice = [{ source: "talk", measurements: { recorded: measured }, chain }];
return project;
};
const talking = { ...tonal, source: "talk" };
joins(
await sound(voiced([talking, { ...clip("h-mute", 0, 1), transition: dissolve }])),
await sound(voiced([talking, clip("h-mute", 0, 1)])),
0.8 * 48_000,
);
});
test("sound from Matroska and WebM lands where vework places it, to the millisecond", async (t) => {
// FFmpeg 7.0 starts these files at the codec priming, 21 ms (AAC) and 7 ms (Opus) before the
// time zero vework's decoder reads; the beeps start 0.6 s into every second of vework's time.
const dir = await scratch(t, "matroska-");
const spec = { pattern: "testsrc2", width: 64, height: 36, fps: 30, seconds: 3 } as const;
for (const container of ["mkv", "webm"] as const) {
const source = await makeSource(dir, { ...spec, id: container, sound: "beeps", container });
// From the file's start, and after a seek: 0.3 s before a beep in both.
for (const start of [0.3, 1.3]) {
const project = projectOf([source], [clip(container, start, 0.6)], {
...tiny,
width: 64,
height: 36,
});
const sound = await pieceSound(dir, project);
const late = sound.findIndex((sample) => Math.abs(sample) > 0.02) - 0.3 * 48_000;
// 1 ms, and the sample the codec blurs the beep's first cycle by. Matroska times packets
// in whole milliseconds, so after a seek FFmpeg can still place Opus up to 1 ms off.
assert.ok(Math.abs(late) <= 49, `${container} from ${start} s: ${late} samples late`);
}
}
});
/** A source's speech as vework would record it, for decisions written by hand. */
const measured = { loudnessLufs: -14, loudnessRangeLu: 3, clippedShare: 0 };
/** Every stage of a voice chain. */
const chain = {
denoise: { attenuationLimitDb: 20 },
dereverb: { amount: 0.5, thresholdDb: -40 },
highpassHz: 80,
eq: [{ type: "peak", frequencyHz: 300, gainDb: -3, q: 1 }],
level: { targetDb: -20, windowSeconds: 3, maxGainDb: 12 },
compressor: { thresholdDb: -20, ratio: 3, attackMs: 10, releaseMs: 120, makeupDb: 2 },
deesser: { frequencyHz: 6000, intensity: 0.4, thresholdDb: -38 },
limiter: { ceilingDb: -9 },
} satisfies NonNullable<Project["audio"]["voice"]>[number]["chain"];
test("a clip's voice chain has settled by its first instant, as it has partway through the source", async (t) => {
const dir = await scratch(t, "settle-");
const spec = { id: "quiet", pattern: "testsrc2", width: 64, height: 36, fps: 30, seconds: 10 };
const source = await makeSource(dir, { ...spec, sound: 220 });
// The tone sits 18 dB under the leveller's target, so it is raised by the whole 12 dB.
const levelled = (start: number, seconds: number) => {
const project = projectOf([source], [clip("quiet", start, seconds)], {
...{ ...tiny, width: 64, height: 36 },
});
const level = { targetDb: -3, windowSeconds: 3, maxGainDb: 12 };
project.audio.voice = [
{ source: "quiet", measurements: { recorded: measured }, chain: { level } },
];
return project;
};
const late = await pieceSound(dir, levelled(6.1, 2));
const early = await pieceSound(dir, levelled(4, 4.1));
/** dB RMS of the 100 ms from `at` seconds. */
const level = (samples: Float32Array, at: number) => {
const from = Math.round(at * 48_000);
const window = samples.subarray(from, from + 4_800);
return 10 * Math.log10(window.reduce((sum, x) => sum + x * x, 0) / window.length);
};
// The same source seconds, 6.4 to 8.1, in both, past the clip's edge fade.
for (let at = 0.3; at < 2; at += 0.1) {
const [a, b] = [level(late, at), level(early, at + 2.1)];
assert.ok(Math.abs(a - b) < 1, `${at.toFixed(1)} s into the clip: ${a} against ${b} dB`);
}
});
test("a voice chain plays the denoised speech with the recording mixed back at its limit", async (t) => {
const dir = await scratch(t, "voice-");
const spec = { id: "talk", pattern: "testsrc2", width: 64, height: 36, fps: 30, seconds: 4 };
const source = await makeSource(dir, { ...spec, sound: 220, noisy: 0.05 });
const plain = projectOf([source], [clip("talk", 0.5, 3)], { ...tiny, width: 64, height: 36 });
const denoised: Project = {
...plain,
audio: {
...plain.audio,
voice: [
{
source: "talk",
measurements: { recorded: measured },
chain: { denoise: { attenuationLimitDb: 20 } },
},
],
},
};
/** The noise between the tones against the tones, in dB. */
const noiseUnderTone = async (project: Project, name: string) => {
const result = await render(await write(dir, project), join(dir, `${name}.mp4`));
const { samples, frames } = await inspect(result.video);
assert.equal(samples.length, frames * 1600);
const power = (from: number, to: number) => {
let sum = 0;
let count = 0;
for (let i = 0; i < samples.length; i++) {
// The clip starts 0.5 s into its source: tones sound 0.25-0.75 s into each source second.
const phase = (i / 48_000 + 0.5) % 1;
if (phase >= from && phase < to) {
sum += (samples[i] ?? 0) ** 2;
count++;
}
}
return sum / count;
};
return 10 * Math.log10(power(0.85, 0.95) / power(0.35, 0.65));
};
const before = await noiseUnderTone(plain, "plain");
const after = await noiseUnderTone(denoised, "denoised");
assert.ok(Math.abs(before - after - 20) < 1.5, `noise fell ${before - after} dB`);
});
test("a chain that denoises mixes the recording back as vework decoded it, from the stem", async (t) => {
// Two decoders' samples need not line up exactly (the renderer places Matroska sound only to
// the millisecond), so the recording the renderer decodes itself need not line up with the
// denoised speech. Here the stem's recording differs from the source's sound outright: the
// render must play the stem's.
const dir = await scratch(t, "stem-");
const spec = { id: "talk", pattern: "testsrc2", width: 64, height: 36, fps: 30, seconds: 4 };
const source = await makeSource(dir, { ...spec, sound: 220, noisy: 0.05 });
const recorded = "0.3*sin(2*PI*1000*t)";
await run(await ffmpeg(), [
...QUIET,
...["-y", "-f", "lavfi", "-i", `aevalsrc='${recorded}|0':s=48000:d=4`],
...["-c:a", "pcm_f32le", join(dir, "talk.voice.wav")],
]);
const project = projectOf([source], [clip("talk", 0.5, 3)], { ...tiny, width: 64, height: 36 });
const denoise = { attenuationLimitDb: 6 };
project.audio.voice = [
{ source: "talk", measurements: { recorded: measured }, chain: { denoise } },
];
const sound = await pieceSound(dir, project);
const kept = 10 ** (-6 / 20);
// Past the clip's edge fades; the clip starts on a whole number of the tone's cycles.
for (let i = 4_800; i < sound.length - 4_800; i++) {
const expected = kept * 0.3 * Math.sin((2 * Math.PI * 1000 * i) / 48_000);
assert.ok(
Math.abs((sound[i] ?? 0) - expected) < 1e-4,
`sample ${i}: ${sound[i]}, not ${expected}`,
);
}
});
test("a chain that denoises fails when the media index has no denoised speech", async (t) => {
const dir = await scratch(t, "no-stem-");
const [spec] = everyKind(64, 36, 2);
assert.ok(spec);
const source = await makeSource(dir, spec);
const project = projectOf([source], [clip(source.id, 0, 1)], { ...tiny, width: 64, height: 36 });
project.audio.voice = [{ source: source.id, measurements: { recorded: measured }, chain }];
await assert.rejects(
render(await write(dir, project), join(dir, "out.mp4")),
/a30: its voice chain denoises, but its media index has no denoised speech/,
);
});
test("rotated phone footage comes out upright", async (t) => {
const dir = await scratch(t, "rotate-");
// Stored landscape, white across its top half, with a display matrix that turns it portrait.
const top = "geq=lum='if(lt(Y,H/2),235,16)':cb=128:cr=128";
const spec = { id: "phone", pattern: "color", width: 64, height: 36, fps: 30, seconds: 2 };
const source = await makeSource(dir, { ...spec, sound: null, filter: top, rotate: true });
const portrait = { aspect: "9:16", width: 36, height: 64, fps: { num: 30, den: 1 } } as const;
const project = projectOf([source], [clip("phone", 0, 1)], portrait);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const [frame] = await grey(result.video, 36, 64);
assert.ok(frame);
const mean = (columns: (x: number) => boolean) => {
const values = [...frame].filter((_, i) => columns(i % 36));
return values.reduce((sum, value) => sum + value, 0) / values.length;
};
// Turned a quarter counter-clockwise, the top of the stored picture is on the left.
assert.ok(mean((x) => x < 14) > 200, "left side white");
assert.ok(mean((x) => x > 22) < 40, "right side black");
});
test("a crop path moves the crop frame by frame, cutting on the exact frame", async (t) => {
const dir = await scratch(t, "path-");
// Grey rising from black on the left to white on the right: a crop's brightness says where it is.
const ramp = "geq=lum='16+219*X/W':cb=128:cr=128";
const spec = { id: "ramp", pattern: "color", width: 320, height: 180, fps: 30, seconds: 2 };
const source = await makeSource(dir, { ...spec, sound: null, filter: ramp });
const portrait = { aspect: "9:16", width: 36, height: 64, fps: { num: 30, den: 1 } } as const;
const w = 9 / 16 / (16 / 9);
const at = (seconds: number, centre: number) => ({
t: Math.round(seconds * SECOND),
rect: { x: centre - w / 2, y: 0, w, h: 1 },
});
// Held, then a pan from 0.2 to 0.8 between 0.2 s and 1 s, held, then a cut to 0.3 at 1.4 s.
const keyframes = [
at(0.2, 0.2),
at(1, 0.8),
{ ...at(1.4, 0.8), t: 1.4 * SECOND - 1 },
at(1.4, 0.3),
];
const main = [{ ...clip("ramp", 0.1, 1.6), framing: { crop: { type: "path", keyframes } } }];
const project = projectOf([source], main as Project["main"], portrait);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const frames = await grey(result.video, 36, 64);
assert.equal(frames.length, 48);
const brightness = frames.map((frame) => frame.reduce((sum, v) => sum + v, 0) / frame.length);
// Grey levels run 0 to 255 across the source; the first frame's offset, a few levels from
// scaling and pixel edges, applies to every frame.
const offset = (brightness[0] ?? 0) - 255 * 0.2;
assert.ok(Math.abs(offset) < 6, `offset ${offset}`);
for (const [k, mean] of brightness.entries()) {
// Output frame k shows source time 0.1 s + k frames.
const time = 0.1 + k / 30;
const centre =
time < 0.2 ? 0.2 : time < 1 ? 0.2 + (0.6 * (time - 0.2)) / 0.8 : time < 1.4 ? 0.8 : 0.3;
assert.ok(Math.abs(mean - offset - 255 * centre) < 1.5, `frame ${k}: ${mean} for ${centre}`);
}
});
test("a crop past the picture shows it whole over a blurred copy, from the exact frame it cuts to", async (t) => {
const dir = await scratch(t, "backdrop-");
const ramp = "geq=lum='16+219*X/W':cb=128:cr=128";
const spec = { id: "ramp", pattern: "color", width: 320, height: 180, fps: 30, seconds: 2 };
const source = await makeSource(dir, { ...spec, sound: null, filter: ramp });
const portrait = { aspect: "9:16", width: 72, height: 128, fps: { num: 30, den: 1 } } as const;
const w = 9 / 16 / (16 / 9);
const h = 1 / w;
// A 9:16 crop in the middle until 1 s, then the whole picture in the middle of the frame.
const keyframes = [
{ t: 0, rect: { x: 0.5 - w / 2, y: 0, w, h: 1 } },
{ t: SECOND - 1, rect: { x: 0.5 - w / 2, y: 0, w, h: 1 } },
{ t: SECOND, rect: { x: 0, y: (1 - h) / 2, w: 1, h } },
];
const main = [{ ...clip("ramp", 0.5, 1), framing: { crop: { type: "path", keyframes } } }];
const project = projectOf([source], main as Project["main"], portrait);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const frames = await grey(result.video, 72, 128);
assert.equal(frames.length, 30);
const pixel = (frame: Uint8Array, x: number, y: number) => frame[y * 72 + x] ?? 0;
for (const [k, frame] of frames.entries()) {
const [left, right] = [pixel(frame, 1, 64), pixel(frame, 70, 64)];
if (k < 15) {
// Output frame k shows 0.5 s + k frames: the crop spans 0.34 to 0.66 of the ramp.
assert.ok(Math.abs(left - 255 * (0.5 - w / 2)) < 12, `frame ${k}: left ${left}`);
assert.ok(Math.abs(right - 255 * (0.5 + w / 2)) < 12, `frame ${k}: right ${right}`);
continue;
}
// The whole ramp across the middle, 40 rows of the 128, and its blurred copy above and below.
assert.ok(left < 20 && right > 235, `frame ${k}: ${left} to ${right}`);
for (const y of [4, 124]) {
const row = Array.from({ length: 72 }, (_, x) => pixel(frame, x, y));
assert.ok(row.every((v) => v > 0) && (row[36] ?? 0) > 60, `frame ${k}, row ${y}: ${row}`);
const steps = row.slice(1).map((v, x) => Math.abs(v - (row[x] ?? 0)));
assert.ok(Math.max(...steps) < 20, `frame ${k}, row ${y} is not smooth: ${row}`);
}
}
});
test("a crop that changes size during a dissolve renders each side of the cut with its own", async (t) => {
const dir = await scratch(t, "dissolve-cut-");
// A white square, 40 pixels wide, in the middle of a black frame.
const square = await makeSource(dir, {
id: "square",
pattern: "color",
filter: "drawbox=x=140:y=70:w=40:h=40:color=white:t=fill",
width: 320,
height: 180,
fps: 30,
seconds: 3,
sound: null,
});
// The second clip comes in over 0.4 s from 1 s of the source, and its crop cuts at 1.1 s to
// twice the picture's size, which shows the picture at half size over its blurred copy.
const keyframes: CropPath["keyframes"] = [
{ t: 1.1 * SECOND - 1, rect: { x: 0, y: 0, w: 1, h: 1 } },
{ t: 1.1 * SECOND, rect: { x: -0.5, y: -0.5, w: 2, h: 2 } },
];
const project = projectOf(
[square],
[
clip("square", 0, 1),
{
...clip("square", 1, 1),
transition: { type: "dissolve", duration: 0.4 * SECOND },
framing: { crop: { type: "path", keyframes } },
},
],
{ ...tiny, width: 320, height: 180 },
);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const picture = await grey(result.video, 320, 180);
assert.equal(picture.length, 48);
const width = (frame: Uint8Array) =>
frame.subarray(90 * 320, 91 * 320).filter((value) => value > 128).length;
assert.equal(width(picture[0] as Uint8Array), 40);
assert.equal(width(picture.at(-1) as Uint8Array), 20);
});
test("a split screen fills its top and bottom halves with their own crops", async (t) => {
const dir = await scratch(t, "halves-");
// Dark on the left half of the picture, light on the right.
const sides = "geq=lum='if(lt(X,W/2),40,220)':cb=128:cr=128";
const spec = { id: "sides", pattern: "color", width: 320, height: 180, fps: 30, seconds: 1 };
const source = await makeSource(dir, { ...spec, sound: null, filter: sides });
const portrait = { aspect: "9:16", width: 72, height: 128, fps: { num: 30, den: 1 } } as const;
// Each half is 72 × 64, 9:8: 0.6 of the picture's height is 0.38 of its width.
const pane = (x: number) => ({ x, y: 0.2, w: 0.6 * (9 / 8) * (9 / 16), h: 0.6 });
const crop = { type: "static", rect: pane(0.05), below: pane(0.55) } as const;
const project = projectOf([source], [{ ...clip("sides", 0, 0.5), framing: { crop } }], portrait);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const frames = await grey(result.video, 72, 128);
assert.equal(frames.length, 15);
for (const frame of frames) {
const mean = (from: number, to: number) =>
frame.subarray(from * 72, to * 72).reduce((sum, v) => sum + v, 0) / ((to - from) * 72);
// Grey levels 40 and 220 of the limited range, in the full range the frames are read in.
const full = (level: number) => ((level - 16) * 255) / 219;
assert.ok(Math.abs(mean(2, 62) - full(40)) < 6, `top ${mean(2, 62)}`);
assert.ok(Math.abs(mean(66, 126) - full(220)) < 6, `bottom ${mean(66, 126)}`);
}
});
test("footage with non-square pixels is cropped where the plan puts the crop", async (t) => {
const dir = await scratch(t, "anamorphic-");
// 16:9 stored in 240 × 180 with 4:3 pixels, grey rising from black on the left to white on the
// right: a column's brightness says where in the source it is.
const ramp = "geq=lum='16+219*X/W':cb=128:cr=128";
const spec = { id: "hdv", pattern: "color", width: 240, height: 180, fps: 30, seconds: 1 };
const source = await makeSource(dir, { ...spec, sound: null, filter: ramp, sar: [4, 3] });
const indexPath = join(dir, "hdv.index.json");
const index = validateMediaIndex(JSON.parse(await readFile(indexPath, "utf8")));
// A face near the left edge, which the crop is pushed against.
const boxes = [0, 0.5].map((t) => ({ t, x: 0.07, y: 0.3, w: 0.06, h: 0.11 }));
const face = { id: 0, boxes: boxes as [FaceBox, ...FaceBox[]] };
const shot: FramedShot = {
start: 0,
end: 1,
layout: "talking_head",
faces: [face],
speakers: [],
};
index.framing = { fps: 5, shots: [shot] };
const portrait = { aspect: "9:16", width: 36, height: 64, fps: { num: 30, den: 1 } } as const;
const crop = cropPath(index, clip("hdv", 0, 1), portrait);
assert.equal(crop?.type, "static");
const rect = crop?.type === "static" ? crop.rect : { x: 0, y: 0, w: 1, h: 1 };
const main = [{ ...clip("hdv", 0, 1), framing: { crop } }];
const project = projectOf([source], main as Project["main"], portrait);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const [frame] = await grey(result.video, 36, 64);
assert.ok(frame);
const column = (x: number) => {
const values = [...frame].filter((_, i) => i % 36 === x);
return values.reduce((sum, value) => sum + value, 0) / values.length;
};
// The outermost columns show the source half an output pixel inside the crop's edges.
const half = rect.w / 36 / 2;
const edges = [column(0), column(35)];
const planned = [255 * (rect.x + half), 255 * (rect.x + rect.w - half)];
for (const [k, edge] of edges.entries()) {
assert.ok(Math.abs(edge - (planned[k] ?? 0)) < 5, `${edges} rendered, ${planned} planned`);
}
});
test("a crop path too long for one command-line argument renders every frame", async (t) => {
const dir = await scratch(t, "dense-path-");
const ramp = "geq=lum='16+219*X/W':cb=128:cr=128";
const spec = { id: "ramp", pattern: "color", width: 320, height: 180, fps: 30, seconds: 11 };
const source = await makeSource(dir, { ...spec, sound: 220, filter: ramp });
const portrait = { aspect: "9:16", width: 36, height: 64, fps: { num: 30, den: 1 } } as const;
const w = 9 / 16 / (16 / 9);
// 3000 keyframes over 10 s, the crop's centre swinging between 0.3 and 0.7 every frame's
// tenth: an expression of well over 128 KiB, Linux's limit for one argument.
const centreAt = (ticks: number) => 0.5 + 0.2 * Math.sin(ticks / 1000);
const keyframes = Array.from({ length: 3000 }, (_, k) => {
const ticks = k * 400;
return { t: ticks, rect: { x: centreAt(ticks) - w / 2, y: 0, w, h: 1 } };
});
const main = [{ ...clip("ramp", 0, 10), framing: { crop: { type: "path", keyframes } } }];
const project = projectOf([source], main as Project["main"], portrait);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const frames = await grey(result.video, 36, 64);
assert.equal(frames.length, 300);
const brightness = frames.map((frame) => frame.reduce((sum, v) => sum + v, 0) / frame.length);
// Frame k reads the path a millisecond (120 ticks) after its time, as the clock reads the
// picture; the first frame gives the offset from scaling and pixel edges.
const offset = (brightness[0] ?? 0) - 255 * centreAt(120);
for (const [k, mean] of brightness.entries()) {
const ticks = k * 4000 + 120;
const before = Math.floor(ticks / 400) * 400;
const centre =
centreAt(before) + ((centreAt(before + 400) - centreAt(before)) * (ticks - before)) / 400;
assert.ok(Math.abs(mean - offset - 255 * centre) < 1.5, `frame ${k}: ${mean} for ${centre}`);
}
});
test("untagged footage keeps its colours, read with the matrix players assume for its size", async (t) => {
const dir = await scratch(t, "matrix-");
// One flat colour, as YUV values without a tag saying which matrix they use.
const flat = "format=yuv420p,geq=lum=63:cb=102:cr=240";
for (const [width, height] of [
[1280, 720],
[640, 360],
] as const) {
const spec = { id: `flat${height}`, pattern: "color", width, height, fps: 30, seconds: 1 };
const source = await makeSource(dir, { ...spec, sound: null, filter: flat });
const output = { ...tiny, width, height };
const project = projectOf([source], [clip(source.id, 0, 0.2)], output);
const result = await render(await write(dir, project), join(dir, `${source.id}.out.mp4`));
const raw = join(dir, `${source.id}.yuv`);
await run(await ffmpeg(), [
...QUIET,
"-i",
result.video,
"-frames:v",
"1",
"-f",
"rawvideo",
"-pix_fmt",
"yuv420p",
raw,
]);
const frame = await readFile(raw);
const size = width * height;
// The output is tagged BT.709: the HD source passes through unchanged, and the SD one,
// read as BT.601, converts.
const yuv = [frame[0], frame[size], frame[size + size / 4]];
if (height === 720) assert.deepEqual(yuv, [63, 102, 240]);
else assert.notDeepEqual(yuv, [63, 102, 240]);
}
});
test("a push-in zooms on exact frames, smoothly and about the centre, across pieces", async (t) => {
const dir = await scratch(t, "push-");
// A white square, 40 pixels wide, in the middle of a black frame.
const square = await makeSource(dir, {
id: "square",
pattern: "color",
filter: "drawbox=x=140:y=70:w=40:h=40:color=white:t=fill",
width: 320,
height: 180,
fps: 30,
seconds: 3,
sound: null,
});
const path = (from: number): ScalePath => ({
type: "path",
keyframes: [
{ t: Math.round(from * SECOND), scale: 1 },
{ t: Math.round((from + 0.6) * SECOND), scale: 1.5 },
],
});
// The dissolve blends the end of the first clip with the start of the second, which shows the
// same picture 0.2 s later in its source at the same scale, so every frame follows one push.
const project = projectOf(
[square],
[
{ ...clip("square", 0, 1), framing: { scale: path(0.3) } },
{
...clip("square", 1, 0.6),
transition: { type: "dissolve", duration: SECOND / 5 },
framing: { scale: path(0.5) },
},
],
{ ...tiny, width: 320, height: 180 },
);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const picture = await grey(result.video, 320, 180);
assert.equal(picture.length, 42);
const eased = (seconds: number) => {
const u = Math.min(1, Math.max(0, (seconds - 0.3) / 0.6));
return 1 + (0.5 * (1 - Math.cos(Math.PI * u))) / 2;
};
for (const [n, frame] of picture.entries()) {
const row = frame.subarray(90 * 320, 91 * 320);
const white = row[160] ?? 0;
const black = row[2] ?? 0;
let width = 0;
let moment = 0;
for (const [x, value] of row.entries()) {
const share = (value - black) / (white - black);
width += share;
moment += share * x;
}
const expected = 40 * eased(n / 30);
assert.ok(
Math.abs(width - expected) < 0.6,
`frame ${n}: ${width} px wide, expected ${expected}`,
);
assert.ok(Math.abs(moment / width - 159.5) < 0.25, `frame ${n}: centred at ${moment / width}`);
}
});
test("a punch-in that steps within a clip changes on the exact frame, each side at its own scale", async (t) => {
const dir = await scratch(t, "step-");
// A white square, 40 pixels wide, in the middle of a black frame.
const square = await makeSource(dir, {
id: "square",
pattern: "color",
filter: "drawbox=x=140:y=70:w=40:h=40:color=white:t=fill",
width: 320,
height: 180,
fps: 30,
seconds: 2,
sound: null,
});
const scale: ScalePath = {
type: "path",
keyframes: [
{ t: SECOND / 2 - 1, scale: 1 },
{ t: SECOND / 2, scale: 1.25 },
],
};
const project = projectOf([square], [{ ...clip("square", 0, 1), framing: { scale } }], {
...tiny,
width: 320,
height: 180,
});
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const picture = await grey(result.video, 320, 180);
assert.equal(picture.length, 30);
for (const [n, frame] of picture.entries()) {
const row = frame.subarray(90 * 320, 91 * 320);
const width = row.filter((value) => value > 128).length;
assert.equal(width, n < 15 ? 40 : 50, `frame ${n}`);
}
});
test("steps and a push-in in one clip at 29.97 fps render every frame, each at its scale", async (t) => {
const dir = await scratch(t, "steps-push-");
// A white square, 40 pixels wide, in the middle of a black frame.
const square = await makeSource(dir, {
id: "square",
pattern: "color",
filter: "drawbox=x=140:y=70:w=40:h=40:color=white:t=fill",
width: 320,
height: 180,
fps: 30000 / 1001,
seconds: 4,
sound: null,
});
const ntsc = { ...tiny, width: 320, height: 180, fps: { num: 30000, den: 1001 } } as const;
// A step to 1.25 at 1 s, a push from 1.25 to 1.325 over 1.5-2 s, and a step back at 2.5 s; and
// a clip of one step.
const pushed: ScalePath = {
type: "path",
keyframes: [
{ t: SECOND - 1, scale: 1 },
{ t: SECOND, scale: 1.25 },
{ t: 1.5 * SECOND, scale: 1.25 },
{ t: 2 * SECOND, scale: 1.325 },
{ t: 2.5 * SECOND - 1, scale: 1.325 },
{ t: 2.5 * SECOND, scale: 1 },
],
};
const stepped: ScalePath = {
type: "path",
keyframes: [
{ t: 3.4 * SECOND - 1, scale: 1 },
{ t: 3.4 * SECOND, scale: 1.25 },
],
};
const project = projectOf(
[square],
[
{ ...clip("square", 0.5, 2.3), framing: { scale: pushed } },
{ ...clip("square", 3, 0.8), framing: { scale: stepped } },
],
ntsc,
);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const picture = await grey(result.video, 320, 180);
const frames = (seconds: number) => Math.round((seconds * 30000) / 1001);
assert.equal(picture.length, frames(2.3) + frames(0.8));
const width = (n: number) =>
(picture[n] as Uint8Array).subarray(90 * 320, 91 * 320).filter((v) => v > 128).length;
// Output frame n of the first clip shows source time 0.5 s + n frames.
const at = (seconds: number) => Math.ceil(((seconds - 0.5) * 30000) / 1001);
assert.equal(width(at(1) - 1), 40);
assert.equal(width(at(1)), 50);
assert.ok(Math.abs(width(at(2.2)) - 53) <= 1, `${width(at(2.2))}`);
assert.equal(width(at(2.5) - 1 + 1), 40);
const second = frames(2.3);
assert.equal(width(second + Math.ceil((0.4 * 30000) / 1001) - 1), 40);
assert.equal(width(second + Math.ceil((0.4 * 30000) / 1001)), 50);
});
test("a punch-in and a push-in about an anchor keep it still on screen", async (t) => {
const dir = await scratch(t, "anchor-");
// A white square, 40 pixels wide, centred at x = 60 of a 320-pixel frame: the anchor.
const square = await makeSource(dir, {
id: "square",
pattern: "color",
filter: "drawbox=x=40:y=70:w=40:h=40:color=white:t=fill",
width: 320,
height: 180,
fps: 30,
seconds: 3,
sound: null,
});
const anchor = { x: 60 / 320, y: 0.5 };
const pushed: ScalePath = {
type: "path",
keyframes: [
{ t: SECOND, scale: 1 },
{ t: Math.round(1.6 * SECOND), scale: 1.5 },
],
};
const project = projectOf(
[square],
[
{ ...clip("square", 0, 1), framing: { scale: 1.25, anchor } },
{ ...clip("square", 1, 2), framing: { scale: pushed, anchor } },
],
{ ...tiny, width: 320, height: 180 },
);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const picture = await grey(result.video, 320, 180);
for (const [n, frame] of picture.entries()) {
const row = frame.subarray(90 * 320, 91 * 320);
let width = 0;
let moment = 0;
for (const [x, value] of row.entries()) {
const share = Math.min(1, Math.max(0, (value - 16) / (235 - 16)));
width += share;
moment += share * x;
}
const centre = moment / width;
assert.ok(Math.abs(centre - 59.5) < 0.6, `frame ${n}: the square is at ${centre}`);
const expected = n < 30 ? 50 : n >= 48 ? 60 : undefined;
if (expected) assert.ok(Math.abs(width - expected) < 1, `frame ${n}: ${width} px wide`);
}
});
test("an edit without any sound still has a silent audio track, left unnormalised", async (t) => {
const dir = await scratch(t, "silent-");
const specs = everyKind(64, 36, 2).filter(
(spec) => spec.sound === null || spec.sound === "silent",
);
const sources = [];
for (const spec of specs) sources.push(await makeSource(dir, spec));
const project = projectOf(
sources,
[clip("h-mute", 0.2, 0.5), clip("i-silent", 0.4, 0.5)] as Project["main"],
{ ...tiny, width: 64, height: 36 },
);
const result = await render(await write(dir, project), join(dir, "out.mp4"));
assert.equal(result.loudness, null);
const { samples, frames } = await inspect(result.video);
assert.equal(frames, 30);
assert.equal(samples.length, 30 * 1600);
assert.ok(samples.every((value) => value === 0));
});
test("a mix louder than loudness normalisation measures is still normalised", async (t) => {
const dir = await scratch(t, "hot-");
const bin = await ffmpeg();
// A full-scale square wave in both channels measures about +3 LUFS.
const square = "sgn(sin(2*PI*440*t))";
const hot = join(dir, "hot.f32");
const lavfi = `aevalsrc='${square}|${square}':s=48000:d=3`;
await run(bin, [...QUIET, "-f", "lavfi", "-i", lavfi, ...RAW_AUDIO, hot]);
const target = { integratedLufs: -14, truePeakDbtp: -1 };
const measure = (file: string) =>
run(bin, [
"-hide_banner",
"-nostats",
...RAW_AUDIO,
"-i",
file,
"-af",
measureLoudness(target),
"-f",
"null",
"-",
]);
const measured = parseMeasurement((await measure(hot)).stderr);
assert.ok(measured.input_i > 0, String(measured.input_i));
const out = join(dir, "master.f32");
const master = masterAudio("", measured, target, 3 * 48_000);
await run(bin, [...QUIET, ...RAW_AUDIO, "-i", hot, "-af", master, ...RAW_AUDIO, out]);
const after = parseMeasurement((await measure(out)).stderr);
assert.ok(Math.abs(after.input_i - target.integratedLufs) < 1, String(after.input_i));
});
test("a noisy mix with sharp transients keeps its true-peak ceiling once encoded", async (t) => {
const dir = await scratch(t, "peaks-");
const source = await makeSource(dir, {
id: "clicks",
pattern: "testsrc2",
width: 64,
height: 36,
fps: 30,
seconds: 8,
sound: "transients",
});
const project = projectOf([source], [clip("clicks", 0, 8)], { ...tiny, width: 64, height: 36 });
const result = await render(await write(dir, project), join(dir, "out.mp4"));
const ceiling = project.audio.loudness.truePeakDbtp;
const log = await run(await ffmpeg(), [