@open-take/compositor 0.5.3 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdp-CzT5BKNY.js +3 -0
- package/dist/cdp-QXbQfXna.js +373 -0
- package/dist/cdp-QXbQfXna.js.map +1 -0
- package/dist/index.d.ts +4327 -195
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +26282 -160
- package/dist/index.js.map +1 -1
- package/dist/server-841PMF2H.js +163 -0
- package/dist/server-841PMF2H.js.map +1 -0
- package/dist/server-C2aVv4-t.js +3 -0
- package/kit/audio.mjs +2366 -0
- package/kit/camera.js +587 -0
- package/kit/cursor.js +264 -0
- package/kit/cut.js +427 -0
- package/kit/draw.js +346 -0
- package/kit/look.js +589 -0
- package/kit/map.js +170 -0
- package/kit/media.js +3568 -0
- package/kit/motion.js +1115 -0
- package/kit/seams.js +1006 -0
- package/kit/stage.js +923 -0
- package/kit/time.js +812 -0
- package/kit/world.js +1072 -0
- package/package.json +7 -3
- package/src/ffmpeg.ts +63 -0
- package/src/film/beats.ts +1285 -0
- package/src/film/carry.ts +221 -0
- package/src/film/changes.ts +330 -0
- package/src/film/check.ts +996 -0
- package/src/film/clock.ts +2530 -0
- package/src/film/components-probe.ts +809 -0
- package/src/film/components.ts +1566 -0
- package/src/film/frames.ts +389 -0
- package/src/film/gallery.ts +3276 -0
- package/src/film/kit.ts +515 -0
- package/src/film/layout.ts +701 -0
- package/src/film/listen.ts +1979 -0
- package/src/film/look.ts +3829 -0
- package/src/film/materials.ts +976 -0
- package/src/film/moving.ts +248 -0
- package/src/film/part-files.ts +729 -0
- package/src/film/picture.ts +74 -0
- package/src/film/probe-text.ts +843 -0
- package/src/film/probe.ts +3456 -0
- package/src/film/provenance.ts +596 -0
- package/src/film/render.ts +2447 -0
- package/src/film/report.ts +1631 -0
- package/src/film/sheet.ts +156 -0
- package/src/film/study-declared.ts +123 -0
- package/src/film/study-picture.ts +791 -0
- package/src/film/study-sound.ts +416 -0
- package/src/film/study.ts +864 -0
- package/src/film/tuning.ts +155 -0
- package/src/film/viewer.ts +174 -0
- package/src/html/cdp.ts +575 -0
- package/src/html/server.ts +208 -0
- package/src/index.ts +202 -0
- package/src/launch-render.ts +3 -2
- package/src/math.ts +3 -3
- package/src/mjpeg-matroska.ts +228 -0
- package/src/render.ts +6 -4
- package/src/state-diff.ts +215 -0
- package/src/state-index.ts +99 -0
- package/src/types.ts +59 -1
- package/starter/PLAN.md +84 -0
- package/starter/START.md +460 -0
- package/starter/lib/anim.js +760 -0
- package/starter/lib/devices.js +1402 -0
- package/starter/lib/handoff.js +421 -0
- package/starter/lib/hud.js +1879 -0
- package/starter/lib/measure.mjs +154 -0
- package/starter/lib/moves.js +1095 -0
- package/starter/lib/palette.mjs +803 -0
- package/starter/lib/physics-seeds.mjs +198 -0
- package/starter/lib/physics.js +738 -0
- package/starter/lib/sampler.mjs +242 -0
- package/starter/lib/solid.js +727 -0
- package/starter/lib/space.js +1227 -0
- package/starter/lib/swarm.js +1398 -0
- package/starter/reference/motion.md +276 -0
- package/starter/reference/structure.md +466 -0
- package/starter/reference/travel/motion.md +433 -0
- package/starter/reference/travel/sound.md +241 -0
- package/starter/reference/travel/structure.md +518 -0
- package/starter/samples/NOTICE.txt +55 -0
- package/starter/samples/celli/celli_24_1.opus +0 -0
- package/starter/samples/celli/celli_24_3.opus +0 -0
- package/starter/samples/celli/celli_28_1.opus +0 -0
- package/starter/samples/celli/celli_28_3.opus +0 -0
- package/starter/samples/celli/celli_31_1.opus +0 -0
- package/starter/samples/celli/celli_31_3.opus +0 -0
- package/starter/samples/celli/celli_35_1.opus +0 -0
- package/starter/samples/celli/celli_35_3.opus +0 -0
- package/starter/samples/celli/celli_38_1.opus +0 -0
- package/starter/samples/celli/celli_38_3.opus +0 -0
- package/starter/samples/celli/celli_41_1.opus +0 -0
- package/starter/samples/celli/celli_41_3.opus +0 -0
- package/starter/samples/celli/celli_45_1.opus +0 -0
- package/starter/samples/celli/celli_45_3.opus +0 -0
- package/starter/samples/celli/celli_48_1.opus +0 -0
- package/starter/samples/celli/celli_48_3.opus +0 -0
- package/starter/samples/celli/celli_52_1.opus +0 -0
- package/starter/samples/celli/celli_52_3.opus +0 -0
- package/starter/samples/celli/celli_55_1.opus +0 -0
- package/starter/samples/celli/celli_55_3.opus +0 -0
- package/starter/samples/celli/celli_59_1.opus +0 -0
- package/starter/samples/celli/celli_59_3.opus +0 -0
- package/starter/samples/celli/celli_62_1.opus +0 -0
- package/starter/samples/celli/celli_62_3.opus +0 -0
- package/starter/samples/celli/celli_65_1.opus +0 -0
- package/starter/samples/celli/celli_65_3.opus +0 -0
- package/starter/samples/crash/crash_f_1.flac +0 -0
- package/starter/samples/crash/crash_fff_1.flac +0 -0
- package/starter/samples/ebass/ebass_0_x.flac +0 -0
- package/starter/samples/ebass/ebass_10_x.flac +0 -0
- package/starter/samples/ebass/ebass_11_x.flac +0 -0
- package/starter/samples/ebass/ebass_1_x.flac +0 -0
- package/starter/samples/ebass/ebass_2_x.flac +0 -0
- package/starter/samples/ebass/ebass_3_x.flac +0 -0
- package/starter/samples/ebass/ebass_4_x.flac +0 -0
- package/starter/samples/ebass/ebass_5_x.flac +0 -0
- package/starter/samples/ebass/ebass_6_x.flac +0 -0
- package/starter/samples/ebass/ebass_7_x.flac +0 -0
- package/starter/samples/ebass/ebass_8_x.flac +0 -0
- package/starter/samples/ebass/ebass_9_x.flac +0 -0
- package/starter/samples/ek_clap/ek_clap_1_1.flac +0 -0
- package/starter/samples/ek_hat/ek_hat_1_1.flac +0 -0
- package/starter/samples/ek_hat/ek_hat_1_2.flac +0 -0
- package/starter/samples/ek_kick/ek_kick_1_1.flac +0 -0
- package/starter/samples/ek_kick/ek_kick_1_2.flac +0 -0
- package/starter/samples/glock/glock_67_x.flac +0 -0
- package/starter/samples/glock/glock_72_x.flac +0 -0
- package/starter/samples/glock/glock_79_x.flac +0 -0
- package/starter/samples/glock/glock_84_x.flac +0 -0
- package/starter/samples/glock/glock_91_x.flac +0 -0
- package/starter/samples/glock/glock_96_x.flac +0 -0
- package/starter/samples/harp/harp_101_f.opus +0 -0
- package/starter/samples/harp/harp_28_f.opus +0 -0
- package/starter/samples/harp/harp_31_mp.opus +0 -0
- package/starter/samples/harp/harp_35_mf.opus +0 -0
- package/starter/samples/harp/harp_38_mf.opus +0 -0
- package/starter/samples/harp/harp_41_mf.opus +0 -0
- package/starter/samples/harp/harp_45_mf.opus +0 -0
- package/starter/samples/harp/harp_48_mf.opus +0 -0
- package/starter/samples/harp/harp_52_mf.opus +0 -0
- package/starter/samples/harp/harp_55_mf.opus +0 -0
- package/starter/samples/harp/harp_59_mf.opus +0 -0
- package/starter/samples/harp/harp_62_mf.opus +0 -0
- package/starter/samples/harp/harp_65_mf.opus +0 -0
- package/starter/samples/harp/harp_69_mf.opus +0 -0
- package/starter/samples/harp/harp_72_mf.opus +0 -0
- package/starter/samples/harp/harp_76_mf.opus +0 -0
- package/starter/samples/harp/harp_79_mf.opus +0 -0
- package/starter/samples/harp/harp_83_mf.opus +0 -0
- package/starter/samples/harp/harp_86_mf.opus +0 -0
- package/starter/samples/harp/harp_89_mf.opus +0 -0
- package/starter/samples/harp/harp_93_mf.opus +0 -0
- package/starter/samples/harp/harp_95_mf.opus +0 -0
- package/starter/samples/harp/harp_98_f.opus +0 -0
- package/starter/samples/manifest.json +2951 -0
- package/starter/samples/marimba/marimba_29_x.flac +0 -0
- package/starter/samples/marimba/marimba_36_x.flac +0 -0
- package/starter/samples/marimba/marimba_43_x.flac +0 -0
- package/starter/samples/marimba/marimba_47_x.flac +0 -0
- package/starter/samples/marimba/marimba_53_x.flac +0 -0
- package/starter/samples/marimba/marimba_60_x.flac +0 -0
- package/starter/samples/marimba/marimba_67_x.flac +0 -0
- package/starter/samples/marimba/marimba_71_x.flac +0 -0
- package/starter/samples/marimba/marimba_77_x.flac +0 -0
- package/starter/samples/marimba/marimba_84_x.flac +0 -0
- package/starter/samples/piano/piano_102_12.opus +0 -0
- package/starter/samples/piano/piano_102_16.opus +0 -0
- package/starter/samples/piano/piano_102_4.opus +0 -0
- package/starter/samples/piano/piano_102_8.opus +0 -0
- package/starter/samples/piano/piano_105_12.opus +0 -0
- package/starter/samples/piano/piano_105_16.opus +0 -0
- package/starter/samples/piano/piano_105_4.opus +0 -0
- package/starter/samples/piano/piano_105_8.opus +0 -0
- package/starter/samples/piano/piano_108_12.opus +0 -0
- package/starter/samples/piano/piano_108_16.opus +0 -0
- package/starter/samples/piano/piano_108_4.opus +0 -0
- package/starter/samples/piano/piano_108_8.opus +0 -0
- package/starter/samples/piano/piano_21_12.opus +0 -0
- package/starter/samples/piano/piano_21_16.opus +0 -0
- package/starter/samples/piano/piano_21_4.opus +0 -0
- package/starter/samples/piano/piano_21_8.opus +0 -0
- package/starter/samples/piano/piano_24_12.opus +0 -0
- package/starter/samples/piano/piano_24_16.opus +0 -0
- package/starter/samples/piano/piano_24_4.opus +0 -0
- package/starter/samples/piano/piano_24_8.opus +0 -0
- package/starter/samples/piano/piano_27_12.opus +0 -0
- package/starter/samples/piano/piano_27_16.opus +0 -0
- package/starter/samples/piano/piano_27_4.opus +0 -0
- package/starter/samples/piano/piano_27_8.opus +0 -0
- package/starter/samples/piano/piano_30_12.opus +0 -0
- package/starter/samples/piano/piano_30_16.opus +0 -0
- package/starter/samples/piano/piano_30_4.opus +0 -0
- package/starter/samples/piano/piano_30_8.opus +0 -0
- package/starter/samples/piano/piano_33_12.opus +0 -0
- package/starter/samples/piano/piano_33_16.opus +0 -0
- package/starter/samples/piano/piano_33_4.opus +0 -0
- package/starter/samples/piano/piano_33_8.opus +0 -0
- package/starter/samples/piano/piano_36_12.opus +0 -0
- package/starter/samples/piano/piano_36_16.opus +0 -0
- package/starter/samples/piano/piano_36_4.opus +0 -0
- package/starter/samples/piano/piano_36_8.opus +0 -0
- package/starter/samples/piano/piano_39_12.opus +0 -0
- package/starter/samples/piano/piano_39_16.opus +0 -0
- package/starter/samples/piano/piano_39_4.opus +0 -0
- package/starter/samples/piano/piano_39_8.opus +0 -0
- package/starter/samples/piano/piano_42_12.opus +0 -0
- package/starter/samples/piano/piano_42_16.opus +0 -0
- package/starter/samples/piano/piano_42_4.opus +0 -0
- package/starter/samples/piano/piano_42_8.opus +0 -0
- package/starter/samples/piano/piano_45_12.opus +0 -0
- package/starter/samples/piano/piano_45_16.opus +0 -0
- package/starter/samples/piano/piano_45_4.opus +0 -0
- package/starter/samples/piano/piano_45_8.opus +0 -0
- package/starter/samples/piano/piano_48_12.opus +0 -0
- package/starter/samples/piano/piano_48_16.opus +0 -0
- package/starter/samples/piano/piano_48_4.opus +0 -0
- package/starter/samples/piano/piano_48_8.opus +0 -0
- package/starter/samples/piano/piano_51_12.opus +0 -0
- package/starter/samples/piano/piano_51_16.opus +0 -0
- package/starter/samples/piano/piano_51_4.opus +0 -0
- package/starter/samples/piano/piano_51_8.opus +0 -0
- package/starter/samples/piano/piano_54_12.opus +0 -0
- package/starter/samples/piano/piano_54_16.opus +0 -0
- package/starter/samples/piano/piano_54_4.opus +0 -0
- package/starter/samples/piano/piano_54_8.opus +0 -0
- package/starter/samples/piano/piano_57_12.opus +0 -0
- package/starter/samples/piano/piano_57_16.opus +0 -0
- package/starter/samples/piano/piano_57_4.opus +0 -0
- package/starter/samples/piano/piano_57_8.opus +0 -0
- package/starter/samples/piano/piano_60_12.opus +0 -0
- package/starter/samples/piano/piano_60_16.opus +0 -0
- package/starter/samples/piano/piano_60_4.opus +0 -0
- package/starter/samples/piano/piano_60_8.opus +0 -0
- package/starter/samples/piano/piano_63_12.opus +0 -0
- package/starter/samples/piano/piano_63_16.opus +0 -0
- package/starter/samples/piano/piano_63_4.opus +0 -0
- package/starter/samples/piano/piano_63_8.opus +0 -0
- package/starter/samples/piano/piano_66_12.opus +0 -0
- package/starter/samples/piano/piano_66_16.opus +0 -0
- package/starter/samples/piano/piano_66_4.opus +0 -0
- package/starter/samples/piano/piano_66_8.opus +0 -0
- package/starter/samples/piano/piano_69_12.opus +0 -0
- package/starter/samples/piano/piano_69_16.opus +0 -0
- package/starter/samples/piano/piano_69_4.opus +0 -0
- package/starter/samples/piano/piano_69_8.opus +0 -0
- package/starter/samples/piano/piano_72_12.opus +0 -0
- package/starter/samples/piano/piano_72_16.opus +0 -0
- package/starter/samples/piano/piano_72_4.opus +0 -0
- package/starter/samples/piano/piano_72_8.opus +0 -0
- package/starter/samples/piano/piano_75_12.opus +0 -0
- package/starter/samples/piano/piano_75_16.opus +0 -0
- package/starter/samples/piano/piano_75_4.opus +0 -0
- package/starter/samples/piano/piano_75_8.opus +0 -0
- package/starter/samples/piano/piano_78_12.opus +0 -0
- package/starter/samples/piano/piano_78_16.opus +0 -0
- package/starter/samples/piano/piano_78_4.opus +0 -0
- package/starter/samples/piano/piano_78_8.opus +0 -0
- package/starter/samples/piano/piano_81_12.opus +0 -0
- package/starter/samples/piano/piano_81_16.opus +0 -0
- package/starter/samples/piano/piano_81_4.opus +0 -0
- package/starter/samples/piano/piano_81_8.opus +0 -0
- package/starter/samples/piano/piano_84_12.opus +0 -0
- package/starter/samples/piano/piano_84_16.opus +0 -0
- package/starter/samples/piano/piano_84_4.opus +0 -0
- package/starter/samples/piano/piano_84_8.opus +0 -0
- package/starter/samples/piano/piano_87_12.opus +0 -0
- package/starter/samples/piano/piano_87_16.opus +0 -0
- package/starter/samples/piano/piano_87_4.opus +0 -0
- package/starter/samples/piano/piano_87_8.opus +0 -0
- package/starter/samples/piano/piano_90_12.opus +0 -0
- package/starter/samples/piano/piano_90_16.opus +0 -0
- package/starter/samples/piano/piano_90_4.opus +0 -0
- package/starter/samples/piano/piano_90_8.opus +0 -0
- package/starter/samples/piano/piano_93_12.opus +0 -0
- package/starter/samples/piano/piano_93_16.opus +0 -0
- package/starter/samples/piano/piano_93_4.opus +0 -0
- package/starter/samples/piano/piano_93_8.opus +0 -0
- package/starter/samples/piano/piano_96_12.opus +0 -0
- package/starter/samples/piano/piano_96_16.opus +0 -0
- package/starter/samples/piano/piano_96_4.opus +0 -0
- package/starter/samples/piano/piano_96_8.opus +0 -0
- package/starter/samples/piano/piano_99_12.opus +0 -0
- package/starter/samples/piano/piano_99_16.opus +0 -0
- package/starter/samples/piano/piano_99_4.opus +0 -0
- package/starter/samples/piano/piano_99_8.opus +0 -0
- package/starter/samples/piano/piano_rel_102_x.opus +0 -0
- package/starter/samples/piano/piano_rel_105_x.opus +0 -0
- package/starter/samples/piano/piano_rel_108_x.opus +0 -0
- package/starter/samples/piano/piano_rel_21_x.opus +0 -0
- package/starter/samples/piano/piano_rel_24_x.opus +0 -0
- package/starter/samples/piano/piano_rel_27_x.opus +0 -0
- package/starter/samples/piano/piano_rel_30_x.opus +0 -0
- package/starter/samples/piano/piano_rel_33_x.opus +0 -0
- package/starter/samples/piano/piano_rel_36_x.opus +0 -0
- package/starter/samples/piano/piano_rel_39_x.opus +0 -0
- package/starter/samples/piano/piano_rel_42_x.opus +0 -0
- package/starter/samples/piano/piano_rel_45_x.opus +0 -0
- package/starter/samples/piano/piano_rel_48_x.opus +0 -0
- package/starter/samples/piano/piano_rel_51_x.opus +0 -0
- package/starter/samples/piano/piano_rel_54_x.opus +0 -0
- package/starter/samples/piano/piano_rel_57_x.opus +0 -0
- package/starter/samples/piano/piano_rel_60_x.opus +0 -0
- package/starter/samples/piano/piano_rel_63_x.opus +0 -0
- package/starter/samples/piano/piano_rel_66_x.opus +0 -0
- package/starter/samples/piano/piano_rel_69_x.opus +0 -0
- package/starter/samples/piano/piano_rel_72_x.opus +0 -0
- package/starter/samples/piano/piano_rel_75_x.opus +0 -0
- package/starter/samples/piano/piano_rel_78_x.opus +0 -0
- package/starter/samples/piano/piano_rel_81_x.opus +0 -0
- package/starter/samples/piano/piano_rel_84_x.opus +0 -0
- package/starter/samples/piano/piano_rel_87_x.opus +0 -0
- package/starter/samples/piano/piano_rel_90_x.opus +0 -0
- package/starter/samples/piano/piano_rel_93_x.opus +0 -0
- package/starter/samples/piano/piano_rel_96_x.opus +0 -0
- package/starter/samples/piano/piano_rel_99_x.opus +0 -0
- package/starter/samples/pizz/pizz_24_2.flac +0 -0
- package/starter/samples/pizz/pizz_28_2.flac +0 -0
- package/starter/samples/pizz/pizz_31_2.flac +0 -0
- package/starter/samples/pizz/pizz_35_2.flac +0 -0
- package/starter/samples/pizz/pizz_38_2.flac +0 -0
- package/starter/samples/pizz/pizz_41_2.flac +0 -0
- package/starter/samples/pizz/pizz_45_2.flac +0 -0
- package/starter/samples/pizz/pizz_48_2.flac +0 -0
- package/starter/samples/pizz/pizz_52_2.flac +0 -0
- package/starter/samples/pizz/pizz_57_2.flac +0 -0
- package/starter/samples/pizz/pizz_60_2.flac +0 -0
- package/starter/samples/pizz/pizz_64_2.flac +0 -0
- package/starter/samples/pizz/pizz_67_2.flac +0 -0
- package/starter/samples/pizz/pizz_71_2.flac +0 -0
- package/starter/samples/pizz/pizz_74_2.flac +0 -0
- package/starter/samples/pk_hat/pk_hat_2_1.flac +0 -0
- package/starter/samples/pk_hat/pk_hat_2_2.flac +0 -0
- package/starter/samples/pk_hat/pk_hat_6_1.flac +0 -0
- package/starter/samples/pk_hat/pk_hat_6_2.flac +0 -0
- package/starter/samples/pk_kick/pk_kick_3_1.flac +0 -0
- package/starter/samples/pk_kick/pk_kick_3_2.flac +0 -0
- package/starter/samples/pk_kick/pk_kick_7_1.flac +0 -0
- package/starter/samples/pk_kick/pk_kick_7_2.flac +0 -0
- package/starter/samples/pk_ohat/pk_ohat_3_1.flac +0 -0
- package/starter/samples/pk_ohat/pk_ohat_3_2.flac +0 -0
- package/starter/samples/pk_ohat/pk_ohat_6_1.flac +0 -0
- package/starter/samples/pk_ohat/pk_ohat_6_2.flac +0 -0
- package/starter/samples/pk_rim/pk_rim_2_1.flac +0 -0
- package/starter/samples/pk_rim/pk_rim_2_2.flac +0 -0
- package/starter/samples/pk_rim/pk_rim_5_1.flac +0 -0
- package/starter/samples/pk_rim/pk_rim_5_2.flac +0 -0
- package/starter/samples/pk_snare/pk_snare_3_1.flac +0 -0
- package/starter/samples/pk_snare/pk_snare_3_2.flac +0 -0
- package/starter/samples/pk_snare/pk_snare_7_1.flac +0 -0
- package/starter/samples/pk_snare/pk_snare_7_2.flac +0 -0
- package/starter/samples/shaker/shaker_1_1.flac +0 -0
- package/starter/samples/shaker/shaker_2_1.flac +0 -0
- package/starter/samples/snap/snap_r_1.flac +0 -0
- package/starter/samples/snap/snap_r_2.flac +0 -0
- package/starter/samples/snap/snap_r_3.flac +0 -0
- package/starter/samples/snap/snap_r_4.flac +0 -0
- package/starter/samples/snap/snap_r_5.flac +0 -0
- package/starter/samples/snap/snap_r_6.flac +0 -0
- package/starter/samples/tom/tom_3_1.flac +0 -0
- package/starter/samples/tom/tom_3_2.flac +0 -0
- package/starter/samples/tom/tom_4_1.flac +0 -0
- package/starter/samples/tom/tom_4_2.flac +0 -0
- package/starter/samples/vibes/vibes_41_1.opus +0 -0
- package/starter/samples/vibes/vibes_41_2.opus +0 -0
- package/starter/samples/vibes/vibes_45_1.opus +0 -0
- package/starter/samples/vibes/vibes_45_2.opus +0 -0
- package/starter/samples/vibes/vibes_48_1.opus +0 -0
- package/starter/samples/vibes/vibes_48_2.opus +0 -0
- package/starter/samples/vibes/vibes_52_1.opus +0 -0
- package/starter/samples/vibes/vibes_52_2.opus +0 -0
- package/starter/samples/vibes/vibes_55_1.opus +0 -0
- package/starter/samples/vibes/vibes_55_2.opus +0 -0
- package/starter/samples/vibes/vibes_59_1.opus +0 -0
- package/starter/samples/vibes/vibes_59_2.opus +0 -0
- package/starter/samples/vibes/vibes_62_1.opus +0 -0
- package/starter/samples/vibes/vibes_62_2.opus +0 -0
- package/starter/samples/vibes/vibes_65_1.opus +0 -0
- package/starter/samples/vibes/vibes_65_2.opus +0 -0
- package/starter/samples/vibes/vibes_69_1.opus +0 -0
- package/starter/samples/vibes/vibes_69_2.opus +0 -0
- package/starter/samples/vibes/vibes_72_1.opus +0 -0
- package/starter/samples/vibes/vibes_72_2.opus +0 -0
- package/starter/samples/vibes/vibes_76_1.opus +0 -0
- package/starter/samples/vibes/vibes_76_2.opus +0 -0
- package/starter/samples/violas/violas_36_1.opus +0 -0
- package/starter/samples/violas/violas_36_2.opus +0 -0
- package/starter/samples/violas/violas_38_1.opus +0 -0
- package/starter/samples/violas/violas_38_2.opus +0 -0
- package/starter/samples/violas/violas_40_1.opus +0 -0
- package/starter/samples/violas/violas_40_2.opus +0 -0
- package/starter/samples/violas/violas_43_1.opus +0 -0
- package/starter/samples/violas/violas_43_2.opus +0 -0
- package/starter/samples/violas/violas_47_1.opus +0 -0
- package/starter/samples/violas/violas_47_2.opus +0 -0
- package/starter/samples/violas/violas_50_1.opus +0 -0
- package/starter/samples/violas/violas_50_2.opus +0 -0
- package/starter/samples/violas/violas_53_1.opus +0 -0
- package/starter/samples/violas/violas_53_2.opus +0 -0
- package/starter/samples/violas/violas_57_1.opus +0 -0
- package/starter/samples/violas/violas_57_2.opus +0 -0
- package/starter/samples/violas/violas_60_1.opus +0 -0
- package/starter/samples/violas/violas_60_2.opus +0 -0
- package/starter/samples/violas/violas_64_1.opus +0 -0
- package/starter/samples/violas/violas_64_2.opus +0 -0
- package/starter/samples/violas/violas_67_1.opus +0 -0
- package/starter/samples/violas/violas_67_2.opus +0 -0
- package/starter/samples/violas/violas_71_1.opus +0 -0
- package/starter/samples/violas/violas_71_2.opus +0 -0
- package/starter/samples/violas/violas_74_1.opus +0 -0
- package/starter/samples/violas/violas_74_2.opus +0 -0
- package/starter/samples/violins/violins_43_1.opus +0 -0
- package/starter/samples/violins/violins_43_2.opus +0 -0
- package/starter/samples/violins/violins_45_1.opus +0 -0
- package/starter/samples/violins/violins_45_2.opus +0 -0
- package/starter/samples/violins/violins_47_1.opus +0 -0
- package/starter/samples/violins/violins_47_2.opus +0 -0
- package/starter/samples/violins/violins_50_1.opus +0 -0
- package/starter/samples/violins/violins_50_2.opus +0 -0
- package/starter/samples/violins/violins_54_1.opus +0 -0
- package/starter/samples/violins/violins_54_2.opus +0 -0
- package/starter/samples/violins/violins_57_1.opus +0 -0
- package/starter/samples/violins/violins_57_2.opus +0 -0
- package/starter/samples/violins/violins_60_1.opus +0 -0
- package/starter/samples/violins/violins_60_2.opus +0 -0
- package/starter/samples/violins/violins_64_1.opus +0 -0
- package/starter/samples/violins/violins_64_2.opus +0 -0
- package/starter/samples/violins/violins_67_1.opus +0 -0
- package/starter/samples/violins/violins_67_2.opus +0 -0
- package/starter/samples/violins/violins_71_1.opus +0 -0
- package/starter/samples/violins/violins_71_2.opus +0 -0
- package/starter/samples/violins/violins_74_1.opus +0 -0
- package/starter/samples/violins/violins_74_2.opus +0 -0
- package/starter/samples/woodblock/woodblock_f_1.flac +0 -0
- package/starter/samples/woodblock/woodblock_f_2.flac +0 -0
|
@@ -0,0 +1,2447 @@
|
|
|
1
|
+
// `open-take film render`: any web page → a master MP4.
|
|
2
|
+
//
|
|
3
|
+
// The film is the author's own page — open-take decides nothing about how it
|
|
4
|
+
// looks or sounds. This file only performs it: serves the page, drives the film
|
|
5
|
+
// clock (clock.ts) in W headless Chromes, and turns what they draw into a
|
|
6
|
+
// 1080p60 H.264 master with the page's own soundtrack.
|
|
7
|
+
//
|
|
8
|
+
// Motion blur is measured, not guessed: before rendering, every frame's shutter
|
|
9
|
+
// (180°, centred on the frame time) is probed for how far anything visible
|
|
10
|
+
// travels across it, and the frame gets one sample per SPACING_PX of that
|
|
11
|
+
// travel (1 when nothing moves, at most MAX_SAMPLES). The samples are averaged
|
|
12
|
+
// in linear light and dithered back to 8 bits, so a moving edge becomes a
|
|
13
|
+
// smear rather than a strobe and a still frame passes through untouched.
|
|
14
|
+
//
|
|
15
|
+
// Pipeline per worker: seek → JPEG screenshot → (MJPEG in Matroska) ffmpeg
|
|
16
|
+
// decoder → raw RGB → shutter average → ffmpeg x264 chunk. The chunks are
|
|
17
|
+
// joined without re-encoding, each placed at its first frame's own time (not
|
|
18
|
+
// where its container says the one before ends), and the soundtrack is muxed on.
|
|
19
|
+
//
|
|
20
|
+
// Beside the film goes <film>.events.json (see FilmEvents): what the page says
|
|
21
|
+
// happens when (window.__film.events), its curves sampled once per frame in
|
|
22
|
+
// the render loop itself (window.__film.curves), and the cuts — for the score,
|
|
23
|
+
// which places its sounds from it. One curve is the picture's own:
|
|
24
|
+
// "picture.energy", how much the picture changes into each frame, read from
|
|
25
|
+
// the master once it is encoded (as `film probe` reads it).
|
|
26
|
+
|
|
27
|
+
import { type ChildProcess, spawn } from "node:child_process";
|
|
28
|
+
import { existsSync, statSync } from "node:fs";
|
|
29
|
+
import { copyFile, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
30
|
+
import { cpus, tmpdir } from "node:os";
|
|
31
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
32
|
+
import { resolveFfmpeg, resolveFfprobe, runTool, SRGB_TAG_ARGS, SRGB_TAGS } from "../ffmpeg";
|
|
33
|
+
import { type HtmlBrowser, launchHtmlBrowser } from "../html/cdp";
|
|
34
|
+
import { serveDirectory } from "../html/server";
|
|
35
|
+
import { jpegDimensions, matroskaCluster, matroskaHead } from "../mjpeg-matroska";
|
|
36
|
+
import { type FilmMark, type FilmPageInfo, type TextCause, filmClockSource, filmMarks } from "./clock";
|
|
37
|
+
import { frameStore, type VideoFrames } from "./frames";
|
|
38
|
+
import { fileEnergy, fileGrey, findCuts, frameEnergy } from "./probe";
|
|
39
|
+
|
|
40
|
+
/** the shutter is open for this fraction of the frame interval (180°) */
|
|
41
|
+
const SHUTTER_FRACTION = 0.5;
|
|
42
|
+
/** one blur sample per this many px an edge travels while the shutter is open */
|
|
43
|
+
const SPACING_PX = 3;
|
|
44
|
+
const MAX_SAMPLES = 16;
|
|
45
|
+
const DEFAULT_SIZE = { width: 1920, height: 1080 } as const;
|
|
46
|
+
/** frames per re-renderable piece (3 s at 60 fps) */
|
|
47
|
+
const PIECE_FRAMES = 180;
|
|
48
|
+
/** a piece is tried again this many times after Chrome dies or hangs */
|
|
49
|
+
const PIECE_RETRIES = 2;
|
|
50
|
+
|
|
51
|
+
/** Chrome died, hung or lost its socket — worth a fresh Chrome. An error the
|
|
52
|
+
* film itself threw is not: it would throw again. */
|
|
53
|
+
const browserTrouble = (e: Error): boolean =>
|
|
54
|
+
!/page error:|page threw:|film clock: cannot go back|asked for files that are not there/.test(
|
|
55
|
+
e.message,
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
export type FilmProgress = { phase: "probe" | "render"; done: number; total: number };
|
|
59
|
+
|
|
60
|
+
export type FilmFinePlan = {
|
|
61
|
+
seconds: number;
|
|
62
|
+
supersample: number;
|
|
63
|
+
ranges: { from: number; to: number }[];
|
|
64
|
+
/** text near the middle of the probe's moving text speeds, by frame count */
|
|
65
|
+
causes: { element: string; frames: number }[];
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export type FilmRenderOptions = {
|
|
69
|
+
/** the film: an .html file, or a directory holding index.html */
|
|
70
|
+
page: string;
|
|
71
|
+
/** the MP4 to write */
|
|
72
|
+
out: string;
|
|
73
|
+
chromePath: string;
|
|
74
|
+
/** the directory served to the page (its URLs resolve inside it); default:
|
|
75
|
+
* the working directory when the page is inside it, else the page's folder */
|
|
76
|
+
root?: string;
|
|
77
|
+
/** CSS px the page lays out at; default the page's __film, else 1920×1080 */
|
|
78
|
+
width?: number;
|
|
79
|
+
height?: number;
|
|
80
|
+
fps?: number;
|
|
81
|
+
/** seconds; default the page's __film.duration (or __duration) */
|
|
82
|
+
duration?: number;
|
|
83
|
+
/** render only [from, to) seconds */
|
|
84
|
+
from?: number;
|
|
85
|
+
to?: number;
|
|
86
|
+
/** a soundtrack file; null for none; default the page's __film.audio */
|
|
87
|
+
audio?: string | null;
|
|
88
|
+
/** measured motion blur; default on (off in drafts) */
|
|
89
|
+
blur?: boolean;
|
|
90
|
+
/** half size, 30 fps, no blur, fast encode — for looking, not for delivery */
|
|
91
|
+
draft?: boolean;
|
|
92
|
+
/** draw every frame at this many times the pixels each way and scale it down
|
|
93
|
+
* to the film's size. Chrome puts each glyph on a whole device pixel, so text
|
|
94
|
+
* in a slow zoom or drift steps instead of gliding; finer pixels make the
|
|
95
|
+
* steps finer. Unset, the frames where the page's text moves under a device
|
|
96
|
+
* pixel a frame are drawn at FINE_SUPERSAMPLE and the rest at the film's
|
|
97
|
+
* size; a number draws every frame at it (1: none). Ignored in drafts. */
|
|
98
|
+
supersample?: number;
|
|
99
|
+
/** keep the page's `will-change` hints. By default they are dropped while
|
|
100
|
+
* rendering: Chrome draws a will-change layer once, at the size it has
|
|
101
|
+
* then, and scales that picture, so a layer the camera enlarges shows soft
|
|
102
|
+
* text (at a density the frame is not drawn finer at) — dropping the hint
|
|
103
|
+
* redraws it sharp at every size. */
|
|
104
|
+
keepLayers?: boolean;
|
|
105
|
+
workers?: number;
|
|
106
|
+
onProgress?: (p: FilmProgress) => void;
|
|
107
|
+
/** the automatic supersampling plan, after probing and before rendering */
|
|
108
|
+
onFine?: (plan: FilmFinePlan) => void;
|
|
109
|
+
onConsole?: (level: string, text: string) => void;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
export type FilmRenderResult = {
|
|
113
|
+
out: string;
|
|
114
|
+
mode: FilmPageInfo["mode"];
|
|
115
|
+
/** output pixel size */
|
|
116
|
+
width: number;
|
|
117
|
+
/** stretches drawn finer than the rest because the page's text moved under
|
|
118
|
+
* a device pixel a frame there (film seconds, on the page's timeline), and
|
|
119
|
+
* how finely; none when --supersample was given or in a draft */
|
|
120
|
+
fine: { from: number; to: number }[];
|
|
121
|
+
fineCauses: FilmFinePlan["causes"];
|
|
122
|
+
/** window.__bake.hash, the same in every page the render opened; null
|
|
123
|
+
* when the page publishes none */
|
|
124
|
+
bake: string | null;
|
|
125
|
+
fineSupersample: number;
|
|
126
|
+
/** moves where what ends up framed does not head straight for its place
|
|
127
|
+
* (see turnsBack); null when the frames were not probed */
|
|
128
|
+
turnsBack: TurnBack[] | null;
|
|
129
|
+
height: number;
|
|
130
|
+
fps: number;
|
|
131
|
+
frames: number;
|
|
132
|
+
/** screenshots taken (a blurred frame takes several) */
|
|
133
|
+
samples: number;
|
|
134
|
+
durationS: number;
|
|
135
|
+
/** the first frame rendered, and the whole film's length in frames */
|
|
136
|
+
startFrame: number;
|
|
137
|
+
filmFrames: number;
|
|
138
|
+
wallMs: number;
|
|
139
|
+
warnings: string[];
|
|
140
|
+
/** the film's events file (<out without its extension>.events.json), when one was written */
|
|
141
|
+
events?: string;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
/** One thing that happens in the film, as the page declares it: in seconds of
|
|
145
|
+
* page time, with where on the stage (CSS px) and how hard (0..1) if it says. */
|
|
146
|
+
export type FilmEvent = {
|
|
147
|
+
t: number;
|
|
148
|
+
/** what it is: "click", "key", "land", "cut", "hidden-cut", "mark", or any word of the page's */
|
|
149
|
+
kind: string;
|
|
150
|
+
x?: number;
|
|
151
|
+
y?: number;
|
|
152
|
+
force?: number;
|
|
153
|
+
label?: string;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/** One stretch of the film as the page means it (kit/time.js `segment`): in
|
|
157
|
+
* seconds of page time, every other field the page's own free words;
|
|
158
|
+
* `handoff` is how it hands over to what comes next, at `to`. "hidden-cut"
|
|
159
|
+
* declares a cut under motion at `to`; "lift" says a layer moves on its
|
|
160
|
+
* own over the span, which can look like jumps or a camera turning back. */
|
|
161
|
+
export type FilmSegment = {
|
|
162
|
+
from: number;
|
|
163
|
+
to: number;
|
|
164
|
+
label?: string;
|
|
165
|
+
hold?: boolean;
|
|
166
|
+
handoff?: string;
|
|
167
|
+
seam?: Record<string, string | number>;
|
|
168
|
+
/** what lives through the boundary at `to`: a CSS selector, or "(a
|
|
169
|
+
* function)" — followed across it as the curves `carry@<to>:…` */
|
|
170
|
+
carry?: string;
|
|
171
|
+
/** a CSS selector, or a subject's name in the curves */
|
|
172
|
+
subject?: string;
|
|
173
|
+
sound?: string;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
/** Something the film uses that someone else made, and on what terms
|
|
177
|
+
* (kit/time.js `credit`, or window.__film.credits): every field the page's
|
|
178
|
+
* own free words, for the record only — nothing checks or acts on it. */
|
|
179
|
+
export type FilmCredit = {
|
|
180
|
+
what?: string;
|
|
181
|
+
by?: string;
|
|
182
|
+
licence?: string;
|
|
183
|
+
url?: string;
|
|
184
|
+
/** the attribution line as it should appear, if one must */
|
|
185
|
+
text?: string;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
/** Where something on screen comes from (kit/time.js `source`, or
|
|
189
|
+
* window.__film.sources): a part of components.json, the live page it shows
|
|
190
|
+
* on, or a note ("demo", "illustrative") — the page's own word, for the
|
|
191
|
+
* record; `film probe` sets it beside the film's text, nothing checks it. */
|
|
192
|
+
export type FilmSource = {
|
|
193
|
+
/** what on screen it covers: the text as shown, or words for it */
|
|
194
|
+
label: string;
|
|
195
|
+
/** a part of components.json, "<state>:<element id>" */
|
|
196
|
+
ref?: string;
|
|
197
|
+
/** which of the part's values */
|
|
198
|
+
field?: string;
|
|
199
|
+
/** the components.json it was read from, as the page fetched it */
|
|
200
|
+
file?: string;
|
|
201
|
+
url?: string;
|
|
202
|
+
note?: string;
|
|
203
|
+
/** the strings on screen it covers, beside the label */
|
|
204
|
+
text?: string[];
|
|
205
|
+
/** the film's elements whose text it covers (CSS) */
|
|
206
|
+
selector?: string;
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/** <film>.events.json: what the score reads to put its sounds where the
|
|
210
|
+
* picture is. Times are page time (s). */
|
|
211
|
+
export type FilmEvents = {
|
|
212
|
+
version: 1;
|
|
213
|
+
/** the whole film (s), whatever range was rendered */
|
|
214
|
+
duration: number;
|
|
215
|
+
fps: number;
|
|
216
|
+
/** [from, to) s when only part of the film was rendered */
|
|
217
|
+
range?: [number, number];
|
|
218
|
+
/** window.__film.events(), in time order; [] when the page has none */
|
|
219
|
+
events: FilmEvent[];
|
|
220
|
+
/** every hard cut: declared ∪ detected, merged when less than half a frame apart */
|
|
221
|
+
cuts: number[];
|
|
222
|
+
/** the page's events of kind "cut" */
|
|
223
|
+
declaredCuts: number[];
|
|
224
|
+
/** the first frame of a new picture, where the blur probe found one half of a
|
|
225
|
+
* frame's shutter changed and the other did not, and the encoded picture
|
|
226
|
+
* jumps there as a cut does (≥ 12 % of the frame changed at once, standing
|
|
227
|
+
* far over the frames around it — `film probe`'s hard cut); the other
|
|
228
|
+
* splits are `switches`. Found only inside a shutter (half of each frame's
|
|
229
|
+
* time), and not at all in a render without blur (a draft) */
|
|
230
|
+
detectedCuts: number[];
|
|
231
|
+
/** the instants the blur probe split a frame's shutter at that the picture
|
|
232
|
+
* does not show as a cut: less than a cut's share of the frame changed at
|
|
233
|
+
* once, or the change did not stand out from the frames around it (a word,
|
|
234
|
+
* a number or one part swapped; something switched inside a fast push). The
|
|
235
|
+
* frame is still exposed on one side there; nothing reads them as cuts.
|
|
236
|
+
* Absent in files written before it, and where the picture was not read
|
|
237
|
+
* (every split is then in detectedCuts) */
|
|
238
|
+
switches?: number[];
|
|
239
|
+
/** window.__bake.hash of the page that drew it: a range put into this
|
|
240
|
+
* master must have been drawn from the same bake */
|
|
241
|
+
bake?: string;
|
|
242
|
+
/** window.__film.curves(t) once per output frame: rows[i][j] is names[j] at
|
|
243
|
+
* t0 + i·dt; null where the page gave no number. Beside the page's own,
|
|
244
|
+
* "picture.energy" (PICTURE_ENERGY): how much the picture changes into the
|
|
245
|
+
* frame — the mean grey difference from the frame before, 0..1, as `film
|
|
246
|
+
* probe` measures it; null on a range's first frame (nothing before it) */
|
|
247
|
+
curves: { names: string[]; t0: number; dt: number; rows: (number | null)[][] };
|
|
248
|
+
/** window.__film.segments(), by `from` — the page's beat sheet; [] when it has none */
|
|
249
|
+
segments: FilmSegment[];
|
|
250
|
+
/** window.__film.credits (a list, or a function that gives one), as the page
|
|
251
|
+
* gave it; [] when it has none. Information only */
|
|
252
|
+
credits: FilmCredit[];
|
|
253
|
+
/** window.__film.sources (a list, or a function that gives one), as the
|
|
254
|
+
* page gave it; [] when it has none. Information only */
|
|
255
|
+
sources: FilmSource[];
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
/** where a film's events file goes: beside it, `film.mp4` → `film.events.json` */
|
|
259
|
+
export function eventsPathFor(out: string): string {
|
|
260
|
+
const file = resolve(out);
|
|
261
|
+
const dot = file.lastIndexOf(".");
|
|
262
|
+
return `${dot > Math.max(file.lastIndexOf("/"), file.lastIndexOf("\\")) ? file.slice(0, dot) : file}.events.json`;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
type Film = {
|
|
266
|
+
width: number;
|
|
267
|
+
height: number;
|
|
268
|
+
fps: number;
|
|
269
|
+
scale: number;
|
|
270
|
+
f0: number;
|
|
271
|
+
f1: number;
|
|
272
|
+
/** the whole film's length in frames, whatever range is rendered */
|
|
273
|
+
total: number;
|
|
274
|
+
audio: string | null;
|
|
275
|
+
blur: boolean;
|
|
276
|
+
marks: FilmMark[];
|
|
277
|
+
warnings: string[];
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
/** The MP4 metadata key a rendered film carries for `film check`. In the file
|
|
281
|
+
* itself rather than beside it, so it goes wherever the film is copied and a
|
|
282
|
+
* render that drops a mark cannot leave a stale one behind. */
|
|
283
|
+
export const FILM_TAG = "open_take_film";
|
|
284
|
+
|
|
285
|
+
/** What the film carries under FILM_TAG: where on the page's timeline its
|
|
286
|
+
* first frame is (a render --from), the size the page was laid out at, and
|
|
287
|
+
* the page's marks, in page time. */
|
|
288
|
+
export type FilmRecord = { from: number; width: number; height: number; marks: FilmMark[] };
|
|
289
|
+
|
|
290
|
+
const inside = (file: string, dir: string) => {
|
|
291
|
+
const r = relative(dir, file);
|
|
292
|
+
return r !== "" && !r.startsWith("..") && !isAbsolute(r);
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
/** the page file, the directory served, and the page's path in it */
|
|
296
|
+
export function resolveFilmPage(
|
|
297
|
+
page: string,
|
|
298
|
+
root?: string,
|
|
299
|
+
): { root: string; pageFile: string; urlPath: string } {
|
|
300
|
+
let file = resolve(page);
|
|
301
|
+
if (existsSync(file) && statSync(file).isDirectory()) file = join(file, "index.html");
|
|
302
|
+
if (!existsSync(file)) throw new Error(`film: no page at ${file}`);
|
|
303
|
+
const cwd = process.cwd();
|
|
304
|
+
const base = root ? resolve(root) : inside(file, cwd) ? cwd : dirname(file);
|
|
305
|
+
if (!inside(file, base)) throw new Error(`film: the page ${file} is not inside --root ${base}`);
|
|
306
|
+
const urlPath = `/${relative(base, file).split(sep).map(encodeURIComponent).join("/")}`;
|
|
307
|
+
return { root: base, pageFile: file, urlPath };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const missingError = (missing: Set<string>, root: string) =>
|
|
311
|
+
new Error(
|
|
312
|
+
`film: the page asked for files that are not there (served from ${root}):\n` +
|
|
313
|
+
[...missing].map((p) => ` ${p}`).join("\n") +
|
|
314
|
+
"\n(a page that reaches outside its own folder needs --root <the folder that holds it all>)",
|
|
315
|
+
);
|
|
316
|
+
|
|
317
|
+
export const samplesFor = (px: number): number =>
|
|
318
|
+
Math.max(1, Math.min(MAX_SAMPLES, Math.ceil(px / SPACING_PX)));
|
|
319
|
+
|
|
320
|
+
/** the sample instants (s) of one output frame: n points spread evenly over
|
|
321
|
+
* the shutter, centred on the frame time — or over one side of it when the
|
|
322
|
+
* picture cuts in the other (side -1: before the frame time, 1: after); never
|
|
323
|
+
* before the film starts */
|
|
324
|
+
export function sampleTimes(t: number, n: number, fps: number, side = 0): number[] {
|
|
325
|
+
if (n <= 1) return [t];
|
|
326
|
+
const open = SHUTTER_FRACTION / fps;
|
|
327
|
+
const [lo, hi] = side < 0 ? [-0.5, 0] : side > 0 ? [0, 0.5] : [-0.5, 0.5];
|
|
328
|
+
return Array.from({ length: n }, (_, k) =>
|
|
329
|
+
Math.max(0, t + open * (lo + (hi - lo) * ((k + 0.5) / n))),
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** frames [0, costs.length) cut into at most `workers` contiguous slices of
|
|
334
|
+
* about equal total cost */
|
|
335
|
+
export function balancedSlices(costs: readonly number[], workers: number): [number, number][] {
|
|
336
|
+
const total = costs.reduce((a, b) => a + b, 0);
|
|
337
|
+
const slices: [number, number][] = [];
|
|
338
|
+
let start = 0;
|
|
339
|
+
let acc = 0;
|
|
340
|
+
for (let i = 0; i < costs.length; i++) {
|
|
341
|
+
acc += costs[i]!;
|
|
342
|
+
const target = (total * (slices.length + 1)) / workers;
|
|
343
|
+
if (acc >= target && slices.length < workers - 1 && i + 1 < costs.length) {
|
|
344
|
+
slices.push([start, i + 1]);
|
|
345
|
+
start = i + 1;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (start < costs.length) slices.push([start, costs.length]);
|
|
349
|
+
return slices;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** A page that bakes a simulation (starter/lib/physics.js) publishes its
|
|
353
|
+
* hash as window.__bake.hash. Each worker bakes for itself, so every page a
|
|
354
|
+
* render opens is asked once: two hashes mean two different films. */
|
|
355
|
+
export function bakeGuard(where = "in another worker"): {
|
|
356
|
+
check(b: Pick<HtmlBrowser, "evaluate">): Promise<void>;
|
|
357
|
+
readonly hash: string | null;
|
|
358
|
+
} {
|
|
359
|
+
let hash: string | null = null;
|
|
360
|
+
return {
|
|
361
|
+
get hash() {
|
|
362
|
+
return hash;
|
|
363
|
+
},
|
|
364
|
+
async check(b) {
|
|
365
|
+
const h = await b.evaluate<unknown>(
|
|
366
|
+
`(() => { const h = window.__bake?.hash; return h == null ? null : String(h); })()`,
|
|
367
|
+
);
|
|
368
|
+
if (typeof h !== "string") return;
|
|
369
|
+
if (hash === null) hash = h;
|
|
370
|
+
else if (h !== hash) throw new Error(bakesDiffer(hash, h, where));
|
|
371
|
+
},
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export const bakesDiffer = (a: string, b: string, where: string): string =>
|
|
376
|
+
`film: the physics bakes differ (window.__bake.hash ${a} in one page, ${b} ${where}) — the simulation does not repeat here, so the frames would not belong to one film; render with --workers 1, or make the bake repeat (a fixed step and seed, no wall-clock time)`;
|
|
377
|
+
|
|
378
|
+
export async function renderFilm(opts: FilmRenderOptions): Promise<FilmRenderResult> {
|
|
379
|
+
const t0 = Date.now();
|
|
380
|
+
const draft = !!opts.draft;
|
|
381
|
+
const scale = draft ? 0.5 : 1;
|
|
382
|
+
// every browser draws at the same density, but for the frames drawn finer
|
|
383
|
+
// where text moves slowly (see fineFrames)
|
|
384
|
+
const auto = !draft && opts.supersample === undefined;
|
|
385
|
+
const ss = draft ? 1 : supersampleOf(opts.supersample);
|
|
386
|
+
const page = await servePage(opts, scale * ss);
|
|
387
|
+
const tmp = await mkdtemp(join(tmpdir(), "open-take-film-"));
|
|
388
|
+
try {
|
|
389
|
+
// --- what the page is -----------------------------------------------------
|
|
390
|
+
const { browser: first, info, width, height } = await page.openDeclared(opts);
|
|
391
|
+
page.checkFiles();
|
|
392
|
+
const bake = bakeGuard();
|
|
393
|
+
await bake.check(first);
|
|
394
|
+
const film = describe(opts, info, { pageFile: page.pageFile, width, height, scale, draft });
|
|
395
|
+
await first.evaluate(`window.__filmFps = ${film.fps}`);
|
|
396
|
+
const frames = film.f1 - film.f0;
|
|
397
|
+
const workers = Math.max(1, Math.min(opts.workers ?? defaultWorkers(), frames));
|
|
398
|
+
// what the page says happens, asked once; its curves are asked in the render loop
|
|
399
|
+
const declared = await pageEvents(first, film.warnings);
|
|
400
|
+
const segments = await pageSegments(first, film.warnings);
|
|
401
|
+
const credits = await pageCredits(first, film.warnings);
|
|
402
|
+
const sources = await pageSources(first, film.warnings);
|
|
403
|
+
const hasCurves = await first.evaluate<boolean>(`typeof window.__film?.curves === "function"`);
|
|
404
|
+
const curveRows: (Record<string, number | null> | null)[] = new Array(frames).fill(null);
|
|
405
|
+
|
|
406
|
+
// --- probe: how many shutter samples each frame needs, and where --------
|
|
407
|
+
let samples = new Array<number>(frames).fill(1);
|
|
408
|
+
let sides = new Array<number>(frames).fill(0);
|
|
409
|
+
let density = new Array<number>(frames).fill(ss);
|
|
410
|
+
let fine = finePlan([], [], film.fps, film.f0);
|
|
411
|
+
let turns: TurnBack[] | null = null;
|
|
412
|
+
let pool: HtmlBrowser[] = [first];
|
|
413
|
+
// every render but a draft probes: the blur's samples, the frames drawn
|
|
414
|
+
// finer, the moves that turn back
|
|
415
|
+
if (film.blur || !draft) {
|
|
416
|
+
// a clock film keeps its own state, so only a render film probes in parallel
|
|
417
|
+
if (info.mode === "render")
|
|
418
|
+
while (pool.length < workers) {
|
|
419
|
+
const b = await page.open(width, height);
|
|
420
|
+
await prepare(b, film.fps);
|
|
421
|
+
await bake.check(b);
|
|
422
|
+
pool.push(b);
|
|
423
|
+
}
|
|
424
|
+
const p = await probe(pool, film, opts.onProgress);
|
|
425
|
+
if (film.blur) ({ samples, sides } = p);
|
|
426
|
+
turns = turnsBack(
|
|
427
|
+
p.view,
|
|
428
|
+
p.sides,
|
|
429
|
+
film.fps,
|
|
430
|
+
{ width: film.width, height: film.height },
|
|
431
|
+
film.f0,
|
|
432
|
+
);
|
|
433
|
+
if (auto) {
|
|
434
|
+
const flags = fineFrames(p.text, p.sides, film.fps, scale * ss);
|
|
435
|
+
density = flags.map((f) => f ? FINE_SUPERSAMPLE : ss);
|
|
436
|
+
fine = finePlan(
|
|
437
|
+
flags,
|
|
438
|
+
p.textCause.map((cause, i) =>
|
|
439
|
+
slowTextFrame((p.text[i]! / film.fps) * (scale * ss)) ? cause : null,
|
|
440
|
+
),
|
|
441
|
+
film.fps,
|
|
442
|
+
film.f0,
|
|
443
|
+
);
|
|
444
|
+
if (opts.onFine) opts.onFine(fine);
|
|
445
|
+
else if (fine.seconds > 0) process.stderr.write(`${finePlanLine(fine)}\n`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// --- render ------------------------------------------------------------------
|
|
450
|
+
if (info.mode === "clock") {
|
|
451
|
+
// a clock film keeps its own state: every worker starts from a fresh page
|
|
452
|
+
for (const b of pool) await page.close(b);
|
|
453
|
+
pool = [];
|
|
454
|
+
}
|
|
455
|
+
// a frame costs its samples plus its own seek and encode — counted, as
|
|
456
|
+
// an estimate, as 0.4 of a screenshot
|
|
457
|
+
const slices = balancedSlices(
|
|
458
|
+
samples.map((n, i) => (n + 0.4) * (density[i] === ss ? 1 : FINE_COST)),
|
|
459
|
+
workers,
|
|
460
|
+
);
|
|
461
|
+
const ffmpeg = await resolveFfmpeg();
|
|
462
|
+
// each worker renders its slice in pieces of a few seconds, one encoded
|
|
463
|
+
// chunk per piece: when Chrome dies or hangs (memory pressure on a laptop
|
|
464
|
+
// did it), only that piece is rendered again, on a fresh Chrome
|
|
465
|
+
// and a piece draws at one density
|
|
466
|
+
const pieces = slices.map(([a, b]) => {
|
|
467
|
+
const out: [number, number][] = [];
|
|
468
|
+
for (let p = a; p < b; ) {
|
|
469
|
+
let q = Math.min(b, p + PIECE_FRAMES);
|
|
470
|
+
for (let i = p + 1; i < q; i++)
|
|
471
|
+
if (density[i] !== density[p]) {
|
|
472
|
+
q = i;
|
|
473
|
+
break;
|
|
474
|
+
}
|
|
475
|
+
out.push([p, q]);
|
|
476
|
+
p = q;
|
|
477
|
+
}
|
|
478
|
+
return out;
|
|
479
|
+
});
|
|
480
|
+
const chunks: FilmChunk[] = [];
|
|
481
|
+
const chunkOf = pieces.map((ps) =>
|
|
482
|
+
ps.map(([a, b]) => {
|
|
483
|
+
const file = join(tmp, `chunk-${String(chunks.length).padStart(4, "0")}.mp4`);
|
|
484
|
+
chunks.push({ file, frames: b - a });
|
|
485
|
+
return file;
|
|
486
|
+
}),
|
|
487
|
+
);
|
|
488
|
+
let done = 0;
|
|
489
|
+
let failed: Error | null = null;
|
|
490
|
+
await Promise.all(
|
|
491
|
+
pieces.map(async (ps, w) => {
|
|
492
|
+
let browser: HtmlBrowser | undefined = pool[w];
|
|
493
|
+
let drawn = ss;
|
|
494
|
+
try {
|
|
495
|
+
for (let k = 0; k < ps.length; k++) {
|
|
496
|
+
const [a, b] = ps[k]!;
|
|
497
|
+
for (let attempt = 0; ; attempt++) {
|
|
498
|
+
let piece = 0;
|
|
499
|
+
try {
|
|
500
|
+
if (browser && drawn !== density[a]) {
|
|
501
|
+
await page.close(browser);
|
|
502
|
+
browser = undefined;
|
|
503
|
+
}
|
|
504
|
+
if (!browser) {
|
|
505
|
+
drawn = density[a]!;
|
|
506
|
+
browser = await page.open(width, height, scale * drawn);
|
|
507
|
+
await prepare(browser, film.fps);
|
|
508
|
+
await bake.check(browser);
|
|
509
|
+
}
|
|
510
|
+
const sink = new ShutterSink(
|
|
511
|
+
ffmpeg,
|
|
512
|
+
samples.slice(a, b),
|
|
513
|
+
encodeArgs(film, chunkOf[w]![k]!, draft),
|
|
514
|
+
outSize(film),
|
|
515
|
+
);
|
|
516
|
+
try {
|
|
517
|
+
for (let i = a; i < b; i++) {
|
|
518
|
+
if (failed) throw failed;
|
|
519
|
+
page.checkFiles();
|
|
520
|
+
const t = (film.f0 + i) / film.fps;
|
|
521
|
+
const share = sampleShare(samples[i]!, sides[i]);
|
|
522
|
+
for (const ti of sampleTimes(t, samples[i]!, film.fps, sides[i])) {
|
|
523
|
+
await seek(browser, ti, `frame ${film.f0 + i}`, share);
|
|
524
|
+
await sink.push(
|
|
525
|
+
await browser.screenshot({ format: "jpeg", quality: draft ? 85 : 100 }),
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
if (hasCurves) curveRows[i] = await pageCurves(browser, t, film.warnings);
|
|
529
|
+
piece++;
|
|
530
|
+
done++;
|
|
531
|
+
opts.onProgress?.({ phase: "render", done, total: frames });
|
|
532
|
+
}
|
|
533
|
+
await sink.end();
|
|
534
|
+
} catch (e) {
|
|
535
|
+
sink.kill();
|
|
536
|
+
throw e;
|
|
537
|
+
}
|
|
538
|
+
break;
|
|
539
|
+
} catch (e) {
|
|
540
|
+
const err = e as Error;
|
|
541
|
+
if (failed || attempt >= PIECE_RETRIES || !browserTrouble(err)) throw err;
|
|
542
|
+
film.warnings.push(
|
|
543
|
+
`Chrome failed at frame ${film.f0 + a + piece} (${err.message.split("\n")[0]}) — ` +
|
|
544
|
+
`frames ${film.f0 + a}–${film.f0 + b - 1} rendered again on a fresh one`,
|
|
545
|
+
);
|
|
546
|
+
done -= piece;
|
|
547
|
+
if (browser) await page.close(browser);
|
|
548
|
+
browser = undefined;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
} catch (e) {
|
|
553
|
+
failed ??= e as Error;
|
|
554
|
+
throw e;
|
|
555
|
+
}
|
|
556
|
+
}),
|
|
557
|
+
).catch((e) => {
|
|
558
|
+
throw failed ?? e;
|
|
559
|
+
});
|
|
560
|
+
await page.closeAll();
|
|
561
|
+
page.checkFiles();
|
|
562
|
+
film.warnings.push(...(await page.styleWarnings()));
|
|
563
|
+
for (const v of page.unframed())
|
|
564
|
+
film.warnings.push(
|
|
565
|
+
`a video was shown by seeking it, not as its frames: ${v} — under a slow push it can shimmer, and it renders slower`,
|
|
566
|
+
);
|
|
567
|
+
await deliver(ffmpeg, chunks, film, opts.out, tmp);
|
|
568
|
+
const events = eventsPathFor(opts.out);
|
|
569
|
+
let evs = filmEvents(film, declared, sides, curveRows, film.blur, segments, credits, sources);
|
|
570
|
+
// the picture's own change, read back from what was encoded: information
|
|
571
|
+
// for the score, so a film that cannot be read has the curve left out
|
|
572
|
+
try {
|
|
573
|
+
const { width: ew, height: eh } = outSize(film);
|
|
574
|
+
const grey = await fileGrey(ffmpeg, resolve(opts.out), ew, eh, film.fps);
|
|
575
|
+
const energy = frameEnergy(grey);
|
|
576
|
+
// what the shutter split at is a cut only where the picture jumps as a
|
|
577
|
+
// cut does (findCuts); a word or one part swapped, or a switch inside a
|
|
578
|
+
// fast push, is kept apart from the cuts (see FilmEvents.switches)
|
|
579
|
+
if (evs.detectedCuts.length)
|
|
580
|
+
evs = confirmCuts(
|
|
581
|
+
evs,
|
|
582
|
+
findCuts(grey, energy).map((i) => secs6((film.f0 + i) / film.fps)),
|
|
583
|
+
film.f0 > 0 ? secs6(film.f0 / film.fps) : null,
|
|
584
|
+
);
|
|
585
|
+
if (evs.curves.names.includes(PICTURE_ENERGY))
|
|
586
|
+
film.warnings.push(
|
|
587
|
+
`the page has a curve named "${PICTURE_ENERGY}" — the events file has the picture's own in its place`,
|
|
588
|
+
);
|
|
589
|
+
// a range's first frame has nothing before it to change from
|
|
590
|
+
evs = withPictureEnergy(evs, energy, film.f0 > 0 ? 1 : 0, frames);
|
|
591
|
+
} catch (e) {
|
|
592
|
+
film.warnings.push(
|
|
593
|
+
`the picture's change per frame was not read (${(e as Error).message.split("\n")[0]}) — the events file has no "${PICTURE_ENERGY}"`,
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
await writeFile(
|
|
597
|
+
events,
|
|
598
|
+
`${JSON.stringify({ ...evs, ...(bake.hash ? { bake: bake.hash } : {}), ...(turns ? { turnsBack: turns } : {}) })}\n`,
|
|
599
|
+
);
|
|
600
|
+
const { width: w, height: h } = outSize(film);
|
|
601
|
+
return {
|
|
602
|
+
out: resolve(opts.out),
|
|
603
|
+
fine: fine.ranges,
|
|
604
|
+
fineCauses: fine.causes,
|
|
605
|
+
turnsBack: turns,
|
|
606
|
+
bake: bake.hash,
|
|
607
|
+
fineSupersample: FINE_SUPERSAMPLE,
|
|
608
|
+
mode: info.mode,
|
|
609
|
+
// as encoded: an odd side is padded to even
|
|
610
|
+
width: w + (w % 2),
|
|
611
|
+
height: h + (h % 2),
|
|
612
|
+
fps: film.fps,
|
|
613
|
+
frames,
|
|
614
|
+
samples: samples.reduce((x, y) => x + y, 0),
|
|
615
|
+
durationS: frames / film.fps,
|
|
616
|
+
startFrame: film.f0,
|
|
617
|
+
filmFrames: film.total,
|
|
618
|
+
wallMs: Date.now() - t0,
|
|
619
|
+
warnings: film.warnings,
|
|
620
|
+
events,
|
|
621
|
+
};
|
|
622
|
+
} finally {
|
|
623
|
+
await page.shut();
|
|
624
|
+
await rm(tmp, { recursive: true, force: true });
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
|
|
629
|
+
|
|
630
|
+
/** window.__film.events(), once, as plain values; [] when the page has none.
|
|
631
|
+
* An entry without a time or a kind is left out, and said so. */
|
|
632
|
+
async function pageEvents(b: HtmlBrowser, warnings: string[]): Promise<FilmEvent[]> {
|
|
633
|
+
let raw: unknown;
|
|
634
|
+
try {
|
|
635
|
+
raw = await b.evaluate<unknown>(
|
|
636
|
+
`(async () => {
|
|
637
|
+
const f = window.__film?.events;
|
|
638
|
+
if (f === undefined) return null;
|
|
639
|
+
if (typeof f !== "function") return { notFunction: true };
|
|
640
|
+
return JSON.parse(JSON.stringify((await f()) ?? []));
|
|
641
|
+
})()`,
|
|
642
|
+
);
|
|
643
|
+
} catch (e) {
|
|
644
|
+
// like a curve, the events are information for the score: the film goes on
|
|
645
|
+
warnings.push(
|
|
646
|
+
`window.__film.events threw (${(e as Error).message.split("\n")[0]}) — the events file has none`,
|
|
647
|
+
);
|
|
648
|
+
return [];
|
|
649
|
+
}
|
|
650
|
+
if (raw && typeof raw === "object" && "notFunction" in raw) {
|
|
651
|
+
warnings.push(
|
|
652
|
+
"window.__film.events is not a function — it is asked once, as events(); the events file has none",
|
|
653
|
+
);
|
|
654
|
+
return [];
|
|
655
|
+
}
|
|
656
|
+
return checkEvents(raw, warnings);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** a page's events, checked and in time order (see FilmEvent) */
|
|
660
|
+
export function checkEvents(raw: unknown, warnings: string[] = []): FilmEvent[] {
|
|
661
|
+
if (raw == null) return [];
|
|
662
|
+
if (!Array.isArray(raw)) {
|
|
663
|
+
warnings.push("window.__film.events() gave no list — the events file has none");
|
|
664
|
+
return [];
|
|
665
|
+
}
|
|
666
|
+
const out: FilmEvent[] = [];
|
|
667
|
+
let dropped = 0;
|
|
668
|
+
for (const e of raw as Record<string, unknown>[]) {
|
|
669
|
+
if (!e || !finite(e.t) || typeof e.kind !== "string" || !e.kind) {
|
|
670
|
+
dropped++;
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
const ev: FilmEvent = { t: e.t, kind: e.kind };
|
|
674
|
+
if (finite(e.x)) ev.x = e.x;
|
|
675
|
+
if (finite(e.y)) ev.y = e.y;
|
|
676
|
+
if (finite(e.force)) ev.force = Math.max(0, Math.min(1, e.force));
|
|
677
|
+
if (typeof e.label === "string") ev.label = e.label;
|
|
678
|
+
out.push(ev);
|
|
679
|
+
}
|
|
680
|
+
if (dropped)
|
|
681
|
+
warnings.push(
|
|
682
|
+
`window.__film.events(): ${dropped} event(s) without a time (t, s) or a kind were left out`,
|
|
683
|
+
);
|
|
684
|
+
// stable: events at the same time keep the page's order
|
|
685
|
+
return out
|
|
686
|
+
.map((e, i) => [e, i] as const)
|
|
687
|
+
.sort((a, b) => a[0].t - b[0].t || a[1] - b[1])
|
|
688
|
+
.map(([e]) => e);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** window.__film.segments(), once, as plain values; [] when the page has none */
|
|
692
|
+
async function pageSegments(b: HtmlBrowser, warnings: string[]): Promise<FilmSegment[]> {
|
|
693
|
+
let raw: unknown;
|
|
694
|
+
try {
|
|
695
|
+
raw = await b.evaluate<unknown>(
|
|
696
|
+
`(async () => {
|
|
697
|
+
const f = window.__film?.segments;
|
|
698
|
+
if (f === undefined) return null;
|
|
699
|
+
if (typeof f !== "function") return { notFunction: true };
|
|
700
|
+
return JSON.parse(JSON.stringify((await f()) ?? []));
|
|
701
|
+
})()`,
|
|
702
|
+
);
|
|
703
|
+
} catch (e) {
|
|
704
|
+
warnings.push(
|
|
705
|
+
`window.__film.segments threw (${(e as Error).message.split("\n")[0]}) — the events file has none`,
|
|
706
|
+
);
|
|
707
|
+
return [];
|
|
708
|
+
}
|
|
709
|
+
if (raw && typeof raw === "object" && "notFunction" in raw) {
|
|
710
|
+
warnings.push(
|
|
711
|
+
"window.__film.segments is not a function — it is asked once, as segments(); the events file has none",
|
|
712
|
+
);
|
|
713
|
+
return [];
|
|
714
|
+
}
|
|
715
|
+
return checkSegments(raw, warnings);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** a page's beat sheet, checked and by `from` (see FilmSegment): a segment
|
|
719
|
+
* without two times, or that ends before it starts, is left out and said so */
|
|
720
|
+
export function checkSegments(raw: unknown, warnings: string[] = []): FilmSegment[] {
|
|
721
|
+
if (raw == null) return [];
|
|
722
|
+
if (!Array.isArray(raw)) {
|
|
723
|
+
warnings.push("window.__film.segments() gave no list — the events file has none");
|
|
724
|
+
return [];
|
|
725
|
+
}
|
|
726
|
+
const out: FilmSegment[] = [];
|
|
727
|
+
let dropped = 0;
|
|
728
|
+
for (const e of raw as Record<string, unknown>[]) {
|
|
729
|
+
if (!e || !finite(e.from) || !finite(e.to) || !(e.to > e.from)) {
|
|
730
|
+
dropped++;
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
const seg: FilmSegment = { from: e.from, to: e.to };
|
|
734
|
+
for (const k of ["label", "handoff", "carry", "subject", "sound"] as const)
|
|
735
|
+
if (typeof e[k] === "string" && e[k]) seg[k] = e[k] as string;
|
|
736
|
+
if (e.seam && typeof e.seam === "object" && !Array.isArray(e.seam)) {
|
|
737
|
+
const entries = Object.entries(e.seam).filter(([, v]) => typeof v === "string" || finite(v));
|
|
738
|
+
if (entries.length) seg.seam = Object.fromEntries(entries);
|
|
739
|
+
}
|
|
740
|
+
if (typeof e.hold === "boolean") seg.hold = e.hold;
|
|
741
|
+
out.push(seg);
|
|
742
|
+
}
|
|
743
|
+
if (dropped)
|
|
744
|
+
warnings.push(
|
|
745
|
+
`window.__film.segments(): ${dropped} segment(s) without a from and a later to (s) were left out`,
|
|
746
|
+
);
|
|
747
|
+
return out
|
|
748
|
+
.map((s, i) => [s, i] as const)
|
|
749
|
+
.sort((a, b) => a[0].from - b[0].from || a[1] - b[1])
|
|
750
|
+
.map(([s]) => s);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** whether a segment's handoff is the declaration `kind` ("hidden-cut",
|
|
754
|
+
* "lift"), as the page writes it */
|
|
755
|
+
export const handoffIs = (s: Pick<FilmSegment, "handoff">, kind: "hidden-cut" | "lift") =>
|
|
756
|
+
s.handoff?.trim().toLowerCase() === kind;
|
|
757
|
+
|
|
758
|
+
/** the spans of the segments the page declares as a lift: a layer moving on
|
|
759
|
+
* its own, whose jumps and turns are meant */
|
|
760
|
+
export const liftSpans = (segments: readonly FilmSegment[]): [number, number][] =>
|
|
761
|
+
segments.filter((s) => handoffIs(s, "lift")).map((s) => [s.from, s.to]);
|
|
762
|
+
|
|
763
|
+
/** The times of cuts the page says it hides in motion, taken from a
|
|
764
|
+
* "hidden-cut" event's time or the end of a segment with that handoff. */
|
|
765
|
+
export function hiddenCutTimes(
|
|
766
|
+
events: readonly FilmEvent[],
|
|
767
|
+
segments: readonly FilmSegment[],
|
|
768
|
+
): number[] {
|
|
769
|
+
return [
|
|
770
|
+
...events.filter((e) => e.kind === "hidden-cut").map((e) => e.t),
|
|
771
|
+
...segments.filter((s) => handoffIs(s, "hidden-cut")).map((s) => s.to),
|
|
772
|
+
];
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** window.__film.credits — a list, or a function that gives one — once, as
|
|
776
|
+
* plain values; [] when the page has none */
|
|
777
|
+
async function pageCredits(b: HtmlBrowser, warnings: string[]): Promise<FilmCredit[]> {
|
|
778
|
+
let raw: unknown;
|
|
779
|
+
try {
|
|
780
|
+
raw = await b.evaluate<unknown>(
|
|
781
|
+
`(async () => {
|
|
782
|
+
let c = window.__film?.credits;
|
|
783
|
+
if (c === undefined) return null;
|
|
784
|
+
if (typeof c === "function") c = await c();
|
|
785
|
+
return JSON.parse(JSON.stringify(c ?? []));
|
|
786
|
+
})()`,
|
|
787
|
+
);
|
|
788
|
+
} catch (e) {
|
|
789
|
+
warnings.push(
|
|
790
|
+
`window.__film.credits threw (${(e as Error).message.split("\n")[0]}) — the events file has none`,
|
|
791
|
+
);
|
|
792
|
+
return [];
|
|
793
|
+
}
|
|
794
|
+
return checkCredits(raw, warnings);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/** a page's credits as given, each kept to its known fields as strings
|
|
798
|
+
* ("license" read as "licence"); one that says nothing is left out and said so */
|
|
799
|
+
export function checkCredits(raw: unknown, warnings: string[] = []): FilmCredit[] {
|
|
800
|
+
if (raw == null) return [];
|
|
801
|
+
if (!Array.isArray(raw)) {
|
|
802
|
+
warnings.push("window.__film.credits is not a list — the events file has none");
|
|
803
|
+
return [];
|
|
804
|
+
}
|
|
805
|
+
const out: FilmCredit[] = [];
|
|
806
|
+
let dropped = 0;
|
|
807
|
+
for (const e of raw as Record<string, unknown>[]) {
|
|
808
|
+
const c: FilmCredit = {};
|
|
809
|
+
if (e && typeof e === "object") {
|
|
810
|
+
const src: Record<string, unknown> = { ...e, licence: e.licence ?? e.license };
|
|
811
|
+
for (const k of ["what", "by", "licence", "url", "text"] as const) {
|
|
812
|
+
const v = src[k];
|
|
813
|
+
if ((typeof v === "string" && v) || finite(v)) c[k] = String(v);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
if (Object.keys(c).length) out.push(c);
|
|
817
|
+
else dropped++;
|
|
818
|
+
}
|
|
819
|
+
if (dropped)
|
|
820
|
+
warnings.push(
|
|
821
|
+
`window.__film.credits: ${dropped} credit(s) with no what, by, licence, url or text were left out`,
|
|
822
|
+
);
|
|
823
|
+
return out;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/** window.__film.sources — a list, or a function that gives one — once, as
|
|
827
|
+
* plain values; [] when the page has none */
|
|
828
|
+
async function pageSources(b: HtmlBrowser, warnings: string[]): Promise<FilmSource[]> {
|
|
829
|
+
let raw: unknown;
|
|
830
|
+
try {
|
|
831
|
+
raw = await b.evaluate<unknown>(
|
|
832
|
+
`(async () => {
|
|
833
|
+
let s = window.__film?.sources;
|
|
834
|
+
if (s === undefined) return null;
|
|
835
|
+
if (typeof s === "function") s = await s();
|
|
836
|
+
return JSON.parse(JSON.stringify(s ?? []));
|
|
837
|
+
})()`,
|
|
838
|
+
);
|
|
839
|
+
} catch (e) {
|
|
840
|
+
warnings.push(
|
|
841
|
+
`window.__film.sources threw (${(e as Error).message.split("\n")[0]}) — the events file has none`,
|
|
842
|
+
);
|
|
843
|
+
return [];
|
|
844
|
+
}
|
|
845
|
+
return checkSources(raw, warnings);
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** a page's sources as given, each kept to its known fields; one without a
|
|
849
|
+
* label, or that names no ref, url or note, is left out and said so */
|
|
850
|
+
export function checkSources(raw: unknown, warnings: string[] = []): FilmSource[] {
|
|
851
|
+
if (raw == null) return [];
|
|
852
|
+
if (!Array.isArray(raw)) {
|
|
853
|
+
warnings.push("window.__film.sources is not a list — the events file has none");
|
|
854
|
+
return [];
|
|
855
|
+
}
|
|
856
|
+
const out: FilmSource[] = [];
|
|
857
|
+
let dropped = 0;
|
|
858
|
+
for (const e of raw as Record<string, unknown>[]) {
|
|
859
|
+
const label = e && typeof e === "object" ? e.label : undefined;
|
|
860
|
+
if (typeof label !== "string" || !label.trim()) {
|
|
861
|
+
dropped++;
|
|
862
|
+
continue;
|
|
863
|
+
}
|
|
864
|
+
const s: FilmSource = { label };
|
|
865
|
+
for (const k of ["ref", "field", "file", "url", "note", "selector"] as const) {
|
|
866
|
+
const v = e[k];
|
|
867
|
+
if ((typeof v === "string" && v) || finite(v)) s[k] = String(v);
|
|
868
|
+
}
|
|
869
|
+
const text = (Array.isArray(e.text) ? e.text : e.text != null ? [e.text] : [])
|
|
870
|
+
.filter((v) => (typeof v === "string" && v) || finite(v))
|
|
871
|
+
.map(String);
|
|
872
|
+
if (text.length) s.text = text;
|
|
873
|
+
if (s.ref || s.url || s.note) out.push(s);
|
|
874
|
+
else dropped++;
|
|
875
|
+
}
|
|
876
|
+
if (dropped)
|
|
877
|
+
warnings.push(
|
|
878
|
+
`window.__film.sources: ${dropped} source(s) without a label and a ref, url or note were left out`,
|
|
879
|
+
);
|
|
880
|
+
return out;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/** window.__film.curves(t): every value that is a finite number, the rest null */
|
|
884
|
+
async function pageCurves(
|
|
885
|
+
b: HtmlBrowser,
|
|
886
|
+
t: number,
|
|
887
|
+
warnings: string[],
|
|
888
|
+
): Promise<Record<string, number | null> | null> {
|
|
889
|
+
try {
|
|
890
|
+
return await b.evaluate<Record<string, number | null> | null>(
|
|
891
|
+
`(async () => {
|
|
892
|
+
const r = await window.__film.curves(${t});
|
|
893
|
+
if (!r || typeof r !== "object") return null;
|
|
894
|
+
const o = {};
|
|
895
|
+
for (const k of Object.keys(r)) { const v = r[k]; o[k] = typeof v === "number" && Number.isFinite(v) ? v : null; }
|
|
896
|
+
return o;
|
|
897
|
+
})()`,
|
|
898
|
+
);
|
|
899
|
+
} catch (e) {
|
|
900
|
+
// a curve is information for the score, never a reason to lose the film
|
|
901
|
+
if (!warnings.some((w) => w.startsWith("window.__film.curves")))
|
|
902
|
+
warnings.push(
|
|
903
|
+
`window.__film.curves threw (${(e as Error).message.split("\n")[0]}) — left out where it did`,
|
|
904
|
+
);
|
|
905
|
+
return null;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** merge times less than `eps` apart into the first of them, in order */
|
|
910
|
+
export const mergeTimes = (ts: number[], eps: number): number[] =>
|
|
911
|
+
[...ts]
|
|
912
|
+
.sort((a, b) => a - b)
|
|
913
|
+
.reduce<number[]>((acc, t) => {
|
|
914
|
+
if (!acc.length || t - acc[acc.length - 1]! >= eps) acc.push(t);
|
|
915
|
+
return acc;
|
|
916
|
+
}, []);
|
|
917
|
+
|
|
918
|
+
const secs6 = (t: number) => Math.round(t * 1e6) / 1e6;
|
|
919
|
+
|
|
920
|
+
/** the events file of a render of frames [f0, f1): `sides` and `rows` are per
|
|
921
|
+
* rendered frame (see FilmEvents.detectedCuts for what a side says) */
|
|
922
|
+
export function filmEvents(
|
|
923
|
+
film: Pick<Film, "fps" | "f0" | "f1" | "total">,
|
|
924
|
+
events: FilmEvent[],
|
|
925
|
+
sides: readonly number[],
|
|
926
|
+
rows: readonly (Record<string, number | null> | null)[],
|
|
927
|
+
probed: boolean,
|
|
928
|
+
segments: FilmSegment[] = [],
|
|
929
|
+
credits: FilmCredit[] = [],
|
|
930
|
+
sources: FilmSource[] = [],
|
|
931
|
+
): FilmEvents {
|
|
932
|
+
const { fps, f0, f1, total } = film;
|
|
933
|
+
const detected: number[] = [];
|
|
934
|
+
if (probed)
|
|
935
|
+
sides.forEach((side, i) => {
|
|
936
|
+
// side 1: the first half of the shutter changed, so this frame is the
|
|
937
|
+
// first of the new picture; side -1: the second half did, so the next is
|
|
938
|
+
if (side > 0) detected.push(secs6((f0 + i) / fps));
|
|
939
|
+
else if (side < 0 && f0 + i + 1 < total) detected.push(secs6((f0 + i + 1) / fps));
|
|
940
|
+
});
|
|
941
|
+
const declaredCuts = mergeTimes(
|
|
942
|
+
[...events.filter((e) => e.kind === "cut").map((e) => e.t), ...hiddenCutTimes(events, segments)],
|
|
943
|
+
1e-9,
|
|
944
|
+
);
|
|
945
|
+
const names: string[] = [];
|
|
946
|
+
const seen = new Set<string>();
|
|
947
|
+
for (const r of rows)
|
|
948
|
+
if (r)
|
|
949
|
+
for (const k of Object.keys(r))
|
|
950
|
+
if (!seen.has(k)) {
|
|
951
|
+
seen.add(k);
|
|
952
|
+
names.push(k);
|
|
953
|
+
}
|
|
954
|
+
return {
|
|
955
|
+
version: 1,
|
|
956
|
+
duration: secs6(total / fps),
|
|
957
|
+
fps,
|
|
958
|
+
...(f0 > 0 || f1 < total
|
|
959
|
+
? { range: [secs6(f0 / fps), secs6(f1 / fps)] as [number, number] }
|
|
960
|
+
: {}),
|
|
961
|
+
events,
|
|
962
|
+
cuts: mergeTimes([...declaredCuts, ...mergeTimes(detected, 1e-9)], 0.5 / fps),
|
|
963
|
+
declaredCuts,
|
|
964
|
+
detectedCuts: mergeTimes(detected, 1e-9),
|
|
965
|
+
curves: {
|
|
966
|
+
names,
|
|
967
|
+
t0: secs6(f0 / fps),
|
|
968
|
+
dt: 1 / fps,
|
|
969
|
+
rows: names.length ? rows.map((r) => names.map((k) => r?.[k] ?? null)) : [],
|
|
970
|
+
},
|
|
971
|
+
segments,
|
|
972
|
+
credits,
|
|
973
|
+
sources,
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
/** the name of the picture's own curve in the events file (see FilmEvents.curves) */
|
|
978
|
+
export const PICTURE_ENERGY = "picture.energy";
|
|
979
|
+
|
|
980
|
+
/** `ev` with its rows [from, to) of the PICTURE_ENERGY column set from
|
|
981
|
+
* `energy` (one value per row; rounded, null where it is not a number). The
|
|
982
|
+
* column is added when the events have none, null outside [from, to); rows
|
|
983
|
+
* are added when the page gave no curves */
|
|
984
|
+
export function withPictureEnergy(
|
|
985
|
+
ev: FilmEvents,
|
|
986
|
+
energy: ArrayLike<number | null>,
|
|
987
|
+
from = 0,
|
|
988
|
+
to: number = energy.length,
|
|
989
|
+
): FilmEvents {
|
|
990
|
+
const names = ev.curves.names.includes(PICTURE_ENERGY)
|
|
991
|
+
? [...ev.curves.names]
|
|
992
|
+
: [...ev.curves.names, PICTURE_ENERGY];
|
|
993
|
+
const j = names.indexOf(PICTURE_ENERGY);
|
|
994
|
+
const n = Math.max(ev.curves.rows.length, Math.min(to, energy.length));
|
|
995
|
+
const rows = Array.from({ length: n }, (_, i) => {
|
|
996
|
+
const row = names.map((_, k) => ev.curves.rows[i]?.[k] ?? null);
|
|
997
|
+
if (i >= from && i < to) {
|
|
998
|
+
const v = energy[i];
|
|
999
|
+
row[j] = typeof v === "number" && Number.isFinite(v) ? Math.round(v * 1e5) / 1e5 : null;
|
|
1000
|
+
}
|
|
1001
|
+
return row;
|
|
1002
|
+
});
|
|
1003
|
+
return { ...ev, curves: { ...ev.curves, names, rows } };
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
/** the shutter's splits (detectedCuts) sorted against the cuts the picture
|
|
1007
|
+
* shows (`pictureCuts`, the first frame of each new picture, s): a split
|
|
1008
|
+
* within 1.5 frames of one stays a cut, the rest become `switches`. A split
|
|
1009
|
+
* on `first` — a range's first frame, which has nothing before it in the
|
|
1010
|
+
* file to compare — stays as it was. */
|
|
1011
|
+
export function confirmCuts(
|
|
1012
|
+
ev: FilmEvents,
|
|
1013
|
+
pictureCuts: readonly number[],
|
|
1014
|
+
first: number | null = null,
|
|
1015
|
+
): FilmEvents {
|
|
1016
|
+
const tol = 1.5 / ev.fps;
|
|
1017
|
+
const kept: number[] = [];
|
|
1018
|
+
const switches: number[] = [];
|
|
1019
|
+
for (const t of ev.detectedCuts)
|
|
1020
|
+
if (
|
|
1021
|
+
(first != null && Math.abs(t - first) < 0.5 / ev.fps) ||
|
|
1022
|
+
pictureCuts.some((c) => Math.abs(c - t) <= tol)
|
|
1023
|
+
)
|
|
1024
|
+
kept.push(t);
|
|
1025
|
+
else switches.push(t);
|
|
1026
|
+
return {
|
|
1027
|
+
...ev,
|
|
1028
|
+
cuts: mergeTimes([...ev.declaredCuts, ...kept], 0.5 / ev.fps),
|
|
1029
|
+
detectedCuts: kept,
|
|
1030
|
+
switches,
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/** the events file of a master after `patch` — a render of part of it — went
|
|
1035
|
+
* into it: the page's events as they are now, the curves and the detected
|
|
1036
|
+
* cuts of the range in place of the master's own there */
|
|
1037
|
+
export function patchEvents(master: FilmEvents, patch: FilmEvents): FilmEvents | null {
|
|
1038
|
+
const frames = Math.round(master.duration * master.fps);
|
|
1039
|
+
if (
|
|
1040
|
+
master.version !== 1 ||
|
|
1041
|
+
master.range ||
|
|
1042
|
+
Math.abs(master.fps - patch.fps) > 1e-6 ||
|
|
1043
|
+
Math.abs(master.duration - patch.duration) > 0.5 / patch.fps ||
|
|
1044
|
+
!patch.range
|
|
1045
|
+
)
|
|
1046
|
+
return null;
|
|
1047
|
+
const [from, to] = patch.range;
|
|
1048
|
+
const a = Math.round(from * patch.fps);
|
|
1049
|
+
const b = Math.round(to * patch.fps);
|
|
1050
|
+
const inRange = (t: number) => t >= from - 1e-9 && t < to - 1e-9;
|
|
1051
|
+
const detectedCuts = mergeTimes(
|
|
1052
|
+
[...master.detectedCuts.filter((t) => !inRange(t)), ...patch.detectedCuts],
|
|
1053
|
+
1e-9,
|
|
1054
|
+
);
|
|
1055
|
+
const switches =
|
|
1056
|
+
master.switches || patch.switches
|
|
1057
|
+
? mergeTimes(
|
|
1058
|
+
[...(master.switches ?? []).filter((t) => !inRange(t)), ...(patch.switches ?? [])],
|
|
1059
|
+
1e-9,
|
|
1060
|
+
)
|
|
1061
|
+
: undefined;
|
|
1062
|
+
// the curves: names from both, the master's rows outside the range
|
|
1063
|
+
const names = [...master.curves.names];
|
|
1064
|
+
for (const n of patch.curves.names) if (!names.includes(n)) names.push(n);
|
|
1065
|
+
const col = (c: FilmEvents["curves"], row: (number | null)[] | undefined, n: string) => {
|
|
1066
|
+
const j = c.names.indexOf(n);
|
|
1067
|
+
return j < 0 ? null : (row?.[j] ?? null);
|
|
1068
|
+
};
|
|
1069
|
+
const rows =
|
|
1070
|
+
names.length === 0
|
|
1071
|
+
? []
|
|
1072
|
+
: Array.from({ length: frames }, (_, i) =>
|
|
1073
|
+
i >= a && i < b
|
|
1074
|
+
? names.map((n) => col(patch.curves, patch.curves.rows[i - a], n))
|
|
1075
|
+
: names.map((n) => col(master.curves, master.curves.rows[i], n)),
|
|
1076
|
+
);
|
|
1077
|
+
return {
|
|
1078
|
+
version: 1,
|
|
1079
|
+
duration: master.duration,
|
|
1080
|
+
fps: master.fps,
|
|
1081
|
+
events: patch.events,
|
|
1082
|
+
cuts: mergeTimes([...patch.declaredCuts, ...detectedCuts], 0.5 / master.fps),
|
|
1083
|
+
declaredCuts: patch.declaredCuts,
|
|
1084
|
+
detectedCuts,
|
|
1085
|
+
...(switches ? { switches } : {}),
|
|
1086
|
+
curves: { names, t0: 0, dt: 1 / master.fps, rows },
|
|
1087
|
+
// the beat sheet as the page says it now, like its events
|
|
1088
|
+
segments: patch.segments ?? master.segments ?? [],
|
|
1089
|
+
// the credits as the page says them now
|
|
1090
|
+
credits: patch.credits ?? master.credits ?? [],
|
|
1091
|
+
// where its values come from, as the page says it now
|
|
1092
|
+
sources: patch.sources ?? master.sources ?? [],
|
|
1093
|
+
// the same bake in both, or the patch was refused (see patchFilm)
|
|
1094
|
+
...((patch.bake ?? master.bake) ? { bake: patch.bake ?? master.bake } : {}),
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
export type FilmStillsOptions = {
|
|
1099
|
+
page: string;
|
|
1100
|
+
chromePath: string;
|
|
1101
|
+
/** seconds */
|
|
1102
|
+
at: readonly number[];
|
|
1103
|
+
outDir: string;
|
|
1104
|
+
root?: string;
|
|
1105
|
+
width?: number;
|
|
1106
|
+
height?: number;
|
|
1107
|
+
/** with the shutter's motion blur, as in the master (default on) */
|
|
1108
|
+
blur?: boolean;
|
|
1109
|
+
/** as the master is rendered (see FilmRenderOptions.supersample) */
|
|
1110
|
+
supersample?: number;
|
|
1111
|
+
/** see FilmRenderOptions.keepLayers */
|
|
1112
|
+
keepLayers?: boolean;
|
|
1113
|
+
onConsole?: (level: string, text: string) => void;
|
|
1114
|
+
/** what the stills found wrong on the page (an inline style that did not
|
|
1115
|
+
* take), once each */
|
|
1116
|
+
onWarning?: (text: string) => void;
|
|
1117
|
+
};
|
|
1118
|
+
|
|
1119
|
+
/** Render only [from, to) of the film, at master quality, into `into` — a
|
|
1120
|
+
* master of the whole film — in place of its own frames: a change to a few
|
|
1121
|
+
* seconds costs those seconds, not the film. The master's sound is kept (to
|
|
1122
|
+
* change it, muxFilm). Refused when `into` is not a whole master of this
|
|
1123
|
+
* film: one `film render` did not make, one whose frames are not evenly
|
|
1124
|
+
* spaced, another size, frame rate or length, or a range of its own. */
|
|
1125
|
+
export async function patchFilm(
|
|
1126
|
+
opts: FilmRenderOptions & { into: string },
|
|
1127
|
+
): Promise<FilmRenderResult> {
|
|
1128
|
+
const t0 = Date.now();
|
|
1129
|
+
if (opts.from === undefined && opts.to === undefined)
|
|
1130
|
+
throw new Error("film: --into takes --from and/or --to: the seconds to render again");
|
|
1131
|
+
if (opts.draft) throw new Error("film: --into puts master frames into a master — not a --draft");
|
|
1132
|
+
const into = resolve(opts.into);
|
|
1133
|
+
if (!existsSync(into))
|
|
1134
|
+
throw new Error(`film: there is no master at ${into} to put the range into`);
|
|
1135
|
+
const ffmpeg = await resolveFfmpeg();
|
|
1136
|
+
const master = await probeFilm(into);
|
|
1137
|
+
// its frames are swapped by number: frame n must be the one at n/fps, as in
|
|
1138
|
+
// a master `film render` made — not in a file whose average rate only
|
|
1139
|
+
// matches, nor one whose picture was moved off 0 (the range starts at 0,
|
|
1140
|
+
// and the sound is kept where it is)
|
|
1141
|
+
const unlike = !master.made ? "`film render` did not make it" : await framesOff(into);
|
|
1142
|
+
if (unlike)
|
|
1143
|
+
throw new Error(
|
|
1144
|
+
`film: ${opts.into} is not a whole master of this film (${unlike}) — render it whole`,
|
|
1145
|
+
);
|
|
1146
|
+
const tmp = await mkdtemp(join(tmpdir(), "open-take-patch-"));
|
|
1147
|
+
try {
|
|
1148
|
+
const range = join(tmp, "range.mp4");
|
|
1149
|
+
const r = await renderFilm({ ...opts, out: range, audio: null });
|
|
1150
|
+
const masterBake = await readFile(eventsPathFor(into), "utf8")
|
|
1151
|
+
.then((text) => (JSON.parse(text) as Partial<FilmEvents>).bake ?? null)
|
|
1152
|
+
.catch(() => null);
|
|
1153
|
+
if (masterBake && r.bake && masterBake !== r.bake)
|
|
1154
|
+
throw new Error(bakesDiffer(masterBake, r.bake, `in the range rendered for ${opts.into}`));
|
|
1155
|
+
const it = `${master.width}×${master.height} ${master.fps} fps, ${master.frames} frames${master.from ? `, from ${master.from}s` : ""}`;
|
|
1156
|
+
const film = `${r.width}×${r.height} ${r.fps} fps, ${r.filmFrames} frames`;
|
|
1157
|
+
if (
|
|
1158
|
+
master.width !== r.width ||
|
|
1159
|
+
master.height !== r.height ||
|
|
1160
|
+
Math.abs(master.fps - r.fps) > 0.001 ||
|
|
1161
|
+
master.frames !== r.filmFrames ||
|
|
1162
|
+
master.from
|
|
1163
|
+
)
|
|
1164
|
+
throw new Error(
|
|
1165
|
+
`film: ${opts.into} is not a whole master of this film (it is ${it}; the film is ${film}) — render it whole`,
|
|
1166
|
+
);
|
|
1167
|
+
const a = r.startFrame;
|
|
1168
|
+
const b = r.startFrame + r.frames;
|
|
1169
|
+
const parts: string[] = [];
|
|
1170
|
+
let graph = "";
|
|
1171
|
+
if (a > 0) {
|
|
1172
|
+
graph += `[0:v]trim=end_frame=${a},setpts=PTS-STARTPTS[before];`;
|
|
1173
|
+
parts.push("[before]");
|
|
1174
|
+
}
|
|
1175
|
+
graph += "[1:v]setpts=PTS-STARTPTS[range];";
|
|
1176
|
+
parts.push("[range]");
|
|
1177
|
+
if (b < master.frames) {
|
|
1178
|
+
graph += `[0:v]trim=start_frame=${b},setpts=PTS-STARTPTS[after];`;
|
|
1179
|
+
parts.push("[after]");
|
|
1180
|
+
}
|
|
1181
|
+
// frame n at n/fps exactly, as a render puts it — also when the master
|
|
1182
|
+
// had one a few ticks off (see framesOffIn); and named as a master is
|
|
1183
|
+
// named, whatever the master said: one `film render` made before named
|
|
1184
|
+
// BT.709's curve (or, on ffmpeg 8, none) for the same sRGB values, and a
|
|
1185
|
+
// patched master must not name two
|
|
1186
|
+
graph += `${parts.join("")}concat=n=${parts.length}:v=1:a=0,setpts=N/(${r.fps}*TB),format=yuv420p,${SRGB_TAGS}[v]`;
|
|
1187
|
+
const record = { ...(await probeFilm(range)).record, from: 0 };
|
|
1188
|
+
const out = join(tmp, "patched.mp4");
|
|
1189
|
+
// the same encoding as a master (see encodeArgs)
|
|
1190
|
+
await runTool(ffmpeg, [
|
|
1191
|
+
"-v",
|
|
1192
|
+
"error",
|
|
1193
|
+
"-y",
|
|
1194
|
+
"-i",
|
|
1195
|
+
into,
|
|
1196
|
+
"-i",
|
|
1197
|
+
range,
|
|
1198
|
+
"-filter_complex",
|
|
1199
|
+
graph,
|
|
1200
|
+
"-map",
|
|
1201
|
+
"[v]",
|
|
1202
|
+
"-map",
|
|
1203
|
+
"0:a?",
|
|
1204
|
+
"-c:a",
|
|
1205
|
+
"copy",
|
|
1206
|
+
"-c:v",
|
|
1207
|
+
"libx264",
|
|
1208
|
+
"-preset",
|
|
1209
|
+
"medium",
|
|
1210
|
+
"-crf",
|
|
1211
|
+
"14",
|
|
1212
|
+
"-x264-params",
|
|
1213
|
+
`keyint=${Math.round(r.fps) * 2}:min-keyint=1:aq-mode=3`,
|
|
1214
|
+
...SRGB_TAG_ARGS,
|
|
1215
|
+
"-metadata",
|
|
1216
|
+
`${FILM_TAG}=${JSON.stringify(record)}`,
|
|
1217
|
+
"-movflags",
|
|
1218
|
+
"+faststart+use_metadata_tags",
|
|
1219
|
+
out,
|
|
1220
|
+
]);
|
|
1221
|
+
await mkdir(dirname(resolve(opts.out)), { recursive: true });
|
|
1222
|
+
await moveFile(out, resolve(opts.out));
|
|
1223
|
+
const warnings = r.warnings.filter((w) => !w.startsWith("no soundtrack"));
|
|
1224
|
+
// the master's events file, with the range's curves and cuts in place of its own
|
|
1225
|
+
// and the picture's change read again where the patched master changed:
|
|
1226
|
+
// the range and the frame after it (it now follows a new frame)
|
|
1227
|
+
let energy: Float32Array | null = null;
|
|
1228
|
+
try {
|
|
1229
|
+
energy = await fileEnergy(ffmpeg, resolve(opts.out), r.width, r.height, r.fps);
|
|
1230
|
+
} catch (e) {
|
|
1231
|
+
warnings.push(
|
|
1232
|
+
`the picture's change per frame was not read again (${(e as Error).message.split("\n")[0]}) — "${PICTURE_ENERGY}" in the events file is the range render's`,
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
const events = await patchedEventsFile(
|
|
1236
|
+
into,
|
|
1237
|
+
r.events,
|
|
1238
|
+
resolve(opts.out),
|
|
1239
|
+
warnings,
|
|
1240
|
+
(merged, own) =>
|
|
1241
|
+
!energy
|
|
1242
|
+
? merged
|
|
1243
|
+
: own.curves.names.includes(PICTURE_ENERGY)
|
|
1244
|
+
? withPictureEnergy(merged, energy, a, b + 1)
|
|
1245
|
+
: // a master whose events file has no such curve gets it whole
|
|
1246
|
+
withPictureEnergy(merged, energy),
|
|
1247
|
+
);
|
|
1248
|
+
return {
|
|
1249
|
+
...r,
|
|
1250
|
+
out: resolve(opts.out),
|
|
1251
|
+
frames: master.frames,
|
|
1252
|
+
durationS: master.frames / r.fps,
|
|
1253
|
+
startFrame: 0,
|
|
1254
|
+
wallMs: Date.now() - t0,
|
|
1255
|
+
warnings,
|
|
1256
|
+
events,
|
|
1257
|
+
};
|
|
1258
|
+
} finally {
|
|
1259
|
+
await rm(tmp, { recursive: true, force: true });
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/** Put a soundtrack under a rendered film without rendering it again: the
|
|
1264
|
+
* picture is copied as it is, the sound encoded as a render encodes it.
|
|
1265
|
+
* `audio` null leaves the film silent. */
|
|
1266
|
+
export async function muxFilm(opts: {
|
|
1267
|
+
film: string;
|
|
1268
|
+
audio: string | null;
|
|
1269
|
+
out: string;
|
|
1270
|
+
}): Promise<{ out: string; durationS: number }> {
|
|
1271
|
+
const film = resolve(opts.film);
|
|
1272
|
+
if (!existsSync(film)) throw new Error(`film: there is no film at ${film}`);
|
|
1273
|
+
if (opts.audio && !existsSync(resolve(opts.audio)))
|
|
1274
|
+
throw new Error(`film: the soundtrack ${resolve(opts.audio)} does not exist`);
|
|
1275
|
+
const ffmpeg = await resolveFfmpeg();
|
|
1276
|
+
const info = await probeFilm(film);
|
|
1277
|
+
const durationS = info.frames / info.fps;
|
|
1278
|
+
const tmp = await mkdtemp(join(tmpdir(), "open-take-mux-"));
|
|
1279
|
+
try {
|
|
1280
|
+
const out = join(tmp, "muxed.mp4");
|
|
1281
|
+
const args = ["-v", "error", "-y", "-i", film];
|
|
1282
|
+
// a film rendered from the middle starts its sound there too
|
|
1283
|
+
if (opts.audio) args.push("-ss", String(info.from), "-i", resolve(opts.audio));
|
|
1284
|
+
args.push("-map", "0:v", "-c:v", "copy");
|
|
1285
|
+
if (opts.audio)
|
|
1286
|
+
args.push("-map", "1:a", "-af", "apad", "-c:a", "aac", "-b:a", "256k", "-ar", "48000");
|
|
1287
|
+
args.push(
|
|
1288
|
+
"-map_metadata",
|
|
1289
|
+
"0",
|
|
1290
|
+
"-t",
|
|
1291
|
+
durationS.toFixed(6),
|
|
1292
|
+
"-movflags",
|
|
1293
|
+
"+faststart+use_metadata_tags",
|
|
1294
|
+
out,
|
|
1295
|
+
);
|
|
1296
|
+
await runTool(ffmpeg, args);
|
|
1297
|
+
await mkdir(dirname(resolve(opts.out)), { recursive: true });
|
|
1298
|
+
await moveFile(out, resolve(opts.out));
|
|
1299
|
+
return { out: resolve(opts.out), durationS };
|
|
1300
|
+
} finally {
|
|
1301
|
+
await rm(tmp, { recursive: true, force: true });
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
/** write the events file of a patched master (see patchEvents); undefined,
|
|
1306
|
+
* with a warning, when the master has none of its own to patch */
|
|
1307
|
+
async function patchedEventsFile(
|
|
1308
|
+
into: string,
|
|
1309
|
+
rangeEvents: string | undefined,
|
|
1310
|
+
out: string,
|
|
1311
|
+
warnings: string[],
|
|
1312
|
+
then: (merged: FilmEvents, master: FilmEvents) => FilmEvents = (m) => m,
|
|
1313
|
+
): Promise<string | undefined> {
|
|
1314
|
+
const read = async (file: string | undefined): Promise<FilmEvents | null> => {
|
|
1315
|
+
if (!file || !existsSync(file)) return null;
|
|
1316
|
+
try {
|
|
1317
|
+
return JSON.parse(await readFile(file, "utf8")) as FilmEvents;
|
|
1318
|
+
} catch {
|
|
1319
|
+
return null;
|
|
1320
|
+
}
|
|
1321
|
+
};
|
|
1322
|
+
const [master, patch] = await Promise.all([read(eventsPathFor(into)), read(rangeEvents)]);
|
|
1323
|
+
const merged = master && patch ? patchEvents(master, patch) : null;
|
|
1324
|
+
if (!merged) {
|
|
1325
|
+
warnings.push(
|
|
1326
|
+
`${eventsPathFor(into)} is missing or is not this master's — render the film whole for an events file`,
|
|
1327
|
+
);
|
|
1328
|
+
return undefined;
|
|
1329
|
+
}
|
|
1330
|
+
const file = eventsPathFor(out);
|
|
1331
|
+
await writeFile(file, `${JSON.stringify(then(merged, master!))}\n`);
|
|
1332
|
+
return file;
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
/** move a finished file into place — copied when it is on another disk */
|
|
1336
|
+
async function moveFile(from: string, to: string): Promise<void> {
|
|
1337
|
+
try {
|
|
1338
|
+
await rename(from, to);
|
|
1339
|
+
} catch (e) {
|
|
1340
|
+
if ((e as NodeJS.ErrnoException).code !== "EXDEV") throw e;
|
|
1341
|
+
await copyFile(from, to);
|
|
1342
|
+
await rm(from, { force: true });
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
/** an ffprobe rational ("60/1", "1/15360") as a number; 0 when there is none */
|
|
1347
|
+
function ratio(r: string | undefined): number {
|
|
1348
|
+
const [n, d] = String(r ?? "0/1")
|
|
1349
|
+
.split("/")
|
|
1350
|
+
.map(Number);
|
|
1351
|
+
return d && Number.isFinite(n) ? n! / d : 0;
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
/** a rendered film's picture: size, rate, length in frames, and the record
|
|
1355
|
+
* `film render` keeps in it (where it starts on the page's timeline) —
|
|
1356
|
+
* `made` when there is one */
|
|
1357
|
+
export async function probeFilm(file: string): Promise<{
|
|
1358
|
+
width: number;
|
|
1359
|
+
height: number;
|
|
1360
|
+
fps: number;
|
|
1361
|
+
frames: number;
|
|
1362
|
+
from: number;
|
|
1363
|
+
record: Partial<FilmRecord>;
|
|
1364
|
+
made: boolean;
|
|
1365
|
+
}> {
|
|
1366
|
+
const ffprobe = await resolveFfprobe();
|
|
1367
|
+
const p = JSON.parse(
|
|
1368
|
+
await runTool(ffprobe, [
|
|
1369
|
+
"-v",
|
|
1370
|
+
"error",
|
|
1371
|
+
"-select_streams",
|
|
1372
|
+
"v:0",
|
|
1373
|
+
"-show_entries",
|
|
1374
|
+
"stream=width,height,avg_frame_rate,r_frame_rate,nb_frames,duration:format_tags",
|
|
1375
|
+
"-of",
|
|
1376
|
+
"json",
|
|
1377
|
+
file,
|
|
1378
|
+
]),
|
|
1379
|
+
) as {
|
|
1380
|
+
streams?: {
|
|
1381
|
+
width?: number;
|
|
1382
|
+
height?: number;
|
|
1383
|
+
avg_frame_rate?: string;
|
|
1384
|
+
r_frame_rate?: string;
|
|
1385
|
+
nb_frames?: string;
|
|
1386
|
+
duration?: string;
|
|
1387
|
+
}[];
|
|
1388
|
+
format?: { tags?: Record<string, string> };
|
|
1389
|
+
};
|
|
1390
|
+
const v = p.streams?.[0];
|
|
1391
|
+
if (!v?.width || !v.height) throw new Error(`film: ${file} has no picture`);
|
|
1392
|
+
// the rate the stream names, when its average differs only as a frame a
|
|
1393
|
+
// few ticks off makes it (see framesOffIn: 30.005 for a 2 s film); the
|
|
1394
|
+
// average when the stream names none, or one far from it
|
|
1395
|
+
const avg = ratio(v.avg_frame_rate);
|
|
1396
|
+
const named = ratio(v.r_frame_rate);
|
|
1397
|
+
const fps = named > 0 && Math.abs(named - avg) <= avg * 1e-3 ? named : avg;
|
|
1398
|
+
const frames = Number(v.nb_frames) || Math.round(Number(v.duration ?? 0) * fps);
|
|
1399
|
+
let record: Partial<FilmRecord> = {};
|
|
1400
|
+
try {
|
|
1401
|
+
record = JSON.parse(p.format?.tags?.[FILM_TAG] ?? "{}") as Partial<FilmRecord>;
|
|
1402
|
+
} catch {
|
|
1403
|
+
// a film from elsewhere carries none
|
|
1404
|
+
}
|
|
1405
|
+
return {
|
|
1406
|
+
width: v.width,
|
|
1407
|
+
height: v.height,
|
|
1408
|
+
fps,
|
|
1409
|
+
frames,
|
|
1410
|
+
from: Number(record.from) || 0,
|
|
1411
|
+
record,
|
|
1412
|
+
made: typeof record.from === "number",
|
|
1413
|
+
};
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
/** why the film's picture is not as `film render` encodes it — its first
|
|
1417
|
+
* frame at 0 s, frame n at n/fps after it (a file of varying rate is not,
|
|
1418
|
+
* whatever its average); null when it is */
|
|
1419
|
+
async function framesOff(file: string): Promise<string | null> {
|
|
1420
|
+
const p = JSON.parse(
|
|
1421
|
+
await runTool(await resolveFfprobe(), [
|
|
1422
|
+
"-v",
|
|
1423
|
+
"error",
|
|
1424
|
+
"-select_streams",
|
|
1425
|
+
"v:0",
|
|
1426
|
+
"-show_entries",
|
|
1427
|
+
"stream=time_base,r_frame_rate:packet=pts",
|
|
1428
|
+
"-of",
|
|
1429
|
+
"json",
|
|
1430
|
+
file,
|
|
1431
|
+
]),
|
|
1432
|
+
) as { streams?: { time_base?: string; r_frame_rate?: string }[]; packets?: { pts?: number }[] };
|
|
1433
|
+
const tb = ratio(p.streams?.[0]?.time_base);
|
|
1434
|
+
const fps = ratio(p.streams?.[0]?.r_frame_rate);
|
|
1435
|
+
const pts = (p.packets ?? []).map((k) => Number(k.pts));
|
|
1436
|
+
return framesOffIn(pts, tb > 0 && fps > 0 ? 1 / (tb * fps) : 0);
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
/** framesOff on the picture's timestamps, `tick` of them a frame (0 when the
|
|
1440
|
+
* file names no rate: then its first step). Frame n counts as at n/fps when
|
|
1441
|
+
* it is less than half a frame from there — the frames are swapped by
|
|
1442
|
+
* number, and a master made before the chunks were placed exactly carries
|
|
1443
|
+
* one a few ticks early — and a frame missing, doubled or moved by half a
|
|
1444
|
+
* frame or more is not. */
|
|
1445
|
+
export function framesOffIn(timestamps: readonly number[], tick: number): string | null {
|
|
1446
|
+
const pts = timestamps.filter((t) => Number.isFinite(t)).sort((a, b) => a - b);
|
|
1447
|
+
if (!pts.length) return "it has no picture";
|
|
1448
|
+
if (pts[0] !== 0) return "its picture does not start at 0 s";
|
|
1449
|
+
const step = tick > 0 ? tick : (pts[1] ?? 1) - pts[0];
|
|
1450
|
+
return step > 0 && pts.every((t, i) => Math.abs(t - i * step) < step / 2)
|
|
1451
|
+
? null
|
|
1452
|
+
: "its frames are not evenly spaced";
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
/** PNG stills of the film at the given times — `t012.500.png` … — as the
|
|
1456
|
+
* master would show them. */
|
|
1457
|
+
export async function filmStills(opts: FilmStillsOptions): Promise<string[]> {
|
|
1458
|
+
const ss = supersampleOf(opts.supersample);
|
|
1459
|
+
const page = await servePage(opts, ss);
|
|
1460
|
+
try {
|
|
1461
|
+
let { browser, info, width, height } = await page.openDeclared(opts);
|
|
1462
|
+
page.checkFiles();
|
|
1463
|
+
const bake = bakeGuard("in a fresh page for the stills");
|
|
1464
|
+
await bake.check(browser);
|
|
1465
|
+
const film = describe(opts, info, {
|
|
1466
|
+
pageFile: page.pageFile,
|
|
1467
|
+
width,
|
|
1468
|
+
height,
|
|
1469
|
+
scale: 1,
|
|
1470
|
+
draft: false,
|
|
1471
|
+
stills: true,
|
|
1472
|
+
});
|
|
1473
|
+
const times = [...new Set(opts.at)].sort((a, b) => a - b);
|
|
1474
|
+
const half = SHUTTER_FRACTION / film.fps / 2;
|
|
1475
|
+
// a clock film keeps its own state and cannot go back: a still whose
|
|
1476
|
+
// shutter opens before where the page has been is taken on a fresh one
|
|
1477
|
+
let reached = 0;
|
|
1478
|
+
const from = async (t: number) => {
|
|
1479
|
+
if (info.mode === "clock" && t < reached - 1e-9) {
|
|
1480
|
+
await page.close(browser);
|
|
1481
|
+
browser = await page.open(width, height);
|
|
1482
|
+
await prepare(browser);
|
|
1483
|
+
await bake.check(browser);
|
|
1484
|
+
}
|
|
1485
|
+
};
|
|
1486
|
+
const counts: number[] = [];
|
|
1487
|
+
const sides: number[] = [];
|
|
1488
|
+
for (const t of times) {
|
|
1489
|
+
if (!film.blur) {
|
|
1490
|
+
counts.push(1);
|
|
1491
|
+
sides.push(0);
|
|
1492
|
+
} else {
|
|
1493
|
+
await from(Math.max(0, t - half));
|
|
1494
|
+
const m = await motionAt(browser, t, half);
|
|
1495
|
+
counts.push(samplesFor(m.px));
|
|
1496
|
+
sides.push(m.side);
|
|
1497
|
+
reached = t + half;
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
await mkdir(opts.outDir, { recursive: true });
|
|
1501
|
+
const ffmpeg = await resolveFfmpeg();
|
|
1502
|
+
const files: string[] = [];
|
|
1503
|
+
for (let i = 0; i < times.length; i++) {
|
|
1504
|
+
const t = times[i]!;
|
|
1505
|
+
const file = join(opts.outDir, `t${t.toFixed(3).padStart(7, "0")}.png`);
|
|
1506
|
+
const n = counts[i]!;
|
|
1507
|
+
const label = `the still at ${t}s`;
|
|
1508
|
+
const at = sampleTimes(t, n, film.fps, sides[i]);
|
|
1509
|
+
await from(at[0]!);
|
|
1510
|
+
reached = at.at(-1)!;
|
|
1511
|
+
if (n === 1 && ss === 1) {
|
|
1512
|
+
await seek(browser, t, label);
|
|
1513
|
+
await writeFile(file, await browser.screenshot({ format: "png" }));
|
|
1514
|
+
} else {
|
|
1515
|
+
const sink = new ShutterSink(
|
|
1516
|
+
ffmpeg,
|
|
1517
|
+
[n],
|
|
1518
|
+
[
|
|
1519
|
+
"-f",
|
|
1520
|
+
"rawvideo",
|
|
1521
|
+
"-pix_fmt",
|
|
1522
|
+
"rgb24",
|
|
1523
|
+
"-s",
|
|
1524
|
+
`${width}x${height}`,
|
|
1525
|
+
"-r",
|
|
1526
|
+
"1",
|
|
1527
|
+
"-i",
|
|
1528
|
+
"-",
|
|
1529
|
+
"-frames:v",
|
|
1530
|
+
"1",
|
|
1531
|
+
"-update",
|
|
1532
|
+
"1",
|
|
1533
|
+
"-y",
|
|
1534
|
+
file,
|
|
1535
|
+
],
|
|
1536
|
+
{ width, height },
|
|
1537
|
+
);
|
|
1538
|
+
try {
|
|
1539
|
+
for (const ti of at) {
|
|
1540
|
+
await seek(browser, ti, label, sampleShare(n, sides[i]));
|
|
1541
|
+
await sink.push(await browser.screenshot({ format: "jpeg", quality: 100 }));
|
|
1542
|
+
}
|
|
1543
|
+
await sink.end();
|
|
1544
|
+
} catch (e) {
|
|
1545
|
+
sink.kill();
|
|
1546
|
+
throw e;
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
files.push(file);
|
|
1550
|
+
}
|
|
1551
|
+
page.checkFiles();
|
|
1552
|
+
for (const w of await page.styleWarnings()) opts.onWarning?.(w);
|
|
1553
|
+
return files;
|
|
1554
|
+
} finally {
|
|
1555
|
+
await page.shut();
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
/** An inline style the page set that did not take, as the film clock keeps
|
|
1560
|
+
* it: the element (or rule), the CSS property, what was set, what the
|
|
1561
|
+
* property kept, and the film time (s; null before the film starts). */
|
|
1562
|
+
export type StyleReject = {
|
|
1563
|
+
el: string;
|
|
1564
|
+
prop: string;
|
|
1565
|
+
value: string;
|
|
1566
|
+
kept: string;
|
|
1567
|
+
how: "ignored" | "suspect";
|
|
1568
|
+
t: number | null;
|
|
1569
|
+
};
|
|
1570
|
+
|
|
1571
|
+
const MAX_STYLE_WARNINGS = 12;
|
|
1572
|
+
|
|
1573
|
+
/** one warning per element and property, in film time order */
|
|
1574
|
+
export function styleWarnings(list: readonly StyleReject[]): string[] {
|
|
1575
|
+
const sorted = [...list].sort((a, b) => (a.t ?? -1) - (b.t ?? -1));
|
|
1576
|
+
const out = sorted.slice(0, MAX_STYLE_WARNINGS).map((r) => {
|
|
1577
|
+
const when = r.t == null ? "before the film starts" : `at ${r.t.toFixed(3)}s`;
|
|
1578
|
+
const value = JSON.stringify(r.value.length > 120 ? `${r.value.slice(0, 117)}…` : r.value);
|
|
1579
|
+
return r.how === "suspect"
|
|
1580
|
+
? `the page set ${r.prop} on ${r.el} to ${value} ${when}: a custom property takes any text, but this reads NaN, undefined or [object …] — what uses it gets no value`
|
|
1581
|
+
: `the page set ${r.prop} on ${r.el} to ${value} ${when} and the browser ignored it: the element kept ${r.kept ? JSON.stringify(r.kept) : `no ${r.prop} of its own`}${/NaN|undefined|\[object /.test(r.value) ? " (NaN, undefined or [object …] in a value is a number that was not computed — an argument missing, or an object where a number belongs)" : ""}`;
|
|
1582
|
+
});
|
|
1583
|
+
if (sorted.length > MAX_STYLE_WARNINGS)
|
|
1584
|
+
out.push(
|
|
1585
|
+
`${sorted.length - MAX_STYLE_WARNINGS} more inline style(s) the browser ignored, on other elements or properties`,
|
|
1586
|
+
);
|
|
1587
|
+
return out;
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
/** Drops every `will-change` hint once the page is parsed (see
|
|
1591
|
+
* FilmRenderOptions.keepLayers): a layer Chrome keeps as one picture is
|
|
1592
|
+
* enlarged from it, soft, when the camera zooms in. */
|
|
1593
|
+
const DROP_LAYER_HINTS = `(() => {
|
|
1594
|
+
const add = () => {
|
|
1595
|
+
const s = document.createElement("style");
|
|
1596
|
+
s.textContent = "*, *::before, *::after { will-change: auto !important; }";
|
|
1597
|
+
(document.head || document.documentElement).appendChild(s);
|
|
1598
|
+
};
|
|
1599
|
+
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", add, { once: true });
|
|
1600
|
+
else add();
|
|
1601
|
+
})();`;
|
|
1602
|
+
|
|
1603
|
+
/** The film's page, served, and the Chromes that open it — each one with the
|
|
1604
|
+
* film clock installed, drawing `dpr` device pixels per CSS px. */
|
|
1605
|
+
async function servePage(
|
|
1606
|
+
opts: {
|
|
1607
|
+
page: string;
|
|
1608
|
+
root?: string;
|
|
1609
|
+
chromePath: string;
|
|
1610
|
+
keepLayers?: boolean;
|
|
1611
|
+
onConsole?: (level: string, text: string) => void;
|
|
1612
|
+
},
|
|
1613
|
+
dpr: number,
|
|
1614
|
+
) {
|
|
1615
|
+
const { root, pageFile, urlPath } = resolveFilmPage(opts.page, opts.root);
|
|
1616
|
+
const missing = new Set<string>();
|
|
1617
|
+
const server = await serveDirectory(root, (p) => {
|
|
1618
|
+
// the kit looks for components.json beside every shoot and take it reads
|
|
1619
|
+
// (stills(), readTake()), and does without when there is none
|
|
1620
|
+
if (!p.endsWith("/favicon.ico") && !p.endsWith("/components.json"))
|
|
1621
|
+
missing.add(decodeURIComponent(p));
|
|
1622
|
+
});
|
|
1623
|
+
const clock = filmClockSource({ seed: 0x5eed, epochMs: Date.now() });
|
|
1624
|
+
// the videos the page plays, as decoded frames (see frames.ts)
|
|
1625
|
+
const frames = frameStore({ root, server });
|
|
1626
|
+
const unframed = new Set<string>();
|
|
1627
|
+
const browsers = new Set<HtmlBrowser>();
|
|
1628
|
+
const open = async (width: number, height: number, density = dpr) => {
|
|
1629
|
+
let page: HtmlBrowser | null = null;
|
|
1630
|
+
const asked: string[] = [];
|
|
1631
|
+
const answer = (payload: string) => {
|
|
1632
|
+
if (!page) return void asked.push(payload);
|
|
1633
|
+
const b = page;
|
|
1634
|
+
let src = "";
|
|
1635
|
+
try {
|
|
1636
|
+
src = String((JSON.parse(payload) as { src?: unknown }).src ?? "");
|
|
1637
|
+
} catch {
|
|
1638
|
+
return;
|
|
1639
|
+
}
|
|
1640
|
+
const reply = (f: VideoFrames | null) =>
|
|
1641
|
+
b
|
|
1642
|
+
.evaluate(`window.__ot.framesReady(${JSON.stringify(src)}, ${JSON.stringify(f)})`)
|
|
1643
|
+
.catch(() => {});
|
|
1644
|
+
frames.frames(src).then(reply, (e: Error) => {
|
|
1645
|
+
unframed.add(`${decodeURIComponent(new URL(src, server.url).pathname)} (${e.message})`);
|
|
1646
|
+
return reply(null);
|
|
1647
|
+
});
|
|
1648
|
+
};
|
|
1649
|
+
const b = await launchHtmlBrowser({
|
|
1650
|
+
chromePath: opts.chromePath,
|
|
1651
|
+
url: `${server.url}${urlPath}`,
|
|
1652
|
+
width,
|
|
1653
|
+
height,
|
|
1654
|
+
deviceScaleFactor: density,
|
|
1655
|
+
initScript: opts.keepLayers ? clock : `${clock}\n${DROP_LAYER_HINTS}`,
|
|
1656
|
+
stillAnimations: true,
|
|
1657
|
+
onConsole: opts.onConsole,
|
|
1658
|
+
timeoutMs: 120_000,
|
|
1659
|
+
profilePrefix: "open-take-film-",
|
|
1660
|
+
bindings: { __otFrames: answer },
|
|
1661
|
+
});
|
|
1662
|
+
page = b;
|
|
1663
|
+
for (const p of asked.splice(0)) answer(p);
|
|
1664
|
+
browsers.add(b);
|
|
1665
|
+
return b;
|
|
1666
|
+
};
|
|
1667
|
+
// inline styles the page set that did not take, by element and property,
|
|
1668
|
+
// the earliest film time any Chrome saw it (see the film clock's StyleReject)
|
|
1669
|
+
const rejects = new Map<string, StyleReject>();
|
|
1670
|
+
const gather = async (b: HtmlBrowser) => {
|
|
1671
|
+
const got = await b
|
|
1672
|
+
.evaluate<StyleReject[]>("window.__ot?.styleRejects?.() ?? []")
|
|
1673
|
+
.catch(() => [] as StyleReject[]);
|
|
1674
|
+
for (const r of Array.isArray(got) ? got : []) {
|
|
1675
|
+
const k = `${r.el}\n${r.prop}`;
|
|
1676
|
+
const had = rejects.get(k);
|
|
1677
|
+
if (!had || (r.t != null && (had.t == null || r.t < had.t))) rejects.set(k, r);
|
|
1678
|
+
}
|
|
1679
|
+
};
|
|
1680
|
+
const close = async (b: HtmlBrowser) => {
|
|
1681
|
+
browsers.delete(b);
|
|
1682
|
+
await gather(b);
|
|
1683
|
+
await b.close();
|
|
1684
|
+
};
|
|
1685
|
+
return {
|
|
1686
|
+
pageFile,
|
|
1687
|
+
open,
|
|
1688
|
+
close,
|
|
1689
|
+
/** open the page and read what it is; a page that declares its own size,
|
|
1690
|
+
* when none was asked for, is opened again at that size */
|
|
1691
|
+
async openDeclared(asked: { width?: number; height?: number }) {
|
|
1692
|
+
let width = asked.width ?? DEFAULT_SIZE.width;
|
|
1693
|
+
let height = asked.height ?? DEFAULT_SIZE.height;
|
|
1694
|
+
let browser = await open(width, height);
|
|
1695
|
+
let info = await prepare(browser);
|
|
1696
|
+
if (
|
|
1697
|
+
!asked.width &&
|
|
1698
|
+
!asked.height &&
|
|
1699
|
+
info.width &&
|
|
1700
|
+
info.height &&
|
|
1701
|
+
(info.width !== width || info.height !== height)
|
|
1702
|
+
) {
|
|
1703
|
+
width = info.width;
|
|
1704
|
+
height = info.height;
|
|
1705
|
+
await close(browser);
|
|
1706
|
+
browser = await open(width, height);
|
|
1707
|
+
info = await prepare(browser);
|
|
1708
|
+
}
|
|
1709
|
+
return { browser, info, width, height };
|
|
1710
|
+
},
|
|
1711
|
+
/** a file the page asked for that is not there fails the film, by name */
|
|
1712
|
+
checkFiles() {
|
|
1713
|
+
if (missing.size) throw missingError(missing, root);
|
|
1714
|
+
},
|
|
1715
|
+
async closeAll() {
|
|
1716
|
+
for (const b of [...browsers]) await close(b);
|
|
1717
|
+
},
|
|
1718
|
+
/** videos shown by seeking the element, because their frames could not
|
|
1719
|
+
* be decoded — each with the reason */
|
|
1720
|
+
unframed: () => [...unframed],
|
|
1721
|
+
/** what the Chromes opened so far saw of inline styles that did not
|
|
1722
|
+
* take, as warnings — read from the open ones too */
|
|
1723
|
+
async styleWarnings(): Promise<string[]> {
|
|
1724
|
+
for (const b of browsers) await gather(b);
|
|
1725
|
+
return styleWarnings([...rejects.values()]);
|
|
1726
|
+
},
|
|
1727
|
+
async shut() {
|
|
1728
|
+
await Promise.all([...browsers].map((b) => b.close()));
|
|
1729
|
+
await server.close();
|
|
1730
|
+
await frames.clean();
|
|
1731
|
+
},
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
// --- the page ---------------------------------------------------------------------
|
|
1736
|
+
|
|
1737
|
+
/** the film clock ready to seek; with `fps`, the page is told the rate it is
|
|
1738
|
+
* drawn at (window.__filmFps), for what the kit counts in frames — a dip
|
|
1739
|
+
* cut's dark frames, a push cut's flash */
|
|
1740
|
+
async function prepare(b: HtmlBrowser, fps?: number): Promise<FilmPageInfo> {
|
|
1741
|
+
const has = await b.evaluate<boolean>(`typeof window.__ot === "object"`);
|
|
1742
|
+
if (!has) throw new Error("film: the film clock did not install in the page");
|
|
1743
|
+
if (fps) await b.evaluate(`window.__filmFps = ${fps}`);
|
|
1744
|
+
return b.evaluate<FilmPageInfo>("window.__ot.prepare()", { timeoutMs: 120_000 });
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
/** the share of a frame's shutter each of its `n` samples stands for: what a
|
|
1748
|
+
* page that blurs itself exposes per draw (window.__filmShare, clock.ts) */
|
|
1749
|
+
export const sampleShare = (n: number, side = 0): number =>
|
|
1750
|
+
n <= 1 ? 1 : (side === 0 ? 1 : 0.5) / n;
|
|
1751
|
+
|
|
1752
|
+
async function seek(b: HtmlBrowser, t: number, what: string, share = 1): Promise<void> {
|
|
1753
|
+
try {
|
|
1754
|
+
await b.evaluate(`window.__filmShare = ${share}; window.__ot.seek(${t})`);
|
|
1755
|
+
} catch (e) {
|
|
1756
|
+
throw new Error(`film: ${what} (${t.toFixed(3)}s): ${(e as Error).message}`, {
|
|
1757
|
+
cause: e,
|
|
1758
|
+
});
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
/** what the shutter around t sees: how far anything moves (px), and which
|
|
1763
|
+
* side of it to expose when the picture cuts in the other (see sampleTimes) */
|
|
1764
|
+
type Exposure = {
|
|
1765
|
+
px: number;
|
|
1766
|
+
side: number;
|
|
1767
|
+
text: number;
|
|
1768
|
+
textCause: TextCause | null;
|
|
1769
|
+
view: ViewRate | null;
|
|
1770
|
+
};
|
|
1771
|
+
/** the picture's zoom and pan as rates: s − 1 and t (px) a second, about the
|
|
1772
|
+
* page's top left (a point p moves (ds·p + t) a second) */
|
|
1773
|
+
export type ViewRate = {
|
|
1774
|
+
ds: number;
|
|
1775
|
+
tx: number;
|
|
1776
|
+
ty: number;
|
|
1777
|
+
/** the largest moving element's visible share of the frame */
|
|
1778
|
+
share: number;
|
|
1779
|
+
/** what of the elements' movement the zoom and pan leave unexplained, 0..1 */
|
|
1780
|
+
rigid: number;
|
|
1781
|
+
/** which element the fit followed (the largest that moved), by its place in the page */
|
|
1782
|
+
who: string;
|
|
1783
|
+
};
|
|
1784
|
+
|
|
1785
|
+
async function motionAt(b: HtmlBrowser, t: number, half: number): Promise<Exposure> {
|
|
1786
|
+
return b.evaluate<Exposure>(`window.__ot.motion(${t}, ${half})`);
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
function describe(
|
|
1790
|
+
opts: Pick<FilmRenderOptions, "fps" | "duration" | "from" | "to" | "audio" | "blur">,
|
|
1791
|
+
info: FilmPageInfo,
|
|
1792
|
+
at: {
|
|
1793
|
+
pageFile: string;
|
|
1794
|
+
width: number;
|
|
1795
|
+
height: number;
|
|
1796
|
+
scale: number;
|
|
1797
|
+
draft: boolean;
|
|
1798
|
+
/** stills: no length needed, and no soundtrack */
|
|
1799
|
+
stills?: boolean;
|
|
1800
|
+
},
|
|
1801
|
+
): Film {
|
|
1802
|
+
const warnings: string[] = [];
|
|
1803
|
+
const fps = opts.fps ?? (at.draft ? 30 : (info.fps ?? 60));
|
|
1804
|
+
const durationS = opts.duration ?? info.duration;
|
|
1805
|
+
if (!durationS && !at.stills)
|
|
1806
|
+
throw new Error(
|
|
1807
|
+
"film: how long is the film? Declare it in the page — window.__film = { duration: <seconds> } — or pass --duration",
|
|
1808
|
+
);
|
|
1809
|
+
const end = Math.min(opts.to ?? durationS ?? 0, durationS ?? Number.POSITIVE_INFINITY);
|
|
1810
|
+
const from = opts.from ?? 0;
|
|
1811
|
+
const f0 = Math.round(from * fps);
|
|
1812
|
+
const f1 = Math.round(end * fps);
|
|
1813
|
+
if (!at.stills && !(f1 > f0))
|
|
1814
|
+
throw new Error(`film: nothing to render between ${from}s and ${end}s`);
|
|
1815
|
+
let audio: string | null = null;
|
|
1816
|
+
if (!at.stills) {
|
|
1817
|
+
if (typeof opts.audio === "string") audio = resolve(opts.audio);
|
|
1818
|
+
else if (opts.audio !== null && info.audio)
|
|
1819
|
+
audio = resolve(dirname(at.pageFile), decodeURI(info.audio.split("?")[0]!));
|
|
1820
|
+
if (audio && !existsSync(audio))
|
|
1821
|
+
throw new Error(`film: the soundtrack ${audio} does not exist`);
|
|
1822
|
+
if (!audio)
|
|
1823
|
+
warnings.push("no soundtrack — the film is silent (window.__film.audio or --audio)");
|
|
1824
|
+
if (info.tickers.length) {
|
|
1825
|
+
const many = info.tickers.length > 1;
|
|
1826
|
+
const owner = many ? "their" : "its";
|
|
1827
|
+
const tickerName = many ? "tickers" : "ticker";
|
|
1828
|
+
const seek = info.tickers.map((ticker) =>
|
|
1829
|
+
ticker === "GSAP"
|
|
1830
|
+
? "GSAP timeline.seek(t) or timeline.totalTime(t)"
|
|
1831
|
+
: "anime.js animation.seek(t*1000)",
|
|
1832
|
+
);
|
|
1833
|
+
warnings.push(
|
|
1834
|
+
`${info.tickers.join(" and ")} running on ${owner} own ${tickerName} in clock mode: ${owner} motion gets no blur, and frames cannot be probed in parallel. Seek in window.__render(t) with ${seek.join(" and ")} to enable both.`,
|
|
1835
|
+
);
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
if (info.audioElements)
|
|
1839
|
+
warnings.push(
|
|
1840
|
+
`the page has ${info.audioElements} <audio> element(s); a render records picture only — ` +
|
|
1841
|
+
"declare the soundtrack instead (window.__film.audio or --audio)",
|
|
1842
|
+
);
|
|
1843
|
+
return {
|
|
1844
|
+
width: at.width,
|
|
1845
|
+
height: at.height,
|
|
1846
|
+
fps,
|
|
1847
|
+
scale: at.scale,
|
|
1848
|
+
f0,
|
|
1849
|
+
f1,
|
|
1850
|
+
total: Math.round((durationS ?? 0) * fps),
|
|
1851
|
+
audio,
|
|
1852
|
+
blur: opts.blur ?? !at.draft,
|
|
1853
|
+
// checked here, before a frame is drawn: a mark the author meant to make
|
|
1854
|
+
// and mistyped would otherwise only surface as a defect after the render
|
|
1855
|
+
marks: filmMarks(info.marks),
|
|
1856
|
+
warnings,
|
|
1857
|
+
};
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
/** the supersampling factor asked for: a whole number of pixels each way, 1–4 */
|
|
1861
|
+
function supersampleOf(v: number | undefined): number {
|
|
1862
|
+
if (v === undefined) return 1;
|
|
1863
|
+
if (!Number.isFinite(v) || v < 1 || v > 4 || Math.round(v) !== v)
|
|
1864
|
+
throw new Error(`film: supersample is a whole number from 1 to 4, not ${v}`);
|
|
1865
|
+
return v;
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
function defaultWorkers(): number {
|
|
1869
|
+
// measured on a 10-core Mac: 2 → 4 workers gained 6 %, 6 lost 20 % — Chrome's
|
|
1870
|
+
// screenshot path is the shared bottleneck, not the CPU — and a 16 GB Mac
|
|
1871
|
+
// lost a Chrome to memory pressure at 3
|
|
1872
|
+
return Math.max(1, Math.min(2, Math.floor(cpus().length / 2)));
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
/** every frame's shutter samples and the side of the shutter they are spread
|
|
1876
|
+
* over, probed by the pool's browsers in turn */
|
|
1877
|
+
async function probe(
|
|
1878
|
+
pool: HtmlBrowser[],
|
|
1879
|
+
film: Film,
|
|
1880
|
+
onProgress?: (p: FilmProgress) => void,
|
|
1881
|
+
) {
|
|
1882
|
+
const frames = film.f1 - film.f0;
|
|
1883
|
+
const samples = new Array<number>(frames).fill(1);
|
|
1884
|
+
const sides = new Array<number>(frames).fill(0);
|
|
1885
|
+
const text = new Array<number>(frames).fill(0);
|
|
1886
|
+
const textCause = new Array<TextCause | null>(frames).fill(null);
|
|
1887
|
+
const view = new Array<ViewRate | null>(frames).fill(null);
|
|
1888
|
+
const half = SHUTTER_FRACTION / film.fps / 2;
|
|
1889
|
+
let next = 0;
|
|
1890
|
+
let done = 0;
|
|
1891
|
+
await Promise.all(
|
|
1892
|
+
pool.map(async (b) => {
|
|
1893
|
+
for (;;) {
|
|
1894
|
+
const i = next++;
|
|
1895
|
+
if (i >= frames) return;
|
|
1896
|
+
const m = await motionAt(b, (film.f0 + i) / film.fps, half);
|
|
1897
|
+
samples[i] = samplesFor(m.px);
|
|
1898
|
+
sides[i] = m.side;
|
|
1899
|
+
text[i] = m.text ?? 0;
|
|
1900
|
+
textCause[i] = m.textCause ?? null;
|
|
1901
|
+
view[i] = m.view ?? null;
|
|
1902
|
+
done++;
|
|
1903
|
+
if (done % 30 === 0 || done === frames)
|
|
1904
|
+
onProgress?.({ phase: "probe", done, total: frames });
|
|
1905
|
+
}
|
|
1906
|
+
}),
|
|
1907
|
+
);
|
|
1908
|
+
return { samples, sides, text, textCause, view };
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
/** A move of the picture where what it ends up framing does not head
|
|
1912
|
+
* straight for its place: it goes the wrong way first (`back`), or past and
|
|
1913
|
+
* back (`past`), by `px` on `axis`. Times on the page's timeline. */
|
|
1914
|
+
export type TurnBack = {
|
|
1915
|
+
from: number;
|
|
1916
|
+
to: number;
|
|
1917
|
+
at: number;
|
|
1918
|
+
axis: "x" | "y";
|
|
1919
|
+
kind: "back" | "past";
|
|
1920
|
+
px: number;
|
|
1921
|
+
};
|
|
1922
|
+
|
|
1923
|
+
/** Each run of frames where the picture moves (its zoom and pan, `view`, as
|
|
1924
|
+
* the motion probe fitted them), ended by a cut or a stop: the point at the
|
|
1925
|
+
* middle of the frame when it ends is followed back through it, and where
|
|
1926
|
+
* it went the wrong way, or past its place and back, by `min` px or more,
|
|
1927
|
+
* that is said. A camera that moves its centre and its zoom apart, or keeps
|
|
1928
|
+
* inside the page by clamping every frame, does this; a move straight to its
|
|
1929
|
+
* view does not. */
|
|
1930
|
+
export function turnsBack(
|
|
1931
|
+
view: readonly (ViewRate | null)[],
|
|
1932
|
+
sides: readonly number[],
|
|
1933
|
+
fps: number,
|
|
1934
|
+
size: { width: number; height: number },
|
|
1935
|
+
f0 = 0,
|
|
1936
|
+
min = 8,
|
|
1937
|
+
): TurnBack[] {
|
|
1938
|
+
const n = view.length;
|
|
1939
|
+
const c = { x: size.width / 2, y: size.height / 2 };
|
|
1940
|
+
const moving = view.map((v) => {
|
|
1941
|
+
// a picture moving, not a cursor or a caption: a tenth of the frame or more
|
|
1942
|
+
// moving as a whole, as under a camera: not shapes changing on their own
|
|
1943
|
+
if (!v || !(v.share >= 0.1) || !(v.rigid < 0.25)) return false;
|
|
1944
|
+
const sx = v.ds * c.x + v.tx;
|
|
1945
|
+
const sy = v.ds * c.y + v.ty;
|
|
1946
|
+
return Math.hypot(sx, sy) > 20 || Math.abs(v.ds) > 0.05;
|
|
1947
|
+
});
|
|
1948
|
+
const out: TurnBack[] = [];
|
|
1949
|
+
for (let a = 0; a < n; ) {
|
|
1950
|
+
if (!moving[a]) {
|
|
1951
|
+
a++;
|
|
1952
|
+
continue;
|
|
1953
|
+
}
|
|
1954
|
+
let b = a + 1;
|
|
1955
|
+
// a run ends where the picture stops, or jumps (a cut, or the camera
|
|
1956
|
+
// cut to another view: a tenth of the frame in one frame) — not at every
|
|
1957
|
+
// shutter the probe kept to one side (a caption appearing does that)
|
|
1958
|
+
const jump = (i: number) => {
|
|
1959
|
+
const v = view[i]!;
|
|
1960
|
+
return (
|
|
1961
|
+
sides[i] !== 0 && Math.hypot(v.ds * c.x + v.tx, v.ds * c.y + v.ty) / fps > size.width / 10
|
|
1962
|
+
);
|
|
1963
|
+
};
|
|
1964
|
+
// …or where the element followed is another one (a tile shrinking into a
|
|
1965
|
+
// grid as others grow in is not one picture moving)
|
|
1966
|
+
while (b < n && moving[b] && !jump(b) && view[b]!.who === view[a]!.who) b++;
|
|
1967
|
+
// one move after another without a stop (a camera that starts the next
|
|
1968
|
+
// from wherever it is): each is its own, split where the picture is
|
|
1969
|
+
// slowest between two faster stretches
|
|
1970
|
+
const speed = (i: number) => {
|
|
1971
|
+
const v = view[i]!;
|
|
1972
|
+
return Math.hypot(v.ds * c.x + v.tx, v.ds * c.y + v.ty) + Math.abs(v.ds) * c.x;
|
|
1973
|
+
};
|
|
1974
|
+
const cutsAt: number[] = [];
|
|
1975
|
+
for (let i = a + 1; i < b - 1; i++) {
|
|
1976
|
+
const s0 = speed(i);
|
|
1977
|
+
if (!(s0 <= speed(i - 1) && s0 <= speed(i + 1))) continue;
|
|
1978
|
+
let before = 0;
|
|
1979
|
+
let after = 0;
|
|
1980
|
+
for (let k = a; k < i; k++) before = Math.max(before, speed(k));
|
|
1981
|
+
for (let k = i + 1; k < b; k++) after = Math.max(after, speed(k));
|
|
1982
|
+
if (s0 < 0.25 * before && s0 < 0.25 * after) cutsAt.push(i);
|
|
1983
|
+
}
|
|
1984
|
+
const moves: [number, number][] = [];
|
|
1985
|
+
let m0 = a;
|
|
1986
|
+
for (const i of cutsAt) {
|
|
1987
|
+
moves.push([m0, i]);
|
|
1988
|
+
m0 = i;
|
|
1989
|
+
}
|
|
1990
|
+
moves.push([m0, b]);
|
|
1991
|
+
for (const [ma, mb] of moves) out.push(...turnsIn(ma, mb));
|
|
1992
|
+
a = b;
|
|
1993
|
+
}
|
|
1994
|
+
return out;
|
|
1995
|
+
|
|
1996
|
+
function turnsIn(a: number, b: number): TurnBack[] {
|
|
1997
|
+
const out: TurnBack[] = [];
|
|
1998
|
+
if (b - a >= 6) {
|
|
1999
|
+
// back from the end: where the point that ends in the middle was
|
|
2000
|
+
const path: { x: number; y: number }[] = [];
|
|
2001
|
+
let q = { ...c };
|
|
2002
|
+
path.unshift({ ...q });
|
|
2003
|
+
for (let i = b - 1; i >= a; i--) {
|
|
2004
|
+
const v = view[i]!;
|
|
2005
|
+
q = { x: q.x - (v.ds * q.x + v.tx) / fps, y: q.y - (v.ds * q.y + v.ty) / fps };
|
|
2006
|
+
path.unshift({ ...q });
|
|
2007
|
+
}
|
|
2008
|
+
for (const axis of ["x", "y"] as const) {
|
|
2009
|
+
const xs = path.map((p) => p[axis]);
|
|
2010
|
+
const start = xs[0]!;
|
|
2011
|
+
const end = xs.at(-1)!;
|
|
2012
|
+
const up = end >= start;
|
|
2013
|
+
const lo = up ? Math.min(...xs) : Math.max(...xs);
|
|
2014
|
+
const hi = up ? Math.max(...xs) : Math.min(...xs);
|
|
2015
|
+
const t = (k: number) => Math.round(((f0 + a + k) / fps) * 1000) / 1000;
|
|
2016
|
+
const back = Math.abs(start - lo);
|
|
2017
|
+
if (back >= min)
|
|
2018
|
+
out.push({
|
|
2019
|
+
from: t(0),
|
|
2020
|
+
to: t(b - a),
|
|
2021
|
+
at: t(xs.indexOf(lo)),
|
|
2022
|
+
axis,
|
|
2023
|
+
kind: "back",
|
|
2024
|
+
px: Math.round(back),
|
|
2025
|
+
});
|
|
2026
|
+
const past = Math.abs(hi - end);
|
|
2027
|
+
if (past >= min)
|
|
2028
|
+
out.push({
|
|
2029
|
+
from: t(0),
|
|
2030
|
+
to: t(b - a),
|
|
2031
|
+
at: t(xs.indexOf(hi)),
|
|
2032
|
+
axis,
|
|
2033
|
+
kind: "past",
|
|
2034
|
+
px: Math.round(past),
|
|
2035
|
+
});
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
return out;
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
/** how finely the frames where text moves slowly are drawn: what stopped the
|
|
2043
|
+
* visible stepping in a blind check (two stretches of one film) */
|
|
2044
|
+
export const FINE_SUPERSAMPLE = 3;
|
|
2045
|
+
/** a frame drawn at FINE_SUPERSAMPLE costs about this many of one at the
|
|
2046
|
+
* film's size (measured 4.8× and 6.8× on two stretches of one film) */
|
|
2047
|
+
const FINE_COST = 5;
|
|
2048
|
+
|
|
2049
|
+
/** Where finer drawing is planned, and which slow text set it off. Frames
|
|
2050
|
+
* kept at that density through a gap or up to a cut count toward the time. */
|
|
2051
|
+
export function finePlan(
|
|
2052
|
+
flags: readonly boolean[],
|
|
2053
|
+
causes: readonly (TextCause | null)[],
|
|
2054
|
+
fps: number,
|
|
2055
|
+
f0 = 0,
|
|
2056
|
+
): FilmFinePlan {
|
|
2057
|
+
const ranges: FilmFinePlan["ranges"] = [];
|
|
2058
|
+
// Count by element and keep the first label it showed.
|
|
2059
|
+
const counts = new Map<string, { label: string; frames: number }>();
|
|
2060
|
+
let frames = 0;
|
|
2061
|
+
for (let i = 0; i < flags.length; ) {
|
|
2062
|
+
if (!flags[i]) {
|
|
2063
|
+
i++;
|
|
2064
|
+
continue;
|
|
2065
|
+
}
|
|
2066
|
+
const from = i;
|
|
2067
|
+
for (; flags[i]; i++) {
|
|
2068
|
+
const cause = causes[i];
|
|
2069
|
+
if (!cause) continue;
|
|
2070
|
+
const seen = counts.get(cause.key);
|
|
2071
|
+
if (seen) seen.frames++;
|
|
2072
|
+
else counts.set(cause.key, { label: cause.label, frames: 1 });
|
|
2073
|
+
}
|
|
2074
|
+
frames += i - from;
|
|
2075
|
+
ranges.push({ from: secs6((f0 + from) / fps), to: secs6((f0 + i) / fps) });
|
|
2076
|
+
}
|
|
2077
|
+
return {
|
|
2078
|
+
seconds: frames / fps,
|
|
2079
|
+
supersample: FINE_SUPERSAMPLE,
|
|
2080
|
+
ranges,
|
|
2081
|
+
causes: Array.from(counts.values(), ({ label, frames }) => ({ element: label, frames }))
|
|
2082
|
+
.sort((a, b) => b.frames - a.frames),
|
|
2083
|
+
};
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
/** The line a render prints before drawing: how many seconds it draws
|
|
2087
|
+
* finer, which text set that off, and the estimated cost per frame. */
|
|
2088
|
+
export function finePlanLine(plan: FilmFinePlan): string {
|
|
2089
|
+
const names = plan.causes.slice(0, 3).map((c) => c.element).join(", ");
|
|
2090
|
+
const more = plan.causes.length > 3 ? ` and ${plan.causes.length - 3} more` : "";
|
|
2091
|
+
return `film: ${plan.seconds.toFixed(2)} s at ${plan.supersample}× for slow text${names ? ` in ${names}${more}` : ""} (about ${FINE_COST}× the cost per frame)`;
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
const slowTextFrame = (d: number) => d >= 0.001 && d < 1;
|
|
2095
|
+
|
|
2096
|
+
/** Which frames to draw finer: those where the page's moving text moves
|
|
2097
|
+
* under one device pixel a frame (`text`: px a second, as the page's
|
|
2098
|
+
* motion probe found it; `density`: device px per page px) — the slow push,
|
|
2099
|
+
* the ease into and out of a move, the long settle at its end, where a
|
|
2100
|
+
* thousandth of a pixel a frame still ends in a step — joined across gaps
|
|
2101
|
+
* of up to a quarter second, runs of under six frames left out. Each run
|
|
2102
|
+
* then reaches back and on to where a change of density does not show:
|
|
2103
|
+
* a cut (`sides`, as the probe found them), text moving a pixel a frame
|
|
2104
|
+
* or more, or FINE_REACH seconds. */
|
|
2105
|
+
export function fineFrames(
|
|
2106
|
+
text: readonly number[],
|
|
2107
|
+
sides: readonly number[],
|
|
2108
|
+
fps: number,
|
|
2109
|
+
density: number,
|
|
2110
|
+
): boolean[] {
|
|
2111
|
+
const n = text.length;
|
|
2112
|
+
const speed = text.map((v) => (v / fps) * density);
|
|
2113
|
+
const slow = speed.map(slowTextFrame);
|
|
2114
|
+
const out = slow.slice();
|
|
2115
|
+
const gap = Math.round(fps / 4);
|
|
2116
|
+
let last = -1;
|
|
2117
|
+
for (let i = 0; i < n; i++)
|
|
2118
|
+
if (slow[i]) {
|
|
2119
|
+
if (last >= 0 && i - last > 1 && i - last <= gap + 1)
|
|
2120
|
+
for (let j = last + 1; j < i; j++) out[j] = true;
|
|
2121
|
+
last = i;
|
|
2122
|
+
}
|
|
2123
|
+
const runs: [number, number][] = [];
|
|
2124
|
+
for (let i = 0; i < n; ) {
|
|
2125
|
+
if (!out[i]) {
|
|
2126
|
+
i++;
|
|
2127
|
+
continue;
|
|
2128
|
+
}
|
|
2129
|
+
let j = i;
|
|
2130
|
+
while (j < n && out[j]) j++;
|
|
2131
|
+
if (j - i >= 6) runs.push([i, j]);
|
|
2132
|
+
i = j;
|
|
2133
|
+
}
|
|
2134
|
+
const reach = Math.round(FINE_REACH * fps);
|
|
2135
|
+
const fine = new Array<boolean>(n).fill(false);
|
|
2136
|
+
for (let [a, b] of runs) {
|
|
2137
|
+
// side 1: frame j is the first of a new picture; -1: the last of one
|
|
2138
|
+
for (let k = 0; k < reach && a > 0 && sides[a]! <= 0 && sides[a - 1]! >= 0; k++) {
|
|
2139
|
+
if (speed[a - 1]! >= 1) break;
|
|
2140
|
+
a--;
|
|
2141
|
+
}
|
|
2142
|
+
for (let k = 0; k < reach && b < n && sides[b - 1]! >= 0 && sides[b]! <= 0; k++) {
|
|
2143
|
+
if (speed[b]! >= 1) break;
|
|
2144
|
+
b++;
|
|
2145
|
+
}
|
|
2146
|
+
for (let i = a; i < b; i++) fine[i] = true;
|
|
2147
|
+
}
|
|
2148
|
+
return fine;
|
|
2149
|
+
}
|
|
2150
|
+
/** how far a run of finer frames reaches for a place to change density (s) */
|
|
2151
|
+
const FINE_REACH = 2;
|
|
2152
|
+
|
|
2153
|
+
// --- encoding -------------------------------------------------------------------------
|
|
2154
|
+
|
|
2155
|
+
/** the film's frames, in pixels (screenshots are this × the supersampling) */
|
|
2156
|
+
const outSize = (film: Film) => ({
|
|
2157
|
+
width: Math.round(film.width * film.scale),
|
|
2158
|
+
height: Math.round(film.height * film.scale),
|
|
2159
|
+
});
|
|
2160
|
+
|
|
2161
|
+
function encodeArgs(film: Film, out: string, draft: boolean): string[] {
|
|
2162
|
+
// H.264 wants even sides, so an odd one is padded
|
|
2163
|
+
const { width: w, height: h } = outSize(film);
|
|
2164
|
+
return [
|
|
2165
|
+
"-f",
|
|
2166
|
+
"rawvideo",
|
|
2167
|
+
"-pix_fmt",
|
|
2168
|
+
"rgb24",
|
|
2169
|
+
"-s",
|
|
2170
|
+
`${w}x${h}`,
|
|
2171
|
+
"-r",
|
|
2172
|
+
String(film.fps),
|
|
2173
|
+
"-i",
|
|
2174
|
+
"-",
|
|
2175
|
+
"-vf",
|
|
2176
|
+
// the screenshots' sRGB values as limited-range BT.709, rounded exactly
|
|
2177
|
+
// and named sRGB (see SRGB_TAGS)
|
|
2178
|
+
`pad=ceil(iw/2)*2:ceil(ih/2)*2,scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int,format=yuv420p,${SRGB_TAGS}`,
|
|
2179
|
+
"-c:v",
|
|
2180
|
+
"libx264",
|
|
2181
|
+
"-preset",
|
|
2182
|
+
draft ? "veryfast" : "medium",
|
|
2183
|
+
"-crf",
|
|
2184
|
+
draft ? "23" : "14",
|
|
2185
|
+
"-x264-params",
|
|
2186
|
+
`keyint=${film.fps * 2}:min-keyint=1:aq-mode=3`,
|
|
2187
|
+
...SRGB_TAG_ARGS,
|
|
2188
|
+
"-y",
|
|
2189
|
+
out,
|
|
2190
|
+
];
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
/** an encoded piece of the film and how many frames it holds */
|
|
2194
|
+
export type FilmChunk = { file: string; frames: number };
|
|
2195
|
+
|
|
2196
|
+
/** The concat list that joins the chunks: each with its length named, from
|
|
2197
|
+
* the frames before it, so chunk k starts at exactly its first frame's time.
|
|
2198
|
+
* Left to itself the concat demuxer starts a chunk where the one before says
|
|
2199
|
+
* it ends — and an MP4 can say a few ticks short (its edit list is in ms: 89
|
|
2200
|
+
* frames at 60 fps end at 1.483 s, not 1.48333), which put one frame of a
|
|
2201
|
+
* whole render 5 ticks early. The lengths are whole µs (what the demuxer
|
|
2202
|
+
* keeps), rounded from the running total, so their sum never drifts. */
|
|
2203
|
+
export function chunkList(chunks: readonly FilmChunk[], fps: number): string {
|
|
2204
|
+
const us = (n: number) => Math.round((n * 1e6) / fps);
|
|
2205
|
+
let before = 0;
|
|
2206
|
+
return chunks
|
|
2207
|
+
.map((c) => {
|
|
2208
|
+
const len = us(before + c.frames) - us(before);
|
|
2209
|
+
before += c.frames;
|
|
2210
|
+
return `file '${c.file.replace(/'/g, "'\\''")}'\nduration ${(len / 1e6).toFixed(6)}`;
|
|
2211
|
+
})
|
|
2212
|
+
.join("\n");
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2215
|
+
async function deliver(
|
|
2216
|
+
ffmpeg: string,
|
|
2217
|
+
chunks: readonly FilmChunk[],
|
|
2218
|
+
film: Film,
|
|
2219
|
+
out: string,
|
|
2220
|
+
tmp: string,
|
|
2221
|
+
): Promise<void> {
|
|
2222
|
+
const list = join(tmp, "chunks.txt");
|
|
2223
|
+
await writeFile(list, chunkList(chunks, film.fps));
|
|
2224
|
+
await mkdir(dirname(resolve(out)), { recursive: true });
|
|
2225
|
+
const durationS = (film.f1 - film.f0) / film.fps;
|
|
2226
|
+
const args = ["-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", list];
|
|
2227
|
+
if (film.audio) args.push("-ss", String(film.f0 / film.fps), "-i", film.audio);
|
|
2228
|
+
args.push("-map", "0:v", "-c:v", "copy");
|
|
2229
|
+
if (film.audio)
|
|
2230
|
+
args.push("-map", "1:a", "-af", "apad", "-c:a", "aac", "-b:a", "256k", "-ar", "48000");
|
|
2231
|
+
const record: FilmRecord = {
|
|
2232
|
+
from: film.f0 / film.fps,
|
|
2233
|
+
width: film.width,
|
|
2234
|
+
height: film.height,
|
|
2235
|
+
marks: film.marks,
|
|
2236
|
+
};
|
|
2237
|
+
args.push("-metadata", `${FILM_TAG}=${JSON.stringify(record)}`);
|
|
2238
|
+
// a key of our own is written only with use_metadata_tags
|
|
2239
|
+
args.push("-t", durationS.toFixed(6), "-movflags", "+faststart+use_metadata_tags", resolve(out));
|
|
2240
|
+
await runTool(ffmpeg, args);
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
// sRGB ↔ linear light, for averaging samples the way light adds up
|
|
2244
|
+
const TO_LINEAR = new Float32Array(256);
|
|
2245
|
+
for (let i = 0; i < 256; i++) {
|
|
2246
|
+
const c = i / 255;
|
|
2247
|
+
TO_LINEAR[i] = c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
2248
|
+
}
|
|
2249
|
+
const LUT = 8192;
|
|
2250
|
+
const TO_SRGB = new Float32Array(LUT + 2);
|
|
2251
|
+
for (let i = 0; i <= LUT + 1; i++) {
|
|
2252
|
+
const c = Math.min(1, i / LUT);
|
|
2253
|
+
TO_SRGB[i] = (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055) * 255;
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
/** Wait for a full pipe to drain — or for the processes behind it to end,
|
|
2257
|
+
* which would leave the wait for "drain" pending forever and the render
|
|
2258
|
+
* stuck where no retry can reach it. */
|
|
2259
|
+
export function drainOrFail(stream: NodeJS.WritableStream, ended: Promise<unknown>): Promise<void> {
|
|
2260
|
+
return new Promise<void>((ok, fail) => {
|
|
2261
|
+
const drained = () => ok();
|
|
2262
|
+
stream.once("drain", drained);
|
|
2263
|
+
ended.then(
|
|
2264
|
+
() => {
|
|
2265
|
+
stream.removeListener("drain", drained);
|
|
2266
|
+
fail(new Error("film: ffmpeg ended before the samples did"));
|
|
2267
|
+
},
|
|
2268
|
+
(e) => {
|
|
2269
|
+
stream.removeListener("drain", drained);
|
|
2270
|
+
fail(e);
|
|
2271
|
+
},
|
|
2272
|
+
);
|
|
2273
|
+
});
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
/** Screenshots in, finished frames out: JPEG samples are decoded by one ffmpeg,
|
|
2277
|
+
* each output frame's `schedule[n]` samples are averaged in linear light (with
|
|
2278
|
+
* triangular dither back to 8 bits), and the frames go to an encoding ffmpeg
|
|
2279
|
+
* run with `encodeArgs`. Backpressure flows end to end. */
|
|
2280
|
+
class ShutterSink {
|
|
2281
|
+
private decoder: ChildProcess;
|
|
2282
|
+
private encoder: ChildProcess;
|
|
2283
|
+
private headWritten = false;
|
|
2284
|
+
private sampleIndex = 0;
|
|
2285
|
+
private pending: Buffer[] = [];
|
|
2286
|
+
private pendingBytes = 0;
|
|
2287
|
+
private frameBytes = 0;
|
|
2288
|
+
private frame = 0;
|
|
2289
|
+
private got = 0;
|
|
2290
|
+
private acc: Float32Array | null = null;
|
|
2291
|
+
private rng = 0x9e3779b9;
|
|
2292
|
+
private readonly finished: Promise<void>;
|
|
2293
|
+
private error: Error | null = null;
|
|
2294
|
+
|
|
2295
|
+
constructor(
|
|
2296
|
+
ffmpeg: string,
|
|
2297
|
+
private readonly schedule: readonly number[],
|
|
2298
|
+
encodeArgs: string[],
|
|
2299
|
+
/** the film's frame: samples drawn at more pixels are scaled down to it */
|
|
2300
|
+
size: { width: number; height: number },
|
|
2301
|
+
) {
|
|
2302
|
+
this.frameBytes = size.width * size.height * 3;
|
|
2303
|
+
this.decoder = spawn(
|
|
2304
|
+
ffmpeg,
|
|
2305
|
+
[
|
|
2306
|
+
"-v",
|
|
2307
|
+
"error",
|
|
2308
|
+
"-f",
|
|
2309
|
+
"matroska",
|
|
2310
|
+
"-i",
|
|
2311
|
+
"-",
|
|
2312
|
+
"-fps_mode",
|
|
2313
|
+
"passthrough",
|
|
2314
|
+
"-vf",
|
|
2315
|
+
// area averaging: a supersampled frame's 2×2 (3×3…) device pixels become one
|
|
2316
|
+
`scale=${size.width}:${size.height}:in_range=pc:in_color_matrix=bt601:flags=area+accurate_rnd+full_chroma_int,format=rgb24`,
|
|
2317
|
+
"-f",
|
|
2318
|
+
"rawvideo",
|
|
2319
|
+
"-",
|
|
2320
|
+
],
|
|
2321
|
+
{ stdio: ["pipe", "pipe", "pipe"] },
|
|
2322
|
+
);
|
|
2323
|
+
this.encoder = spawn(ffmpeg, ["-v", "error", ...encodeArgs], {
|
|
2324
|
+
stdio: ["pipe", "ignore", "pipe"],
|
|
2325
|
+
});
|
|
2326
|
+
const watch = (p: ChildProcess, name: string) =>
|
|
2327
|
+
new Promise<void>((ok, fail) => {
|
|
2328
|
+
let err = "";
|
|
2329
|
+
p.stderr?.on("data", (d: Buffer) => {
|
|
2330
|
+
err = (err + d.toString()).slice(-4000);
|
|
2331
|
+
});
|
|
2332
|
+
p.on("error", fail);
|
|
2333
|
+
p.on("close", (code, signal) => {
|
|
2334
|
+
if (code === 0) ok();
|
|
2335
|
+
else {
|
|
2336
|
+
const e = new Error(
|
|
2337
|
+
`film: ffmpeg ${name} exited ${code ?? signal}: ${err.trim().slice(-600)}`,
|
|
2338
|
+
);
|
|
2339
|
+
this.error ??= e;
|
|
2340
|
+
fail(e);
|
|
2341
|
+
}
|
|
2342
|
+
});
|
|
2343
|
+
});
|
|
2344
|
+
const decoded = watch(this.decoder, "decoder");
|
|
2345
|
+
const encoded = watch(this.encoder, "encoder");
|
|
2346
|
+
// a write after ffmpeg has gone (EPIPE) is not the error worth reporting:
|
|
2347
|
+
// its exit code is, through watch() above
|
|
2348
|
+
this.decoder.stdin?.on("error", () => {});
|
|
2349
|
+
this.encoder.stdin?.on("error", () => {});
|
|
2350
|
+
this.decoder.stdout?.on("data", (chunk: Buffer) => this.onData(chunk));
|
|
2351
|
+
this.decoder.stdout?.on("end", () => {
|
|
2352
|
+
this.encoder.stdin?.end();
|
|
2353
|
+
});
|
|
2354
|
+
this.finished = Promise.all([decoded, encoded]).then(() => {
|
|
2355
|
+
if (this.frame !== this.schedule.length)
|
|
2356
|
+
throw new Error(
|
|
2357
|
+
`film: ${this.frame} of ${this.schedule.length} frames came out of the shutter`,
|
|
2358
|
+
);
|
|
2359
|
+
});
|
|
2360
|
+
// push() and end() report a failure; a piece given up without end() must
|
|
2361
|
+
// not leave it unhandled
|
|
2362
|
+
this.finished.catch(() => {});
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
/** one sample (a JPEG screenshot), in order */
|
|
2366
|
+
async push(jpeg: Buffer): Promise<void> {
|
|
2367
|
+
if (this.error) throw this.error;
|
|
2368
|
+
const stdin = this.decoder.stdin!;
|
|
2369
|
+
if (!this.headWritten) {
|
|
2370
|
+
const { width, height } = jpegDimensions(jpeg);
|
|
2371
|
+
this.headWritten = true;
|
|
2372
|
+
stdin.write(matroskaHead(width, height, 0));
|
|
2373
|
+
}
|
|
2374
|
+
if (!stdin.write(matroskaCluster(this.sampleIndex++, jpeg)))
|
|
2375
|
+
await drainOrFail(stdin, this.finished);
|
|
2376
|
+
}
|
|
2377
|
+
|
|
2378
|
+
async end(): Promise<void> {
|
|
2379
|
+
this.decoder.stdin?.end();
|
|
2380
|
+
await this.finished;
|
|
2381
|
+
}
|
|
2382
|
+
|
|
2383
|
+
kill(): void {
|
|
2384
|
+
for (const p of [this.decoder, this.encoder])
|
|
2385
|
+
try {
|
|
2386
|
+
p.kill("SIGKILL");
|
|
2387
|
+
} catch {
|
|
2388
|
+
/* gone */
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
private onData(chunk: Buffer): void {
|
|
2393
|
+
this.pending.push(chunk);
|
|
2394
|
+
this.pendingBytes += chunk.length;
|
|
2395
|
+
while (this.frameBytes && this.pendingBytes >= this.frameBytes) {
|
|
2396
|
+
const whole = Buffer.concat(this.pending, this.pendingBytes);
|
|
2397
|
+
const sample = whole.subarray(0, this.frameBytes);
|
|
2398
|
+
const rest = whole.subarray(this.frameBytes);
|
|
2399
|
+
this.pending = rest.length ? [rest] : [];
|
|
2400
|
+
this.pendingBytes = rest.length;
|
|
2401
|
+
this.onSample(sample);
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
|
|
2405
|
+
private onSample(raw: Buffer): void {
|
|
2406
|
+
const n = this.schedule[this.frame] ?? 1;
|
|
2407
|
+
if (n === 1) {
|
|
2408
|
+
this.emit(Buffer.from(raw));
|
|
2409
|
+
return;
|
|
2410
|
+
}
|
|
2411
|
+
if (!this.acc) this.acc = new Float32Array(raw.length);
|
|
2412
|
+
const acc = this.acc;
|
|
2413
|
+
for (let k = 0; k < raw.length; k++) acc[k]! += TO_LINEAR[raw[k]!]!;
|
|
2414
|
+
if (++this.got < n) return;
|
|
2415
|
+
const out = Buffer.allocUnsafe(raw.length);
|
|
2416
|
+
const scale = LUT / n;
|
|
2417
|
+
let s = this.rng;
|
|
2418
|
+
for (let k = 0; k < out.length; k++) {
|
|
2419
|
+
const v = acc[k]! * scale;
|
|
2420
|
+
const i = v | 0;
|
|
2421
|
+
const srgb = TO_SRGB[i]! + (TO_SRGB[i + 1]! - TO_SRGB[i]!) * (v - i);
|
|
2422
|
+
// triangular dither, ±0.5 LSB (xorshift32)
|
|
2423
|
+
s ^= s << 13;
|
|
2424
|
+
s ^= s >>> 17;
|
|
2425
|
+
s ^= s << 5;
|
|
2426
|
+
const r1 = (s >>> 0) / 4294967296;
|
|
2427
|
+
s ^= s << 13;
|
|
2428
|
+
s ^= s >>> 17;
|
|
2429
|
+
s ^= s << 5;
|
|
2430
|
+
const d = srgb + ((s >>> 0) / 4294967296 - r1) * 0.5;
|
|
2431
|
+
out[k] = d <= 0 ? 0 : d >= 255 ? 255 : Math.round(d);
|
|
2432
|
+
}
|
|
2433
|
+
this.rng = s;
|
|
2434
|
+
acc.fill(0);
|
|
2435
|
+
this.got = 0;
|
|
2436
|
+
this.emit(out);
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
private emit(frame: Buffer): void {
|
|
2440
|
+
this.frame++;
|
|
2441
|
+
const stdin = this.encoder.stdin!;
|
|
2442
|
+
if (!stdin.write(frame)) {
|
|
2443
|
+
this.decoder.stdout?.pause();
|
|
2444
|
+
stdin.once("drain", () => this.decoder.stdout?.resume());
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
}
|