nodejs-audio-visualizer 5.1.0 → 5.3.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.
Files changed (51) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +81 -80
  3. package/dist/audio.d.ts +13 -13
  4. package/dist/audio.js +128 -128
  5. package/dist/beats.d.ts +39 -39
  6. package/dist/beats.js +220 -220
  7. package/dist/bpmEncoder.d.ts +14 -14
  8. package/dist/bpmEncoder.js +97 -97
  9. package/dist/config.d.ts +78 -77
  10. package/dist/config.js +377 -369
  11. package/dist/config.js.map +1 -1
  12. package/dist/dsp.d.ts +16 -16
  13. package/dist/dsp.js +76 -76
  14. package/dist/highlight.d.ts +66 -34
  15. package/dist/highlight.js +471 -334
  16. package/dist/highlight.js.map +1 -1
  17. package/dist/image.d.ts +97 -92
  18. package/dist/image.js +545 -538
  19. package/dist/image.js.map +1 -1
  20. package/dist/index.d.ts +87 -79
  21. package/dist/index.js +598 -566
  22. package/dist/index.js.map +1 -1
  23. package/dist/subtitleConvert.d.ts +3 -3
  24. package/dist/subtitleConvert.js +61 -61
  25. package/dist/video.d.ts +150 -120
  26. package/dist/video.js +677 -582
  27. package/dist/video.js.map +1 -1
  28. package/dist/waitForEventLoop.d.ts +1 -1
  29. package/dist/waitForEventLoop.js +5 -5
  30. package/package.json +62 -62
  31. package/src/audio.ts +129 -129
  32. package/src/beats.ts +279 -279
  33. package/src/bpmEncoder.ts +97 -97
  34. package/src/config.ts +487 -476
  35. package/src/dsp.ts +95 -95
  36. package/src/highlight.ts +451 -291
  37. package/src/image.ts +707 -700
  38. package/src/index.ts +813 -769
  39. package/src/subtitleConvert.ts +63 -63
  40. package/src/tests/audio.test.ts +102 -102
  41. package/src/tests/beats.test.ts +134 -134
  42. package/src/tests/config.test.ts +534 -496
  43. package/src/tests/dsp.test.ts +24 -24
  44. package/src/tests/highlight.test.ts +261 -178
  45. package/src/tests/image.test.ts +319 -308
  46. package/src/tests/index.test.ts +180 -180
  47. package/src/tests/subtitleConvert.test.ts +23 -23
  48. package/src/tests/video.test.ts +535 -447
  49. package/src/typings.d.ts +28 -28
  50. package/src/video.ts +856 -722
  51. package/src/waitForEventLoop.ts +2 -2
package/src/index.ts CHANGED
@@ -1,769 +1,813 @@
1
- import path from 'path';
2
- import { readFileSync } from 'fs';
3
- import {
4
- getAudioFilePath,
5
- getBackgroundImagePath,
6
- getBackgroundVideoPath,
7
- getOutVideoPath,
8
- getSubtitleRenderSpec,
9
- subtitleAlignmentToAss,
10
- getFPS,
11
- getSpectrumBusMargin,
12
- getSpectrumWidthAbsolute,
13
- getSpectrumHeightAbsolute,
14
- getSpectrumXAbsolute,
15
- getSpectrumYAbsolute,
16
- getSpectrumColor,
17
- getSpectrumOpacityParsed,
18
- getFfmpeg_cfr,
19
- getFfmpeg_preset,
20
- getFrame_processing_delay,
21
- getVideoTimeouts,
22
- getOutputResolution,
23
- rotationAliasValues,
24
- getSpectrumRotation,
25
- getSpectrumEffect,
26
- SpectrumEffect,
27
- getPolarXAbsolute,
28
- getPolarYAbsolute,
29
- getPolarInnerRadius,
30
- getPolarMaxBarLength,
31
- getPolarBarWidth,
32
- getPolarEffect,
33
- getPolarColor,
34
- getPolarOpacityParsed,
35
- getAutoEditVideo,
36
- getAudioAutoHighlight,
37
- getAudioAutoHighlightCount,
38
- } from './config';
39
- import { createAudioBuffer, bufferToUInt8, createSpectrumsProcessor, pcmU8ToFloatSamples } from './audio';
40
- import { parseImage, getImageColor, getVideoFrameColor, invertColor, Color, convertToBmp, createSpectrumVisualizerFrameGenerator, createPolarVisualizerFrameGenerator, CreatePolarVisualizerFrameProps, CreateVisualizerFrameProps, CommonVisualizerFrameProps, applyCameraShake, getCutShakeOffset, buildCutShakeAmplitudes, CAMERA_SHAKE_EVERY_BEATS } from './image';
41
- import { normalizeInlineSubtitlesToSrt, lrcToSrt } from './subtitleConvert';
42
- import { spawnFfmpegVideoWriter, waitDrain, waitForProcessExit, getVideoInfo, spawnVideoFrameReader, readVideoFrame, detectSceneChanges, buildBeatSyncedSegments, getCutFrameIndices, writeConcatFile, writeSubtitlesFile, spawnConcatVideoFrameReader, cleanupConcatFile, cleanupTempFile } from './video';
43
- import { createBpmEncoder, createBgrFrameEncoder, EncodedBmp } from './bpmEncoder';
44
- import { createBeatDetector, estimateTempo, TempoEstimate, beatGridFrameIndices, tempoForWindow, MAX_TEMPO_ANALYSIS_SECONDS } from './beats';
45
- export { BeatInfo, BeatDetectorOptions, TempoEstimate, estimateTempo, beatGridFrameIndices, shiftTempoPhase, tempoForWindow } from './beats';
46
- import { computeHighlightSlice, HIGHLIGHT_DURATION_SEC } from './highlight';
47
- import { waitForEventLoop } from './waitForEventLoop';
48
- export { computeHighlightSlice, HIGHLIGHT_DURATION_SEC, BeatFrameEvent, HighlightAudioSegment, HighlightRun } from './highlight';
49
-
50
- export const PCM_FORMAT = {
51
- bit: 8,
52
- sign: 'u',
53
- parseFunction: bufferToUInt8
54
- };
55
- const FFMPEG_FORMAT = `${PCM_FORMAT.sign}${PCM_FORMAT.bit}`;
56
- const PROCESSING_BUFFER_SIZE = Math.pow(2, 12);
57
-
58
- export interface Config {
59
- audio: {
60
- path: string;
61
- autoHighlight?: boolean;
62
- /** When `autoHighlight` is true, number of non-overlapping 15s windows to stitch (default 1). */
63
- autoHighlightCount?: number;
64
- };
65
- image?: {
66
- path: string;
67
- };
68
- video?: {
69
- path: string;
70
- autoEdit?: boolean;
71
- };
72
- outVideo: {
73
- path: string;
74
- subtitles?:
75
- | string
76
- | {
77
- path?: string;
78
- rawContent?: string;
79
- alignment?: 'top' | 'middle' | 'bottom';
80
- };
81
- fps?: number;
82
- resolution?: {
83
- width: number;
84
- height: number;
85
- };
86
- spectrum?: {
87
- width?: SpectrumSizeValue;
88
- height?: SpectrumSizeValue;
89
- x?: number | PositionAliasName;
90
- y?: number | PositionAliasName;
91
- rotation?: RotationAliasName;
92
- effect?: SpectrumEffect;
93
- color?: Color | string;
94
- opacity?: string;
95
- };
96
- polar?: {
97
- x?: number | PositionAliasName;
98
- y?: number | PositionAliasName;
99
- innerRadius?: number;
100
- maxBarLength?: number;
101
- barWidth?: number;
102
- effect?: SpectrumEffect;
103
- color?: Color | string;
104
- opacity?: string;
105
- }
106
- };
107
- tweaks?: {
108
- ffmpeg_cfr?: string;
109
- ffmpeg_preset?: string;
110
- frame_processing_delay?: number;
111
- timeouts?: {
112
- readVideoFrame?: number;
113
- waitDrain?: number;
114
- waitForProcessExit?: number;
115
- };
116
- };
117
- }
118
-
119
- export type SpectrumSizeValue = number | string;
120
-
121
- export type PositionAliasName =
122
- 'left' |
123
- 'center' |
124
- 'right' |
125
- 'top' |
126
- 'middle' |
127
- 'bottom';
128
-
129
- export type RotationAliasName = typeof rotationAliasValues[number];
130
-
131
- const sleep = (timeout: number) =>
132
- new Promise(resolve => setTimeout(resolve, timeout));
133
-
134
- const createVisualizerFrameGenerator = (
135
- config: Config,
136
- backgroundWidth: number,
137
- backgroundHeight: number,
138
- defaultColor: Color,
139
- spectrumBusMargin: number
140
- ): (params: CommonVisualizerFrameProps) => EncodedBmp => {
141
- if (config.outVideo.spectrum) {
142
- const createSpectrumVisualizerFrame = createSpectrumVisualizerFrameGenerator();
143
- const spectrumWidth = getSpectrumWidthAbsolute(config, backgroundWidth);
144
- const spectrumHeight = getSpectrumHeightAbsolute(config, backgroundHeight);
145
- const spectrumX = getSpectrumXAbsolute(config, spectrumWidth, backgroundWidth);
146
- const spectrumY = getSpectrumYAbsolute(config, spectrumHeight, backgroundHeight);
147
- const spectrumRotation = getSpectrumRotation(config);
148
- const spectrumColor = getSpectrumColor(config) || invertColor(defaultColor);
149
- const spectrumEffect = getSpectrumEffect(config);
150
- const spectrumOpacity = getSpectrumOpacityParsed(config);
151
-
152
- return (params: CommonVisualizerFrameProps) => {
153
- return createSpectrumVisualizerFrame({
154
- ...params,
155
- size: { width: spectrumWidth, height: spectrumHeight },
156
- position: { x: spectrumX, y: spectrumY },
157
- rotation: spectrumRotation,
158
- margin: spectrumBusMargin,
159
- color: spectrumColor,
160
- opacity: spectrumOpacity,
161
- spectrumEffect,
162
- });
163
- };
164
- }
165
-
166
- if (config.outVideo.polar) {
167
- const createPolarVisualizerFrame = createPolarVisualizerFrameGenerator();
168
- const polarX = getPolarXAbsolute(config, backgroundWidth);
169
- const polarY = getPolarYAbsolute(config, backgroundHeight);
170
- const polarInnerRadius = getPolarInnerRadius(config);
171
- const polarMaxBarLength = getPolarMaxBarLength(config);
172
- const polarBarWidth = getPolarBarWidth(config);
173
- const polarColor = getPolarColor(config) || invertColor(defaultColor);
174
- const polarEffect = getPolarEffect(config);
175
- const polarOpacity = getPolarOpacityParsed(config);
176
-
177
- return (params: CommonVisualizerFrameProps) => {
178
- return createPolarVisualizerFrame({
179
- ...params,
180
- centerX: polarX,
181
- centerY: polarY,
182
- innerRadius: polarInnerRadius,
183
- maxBarLength: polarMaxBarLength,
184
- barWidth: polarBarWidth,
185
- color: polarColor,
186
- opacity: polarOpacity,
187
- spectrumEffect: polarEffect,
188
- });
189
- };
190
- }
191
-
192
- return (params: CommonVisualizerFrameProps) => params.backgroundImageBuffer;
193
- };
194
-
195
- interface PreProcessedAudio {
196
- spectrums: number[][];
197
- beatFrameIndices: number[];
198
- beatEvents: { frameIndex: number; intensity: number }[];
199
- }
200
-
201
- const PRE_PROCESS_PROGRESS_SHARE = 60;
202
- const POST_AUDIO_PROGRESS_SHARE = 10;
203
- const RENDER_PROGRESS_SHARE = 30;
204
-
205
- const preProcessAudio = async (
206
- audioBuffer: Buffer,
207
- sampleRate: number,
208
- fps: number,
209
- framesCount: number,
210
- onPreProcessProgress?: (totalPercent: number) => void,
211
- ): Promise<PreProcessedAudio> => {
212
- if (framesCount === 0) {
213
- for (let t = 1; t <= PRE_PROCESS_PROGRESS_SHARE; t += 1) {
214
- onPreProcessProgress?.(t);
215
- }
216
- return { spectrums: [], beatFrameIndices: [], beatEvents: [] };
217
- }
218
- const audioDataStep = Math.trunc(audioBuffer.length / framesCount);
219
- const processingBuffer = new Float32Array(PROCESSING_BUFFER_SIZE).fill(0);
220
- const skipFramesCount = fps < 45 ? 1 : 2;
221
- const processSpectrum = createSpectrumsProcessor(sampleRate, skipFramesCount);
222
- const detectBeat = createBeatDetector(fps);
223
-
224
- const spectrums: number[][] = [];
225
- const beatFrameIndices: number[] = [];
226
- const beatEvents: { frameIndex: number; intensity: number }[] = [];
227
- let nextPreProcessMilestone = 1;
228
-
229
- for (let i = 0; i < framesCount; i++) {
230
- const currentFrameData = PCM_FORMAT.parseFunction(audioBuffer, i * audioDataStep, i * audioDataStep + audioDataStep);
231
- const frameDataLength = Math.min(currentFrameData.length, PROCESSING_BUFFER_SIZE);
232
- const frameDataTailStart = currentFrameData.length - frameDataLength;
233
- const frameDataToProcess = currentFrameData.slice(frameDataTailStart);
234
-
235
- processingBuffer.copyWithin(0, frameDataLength);
236
- processingBuffer.set(frameDataToProcess, PROCESSING_BUFFER_SIZE - frameDataLength);
237
-
238
- const audioDataParser = () => Array.from(processingBuffer);
239
- const spectrum = processSpectrum(audioDataParser);
240
- const beat = detectBeat(spectrum);
241
-
242
- spectrums.push(spectrum);
243
- if (beat.isBeat) {
244
- beatFrameIndices.push(i);
245
- beatEvents.push({ frameIndex: i, intensity: beat.intensity });
246
- }
247
-
248
- const p =
249
- PRE_PROCESS_PROGRESS_SHARE * (i + 1) / framesCount;
250
- while (
251
- nextPreProcessMilestone <= PRE_PROCESS_PROGRESS_SHARE
252
- && p >= nextPreProcessMilestone
253
- ) {
254
- onPreProcessProgress?.(nextPreProcessMilestone);
255
- nextPreProcessMilestone += 1;
256
- }
257
-
258
- await waitForEventLoop();
259
- }
260
-
261
- return { spectrums, beatFrameIndices, beatEvents };
262
- };
263
-
264
- async function prepareBackgroundForRender(params: {
265
- useVideoBackground: boolean;
266
- backgroundVideoPath: string | undefined;
267
- backgroundImagePath: string | undefined;
268
- beatFrameIndices: number[];
269
- beatIntensities?: number[];
270
- framesCount: number;
271
- outputResolution: ReturnType<typeof getOutputResolution>;
272
- fps: number;
273
- autoEditVideo: boolean;
274
- readVideoFrameTimeout: number;
275
- tempo?: TempoEstimate | null;
276
- }): Promise<{
277
- backgroundWidth: number;
278
- backgroundHeight: number;
279
- defaultColor: Color;
280
- staticBackgroundBuffer: EncodedBmp;
281
- videoFrameReader?: ReturnType<typeof spawnVideoFrameReader>;
282
- videoFrameSize: number;
283
- encodeVideoFrame?: (bgrBuffer: Buffer) => EncodedBmp;
284
- concatFilePath?: string;
285
- cutFrameIndices: number[];
286
- }> {
287
- const {
288
- useVideoBackground,
289
- backgroundVideoPath,
290
- backgroundImagePath,
291
- beatFrameIndices,
292
- beatIntensities,
293
- framesCount,
294
- outputResolution,
295
- fps,
296
- autoEditVideo,
297
- readVideoFrameTimeout,
298
- tempo,
299
- } = params;
300
-
301
- if (useVideoBackground && backgroundVideoPath) {
302
- const videoInfo = await getVideoInfo(backgroundVideoPath);
303
- const sceneChanges = autoEditVideo
304
- ? await detectSceneChanges(backgroundVideoPath)
305
- : [];
306
- const backgroundWidth = outputResolution?.width ?? videoInfo.width;
307
- const backgroundHeight = outputResolution?.height ?? videoInfo.height;
308
-
309
- const videoFrameSize = backgroundWidth * backgroundHeight * 3;
310
- const encodeVideoFrame = createBgrFrameEncoder({ width: backgroundWidth, height: backgroundHeight });
311
-
312
- const segments = buildBeatSyncedSegments(
313
- beatFrameIndices,
314
- framesCount,
315
- sceneChanges,
316
- videoInfo.duration,
317
- fps,
318
- {
319
- beatIntensities,
320
- ...(autoEditVideo && tempo ? { tempo } : {}),
321
- },
322
- );
323
-
324
- const concatFilePath = writeConcatFile(segments, backgroundVideoPath, videoInfo.duration, fps);
325
- const cutFrameIndices = autoEditVideo ? getCutFrameIndices(segments) : [];
326
-
327
- const videoFrameReader = spawnConcatVideoFrameReader({
328
- concatFilePath,
329
- fps,
330
- totalFrames: framesCount,
331
- ...(outputResolution && {
332
- width: backgroundWidth,
333
- height: backgroundHeight,
334
- sourceWidth: videoInfo.width,
335
- sourceHeight: videoInfo.height,
336
- }),
337
- });
338
-
339
- const firstFrame = await readVideoFrame(
340
- videoFrameReader.stdout,
341
- videoFrameSize,
342
- readVideoFrameTimeout,
343
- );
344
- if (!firstFrame) {
345
- throw new Error(`Could not read frames from video: ${backgroundVideoPath}`);
346
- }
347
- const defaultColor = getVideoFrameColor(firstFrame, backgroundWidth, backgroundHeight);
348
- const staticBackgroundBuffer = encodeVideoFrame(firstFrame);
349
- return {
350
- backgroundWidth,
351
- backgroundHeight,
352
- defaultColor,
353
- staticBackgroundBuffer,
354
- videoFrameReader,
355
- videoFrameSize,
356
- encodeVideoFrame,
357
- concatFilePath,
358
- cutFrameIndices,
359
- };
360
- }
361
-
362
- if (!backgroundImagePath) {
363
- throw new Error('Background image path is required when not using video background.');
364
- }
365
- const backgroundImageBmpBuffer = await convertToBmp(
366
- backgroundImagePath,
367
- outputResolution?.width,
368
- outputResolution?.height,
369
- );
370
- const backgroundImage = parseImage(backgroundImageBmpBuffer);
371
- const backgroundWidth = backgroundImage.width;
372
- const backgroundHeight = backgroundImage.height;
373
- const defaultColor = getImageColor(backgroundImage);
374
-
375
- const bpmEncoder = createBpmEncoder({ width: backgroundWidth, height: backgroundHeight });
376
- const staticBackgroundBuffer = bpmEncoder(backgroundImage.data);
377
- return {
378
- backgroundWidth,
379
- backgroundHeight,
380
- defaultColor,
381
- staticBackgroundBuffer,
382
- videoFrameSize: 0,
383
- cutFrameIndices: [],
384
- };
385
- }
386
-
387
- async function resolveBackgroundFrameBuffer(params: {
388
- frameIndex: number;
389
- useVideoBackground: boolean;
390
- videoFrameReader?: ReturnType<typeof spawnVideoFrameReader>;
391
- videoFrameSize: number;
392
- encodeVideoFrame?: (bgrBuffer: Buffer) => EncodedBmp;
393
- staticBackgroundBuffer: EncodedBmp;
394
- readVideoFrameTimeout: number;
395
- }): Promise<{ frameBuffer: EncodedBmp; frameReadFailed: boolean }> {
396
- const {
397
- frameIndex,
398
- useVideoBackground,
399
- videoFrameReader,
400
- videoFrameSize,
401
- encodeVideoFrame,
402
- staticBackgroundBuffer,
403
- readVideoFrameTimeout,
404
- } = params;
405
-
406
- if (useVideoBackground && videoFrameReader && encodeVideoFrame) {
407
- if (frameIndex === 0) {
408
- return { frameBuffer: staticBackgroundBuffer, frameReadFailed: false };
409
- }
410
- const videoFrame = await readVideoFrame(
411
- videoFrameReader.stdout,
412
- videoFrameSize,
413
- readVideoFrameTimeout,
414
- );
415
- if (videoFrame) {
416
- return { frameBuffer: encodeVideoFrame(videoFrame), frameReadFailed: false };
417
- }
418
- return { frameBuffer: staticBackgroundBuffer, frameReadFailed: false };
419
- }
420
- return { frameBuffer: staticBackgroundBuffer, frameReadFailed: false };
421
- }
422
-
423
- export interface RenderAudioVisualizerResult {
424
- exitCode: number;
425
- /** Human-readable failure reason; omitted on full success (exitCode 0). */
426
- reason?: string;
427
- /** Absolute paths of video files written successfully (exit code 0, full pass, no early stop). */
428
- outputVideoFiles: string[];
429
- }
430
-
431
- export const renderAudioVisualizer = (config: Config, onProgress?: (progress: number) => any, shouldStop?: () => boolean) =>
432
- new Promise<RenderAudioVisualizerResult>(async (resolve) => {
433
- if (config.outVideo.spectrum && config.outVideo.polar) {
434
- throw new Error('Cannot use both "spectrum" and "polar" options. Please specify only one visualizer type.');
435
- }
436
- if (!config.image && !config.video) {
437
- throw new Error('Either "image" or "video" must be specified as the background source.');
438
- }
439
- if (config.image && config.video) {
440
- throw new Error('Cannot use both "image" and "video" options. Please specify only one background source.');
441
- }
442
-
443
- const audioFilePath = getAudioFilePath(config);
444
- const outVideoPath = getOutVideoPath(config);
445
- const subtitleSpec = getSubtitleRenderSpec(config);
446
- let subtitleFilePath: string | undefined;
447
- let subtitleFileIsTemporary = false;
448
- let subtitleAlignmentAss = 2;
449
- if (subtitleSpec) {
450
- subtitleAlignmentAss = subtitleAlignmentToAss(subtitleSpec.alignment);
451
- if (subtitleSpec.source.kind === 'file') {
452
- const absPath = subtitleSpec.source.path;
453
- const ext = path.extname(absPath).toLowerCase();
454
- if (ext === '.lrc') {
455
- const raw = readFileSync(absPath, 'utf-8');
456
- subtitleFilePath = writeSubtitlesFile(lrcToSrt(raw));
457
- subtitleFileIsTemporary = true;
458
- } else {
459
- subtitleFilePath = absPath;
460
- }
461
- } else {
462
- subtitleFilePath = writeSubtitlesFile(
463
- normalizeInlineSubtitlesToSrt(subtitleSpec.source.text),
464
- );
465
- subtitleFileIsTemporary = true;
466
- }
467
- }
468
- const backgroundVideoPath = getBackgroundVideoPath(config);
469
- const backgroundImagePath = getBackgroundImagePath(config);
470
- const useVideoBackground = !!backgroundVideoPath;
471
-
472
- const audioReader = await createAudioBuffer(audioFilePath, FFMPEG_FORMAT);
473
- const audioBuffer = audioReader.audioBuffer;
474
- const sampleRate = audioReader.sampleRate;
475
- if (!sampleRate) {
476
- throw new Error('ffmpeg didn\'t show audio sample rate');
477
- }
478
-
479
- const spectrumBusMargin = getSpectrumBusMargin();
480
- const FPS = getFPS(config);
481
- const ffmpeg_cfr = getFfmpeg_cfr(config);
482
- const ffmpeg_preset = getFfmpeg_preset(config);
483
- const frame_processing_delay = getFrame_processing_delay(config);
484
- const videoTimeouts = getVideoTimeouts(config);
485
-
486
- const audioDuration = audioBuffer.length / sampleRate;
487
- const framesCount = Math.trunc(audioDuration * FPS);
488
- const outputResolution = getOutputResolution(config);
489
-
490
- let maxProgressReported = -1;
491
- const reportProgress = (progress: number) => {
492
- if (!onProgress) {
493
- return;
494
- }
495
- const normalized = +Math.min(100, Math.max(0, progress)).toFixed(2);
496
- if (normalized <= maxProgressReported) {
497
- return;
498
- }
499
- maxProgressReported = normalized;
500
- onProgress(normalized);
501
- };
502
- reportProgress(0);
503
-
504
- const preprocessed = await preProcessAudio(
505
- audioBuffer,
506
- sampleRate,
507
- FPS,
508
- framesCount,
509
- (progress: number) => {
510
- reportProgress(progress);
511
- },
512
- );
513
- reportProgress(PRE_PROCESS_PROGRESS_SHARE);
514
-
515
- const autoHighlight = getAudioAutoHighlight(config);
516
- let spectrumsForRender = preprocessed.spectrums;
517
- let beatIndicesForRender = preprocessed.beatFrameIndices;
518
- let beatIntensitiesForRender = preprocessed.beatEvents.map(event => event.intensity);
519
- let framesCountForRender = framesCount;
520
- type HighlightSliceResult = ReturnType<typeof computeHighlightSlice> extends Promise<
521
- infer R
522
- >
523
- ? R
524
- : never;
525
- let highlightSlice: HighlightSliceResult | undefined;
526
-
527
- if (autoHighlight) {
528
- reportProgress(PRE_PROCESS_PROGRESS_SHARE + 1);
529
- highlightSlice = await computeHighlightSlice(
530
- FPS,
531
- framesCount,
532
- preprocessed.spectrums,
533
- preprocessed.beatEvents,
534
- getAudioAutoHighlightCount(config),
535
- );
536
- spectrumsForRender = highlightSlice.spectrums;
537
- beatIndicesForRender = highlightSlice.beatFrameIndices;
538
- beatIntensitiesForRender = highlightSlice.beatIntensities;
539
- framesCountForRender = highlightSlice.highlightFrames;
540
- reportProgress(PRE_PROCESS_PROGRESS_SHARE + POST_AUDIO_PROGRESS_SHARE);
541
- } else {
542
- reportProgress(PRE_PROCESS_PROGRESS_SHARE + POST_AUDIO_PROGRESS_SHARE);
543
- }
544
-
545
- const autoEditVideo = getAutoEditVideo(config);
546
- let trackTempo: TempoEstimate | null = null;
547
- if (autoEditVideo) {
548
- const sampleRateNum = Number(sampleRate);
549
- const maxSamples = Math.floor(sampleRateNum * MAX_TEMPO_ANALYSIS_SECONDS);
550
- const tempoBuffer = audioBuffer.length > maxSamples
551
- ? audioBuffer.slice(0, maxSamples)
552
- : audioBuffer;
553
- trackTempo = estimateTempo(pcmU8ToFloatSamples(tempoBuffer), sampleRateNum, FPS);
554
- }
555
-
556
- const separateHighlightFiles =
557
- autoHighlight &&
558
- highlightSlice &&
559
- highlightSlice.runs.length > 1;
560
-
561
- type VideoRenderPass = {
562
- outPath: string;
563
- spectrums: number[][];
564
- beatIndices: number[];
565
- beatIntensities: number[];
566
- frameCount: number;
567
- startFrame: number;
568
- audioSegment: import('./highlight').HighlightAudioSegment | undefined;
569
- };
570
-
571
- const passes: VideoRenderPass[] =
572
- separateHighlightFiles && highlightSlice
573
- ? highlightSlice.runs.map((run, i) => {
574
- const dir = path.dirname(outVideoPath);
575
- const ext = path.extname(outVideoPath);
576
- const base = path.basename(outVideoPath, ext);
577
- const numberedPath = path.resolve(dir, `${base}-${i + 1}${ext}`);
578
- return {
579
- outPath: numberedPath,
580
- spectrums: run.spectrums,
581
- beatIndices: run.beatFrameIndices,
582
- beatIntensities: run.beatIntensities,
583
- frameCount: run.highlightFrames,
584
- startFrame: run.startFrame,
585
- audioSegment: run.audioSegment,
586
- };
587
- })
588
- : [
589
- {
590
- outPath: outVideoPath,
591
- spectrums: spectrumsForRender,
592
- beatIndices: beatIndicesForRender,
593
- beatIntensities: beatIntensitiesForRender,
594
- frameCount: framesCountForRender,
595
- startFrame: highlightSlice?.startFrame ?? 0,
596
- audioSegment:
597
- autoHighlight &&
598
- highlightSlice &&
599
- highlightSlice.audioSegments.length > 0
600
- ? highlightSlice.audioSegments[0]
601
- : undefined,
602
- },
603
- ];
604
-
605
- const totalPassFrames =
606
- passes.reduce((sum, pass) => sum + pass.frameCount, 0);
607
- const totalRenderMilestones = totalPassFrames + (passes.length * 2);
608
- let renderMilestonesCompleted = 0;
609
- const reportRenderProgress = (milestoneIncrement = 1) => {
610
- renderMilestonesCompleted += milestoneIncrement;
611
- reportProgress(
612
- PRE_PROCESS_PROGRESS_SHARE
613
- + POST_AUDIO_PROGRESS_SHARE
614
- + (RENDER_PROGRESS_SHARE * renderMilestonesCompleted / Math.max(1, totalRenderMilestones)),
615
- );
616
- };
617
- let lastExitCode = 0;
618
- let exitReason: string | undefined;
619
- const outputVideoFiles: string[] = [];
620
- try {
621
- passLoop: for (const pass of passes) {
622
- const tempo = trackTempo
623
- ? tempoForWindow(trackTempo, pass.startFrame, FPS, pass.frameCount, pass.beatIndices)
624
- : null;
625
- const shakeAmplitudes = tempo
626
- ? buildCutShakeAmplitudes(tempo.periodFrames)
627
- : undefined;
628
- const {
629
- backgroundWidth,
630
- backgroundHeight,
631
- defaultColor,
632
- staticBackgroundBuffer,
633
- videoFrameReader,
634
- videoFrameSize,
635
- encodeVideoFrame,
636
- concatFilePath,
637
- } = await prepareBackgroundForRender({
638
- useVideoBackground,
639
- backgroundVideoPath,
640
- backgroundImagePath,
641
- beatFrameIndices: pass.beatIndices,
642
- beatIntensities: pass.beatIntensities,
643
- framesCount: pass.frameCount,
644
- outputResolution,
645
- fps: FPS,
646
- autoEditVideo,
647
- readVideoFrameTimeout: videoTimeouts.readVideoFrame,
648
- ...(tempo ? { tempo } : {}),
649
- });
650
- reportRenderProgress();
651
-
652
- const shakeFrames = new Set(
653
- autoEditVideo
654
- ? (tempo
655
- ? beatGridFrameIndices(tempo, pass.frameCount, CAMERA_SHAKE_EVERY_BEATS)
656
- : pass.beatIndices.filter(frameIndex => frameIndex > 0).filter((_, i) => i % CAMERA_SHAKE_EVERY_BEATS === 0))
657
- : [],
658
- );
659
- const createVisualizerFrame = createVisualizerFrameGenerator(
660
- config, backgroundWidth, backgroundHeight, defaultColor, spectrumBusMargin
661
- );
662
-
663
- const ffmpegVideoWriter = spawnFfmpegVideoWriter({
664
- audioFilename: audioFilePath,
665
- videoFileName: pass.outPath,
666
- ...(subtitleFilePath && {
667
- subtitleFilename: subtitleFilePath,
668
- subtitleAlignmentAss,
669
- }),
670
- fps: FPS,
671
- ...(pass.audioSegment && { audioSegment: pass.audioSegment }),
672
- ...(ffmpeg_cfr && { crf: ffmpeg_cfr }),
673
- ...(ffmpeg_preset && { preset: ffmpeg_preset }),
674
- });
675
- const exitPromise = waitForProcessExit(
676
- ffmpegVideoWriter,
677
- videoTimeouts.waitForProcessExit,
678
- );
679
-
680
- let stoppedEarly = false;
681
- for (let i = 0; i < pass.frameCount; i++) {
682
- const spectrum = pass.spectrums[i];
683
- const { frameBuffer: backgroundImageBuffer, frameReadFailed } = await resolveBackgroundFrameBuffer({
684
- frameIndex: i,
685
- useVideoBackground,
686
- videoFrameReader,
687
- videoFrameSize,
688
- encodeVideoFrame,
689
- staticBackgroundBuffer,
690
- readVideoFrameTimeout: videoTimeouts.readVideoFrame,
691
- });
692
-
693
- const commonVisualizerFrameProps: CommonVisualizerFrameProps = {
694
- backgroundImageBuffer,
695
- spectrum,
696
- };
697
- const frameImage = createVisualizerFrame(commonVisualizerFrameProps);
698
- const shakeOffset = getCutShakeOffset(i, shakeFrames, shakeAmplitudes);
699
- if (shakeOffset.x !== 0 || shakeOffset.y !== 0) {
700
- applyCameraShake(frameImage, backgroundWidth, backgroundHeight, shakeOffset.x, shakeOffset.y);
701
- }
702
- const isFrameProcessed = ffmpegVideoWriter.stdin.write(frameImage.data);
703
- if (!isFrameProcessed) {
704
- const isDrained = await waitDrain(
705
- ffmpegVideoWriter.stdin,
706
- ffmpegVideoWriter,
707
- videoTimeouts.waitDrain,
708
- );
709
- if (!isDrained) {
710
- stoppedEarly = true;
711
- exitReason = 'ffmpeg stdin drain failed';
712
- break;
713
- }
714
- }
715
- if (shouldStop && shouldStop()) {
716
- stoppedEarly = true;
717
- exitReason = 'render stopped by shouldStop callback';
718
- break;
719
- }
720
- if (frame_processing_delay) {
721
- await sleep(frame_processing_delay);
722
- }
723
- await waitForEventLoop();
724
- reportRenderProgress();
725
- }
726
-
727
- if (videoFrameReader) {
728
- videoFrameReader.kill();
729
- }
730
- if (concatFilePath) {
731
- cleanupConcatFile(concatFilePath);
732
- }
733
- ffmpegVideoWriter.stdin.end();
734
-
735
- const { exitCode, reason: ffmpegExitReason } = await exitPromise;
736
- lastExitCode = exitCode;
737
- if (!exitReason && ffmpegExitReason) {
738
- exitReason = ffmpegExitReason;
739
- }
740
- if (lastExitCode === 0 && !stoppedEarly) {
741
- reportRenderProgress();
742
- }
743
-
744
- if (lastExitCode === 0 && !stoppedEarly) {
745
- outputVideoFiles.push(pass.outPath);
746
- }
747
-
748
- if (stoppedEarly || lastExitCode !== 0) {
749
- if (exitReason && lastExitCode === 0) {
750
- lastExitCode = 1;
751
- }
752
- break passLoop;
753
- }
754
- }
755
-
756
- if (lastExitCode === 0 && outputVideoFiles.length === passes.length) {
757
- reportProgress(100);
758
- }
759
- if (exitReason) {
760
- console.error(exitReason);
761
- }
762
-
763
- resolve({ exitCode: lastExitCode, reason: exitReason, outputVideoFiles });
764
- } finally {
765
- if (subtitleFilePath && subtitleFileIsTemporary) {
766
- cleanupTempFile(subtitleFilePath);
767
- }
768
- }
769
- });
1
+ import path from 'path';
2
+ import { readFileSync } from 'fs';
3
+ import {
4
+ getAudioFilePath,
5
+ getBackgroundImagePath,
6
+ getBackgroundVideoPaths,
7
+ getOutVideoPath,
8
+ getSubtitleRenderSpec,
9
+ subtitleAlignmentToAss,
10
+ getFPS,
11
+ getSpectrumBusMargin,
12
+ getSpectrumWidthAbsolute,
13
+ getSpectrumHeightAbsolute,
14
+ getSpectrumXAbsolute,
15
+ getSpectrumYAbsolute,
16
+ getSpectrumColor,
17
+ getSpectrumOpacityParsed,
18
+ getFfmpeg_cfr,
19
+ getFfmpeg_preset,
20
+ getFrame_processing_delay,
21
+ getVideoTimeouts,
22
+ getOutputResolution,
23
+ rotationAliasValues,
24
+ getSpectrumRotation,
25
+ getSpectrumEffect,
26
+ SpectrumEffect,
27
+ getPolarXAbsolute,
28
+ getPolarYAbsolute,
29
+ getPolarInnerRadius,
30
+ getPolarMaxBarLength,
31
+ getPolarBarWidth,
32
+ getPolarEffect,
33
+ getPolarColor,
34
+ getPolarOpacityParsed,
35
+ getAutoEditVideo,
36
+ getCameraShakeEnabled,
37
+ getAudioAutoHighlight,
38
+ getAudioAutoHighlightCount,
39
+ } from './config';
40
+ import { createAudioBuffer, bufferToUInt8, createSpectrumsProcessor, pcmU8ToFloatSamples } from './audio';
41
+ import { parseImage, getImageColor, getVideoFrameColor, invertColor, Color, convertToBmp, createSpectrumVisualizerFrameGenerator, createPolarVisualizerFrameGenerator, CreatePolarVisualizerFrameProps, CreateVisualizerFrameProps, CommonVisualizerFrameProps, applyCameraShake, getCutShakeOffset, buildCutShakeAmplitudes, CAMERA_SHAKE_DELAY_SECONDS, CAMERA_SHAKE_EVERY_BEATS } from './image';
42
+ import { normalizeInlineSubtitlesToSrt, lrcToSrt } from './subtitleConvert';
43
+ import { spawnFfmpegVideoWriter, waitDrain, waitForProcessExit, getVideoInfo, spawnVideoFrameReader, readVideoFrame, detectSceneChanges, buildBeatSyncedSegments, buildSequentialVideoSegments, buildShuffledVideoSegments, getCutFrameIndices, writeConcatFile, writeSubtitlesFile, spawnConcatVideoFrameReader, cleanupConcatFile, cleanupTempFile, VideoSegment } from './video';
44
+ import { createBpmEncoder, createBgrFrameEncoder, EncodedBmp } from './bpmEncoder';
45
+ import { createBeatDetector, estimateTempo, TempoEstimate, beatGridFrameIndices, tempoForWindow, MAX_TEMPO_ANALYSIS_SECONDS } from './beats';
46
+ export { BeatInfo, BeatDetectorOptions, TempoEstimate, estimateTempo, beatGridFrameIndices, shiftTempoPhase, tempoForWindow } from './beats';
47
+ import { computeHighlightSlice, HIGHLIGHT_DURATION_SEC } from './highlight';
48
+ import { waitForEventLoop } from './waitForEventLoop';
49
+ export { computeHighlightSlice, HIGHLIGHT_DURATION_SEC, MAX_BEAT_SNAP_SEC, BeatFrameEvent, HighlightAudioSegment, HighlightRun, HighlightBeatGrid } from './highlight';
50
+
51
+ export const PCM_FORMAT = {
52
+ bit: 8,
53
+ sign: 'u',
54
+ parseFunction: bufferToUInt8
55
+ };
56
+ const FFMPEG_FORMAT = `${PCM_FORMAT.sign}${PCM_FORMAT.bit}`;
57
+ const PROCESSING_BUFFER_SIZE = Math.pow(2, 12);
58
+
59
+ export interface Config {
60
+ audio: {
61
+ path: string;
62
+ autoHighlight?: boolean;
63
+ /** When `autoHighlight` is true, number of non-overlapping ~15s beat-aligned windows to stitch (default 1). */
64
+ autoHighlightCount?: number;
65
+ };
66
+ image?: {
67
+ path: string;
68
+ };
69
+ video?: {
70
+ /**
71
+ * A single video path, or an array of video paths.
72
+ * With an array: when `autoEdit` is false, the videos play one after another (looping the
73
+ * sequence as needed); when `autoEdit` is true, cuts switch (shuffle) between the given
74
+ * videos instead of auto-detecting scene changes within a single video.
75
+ */
76
+ path: string | string[];
77
+ autoEdit?: boolean;
78
+ /** When `autoEdit` is true, disables the brief camera shake applied on cuts, or every 2 beats when there are no cuts (default true). */
79
+ cameraShake?: boolean;
80
+ };
81
+ outVideo: {
82
+ path: string;
83
+ subtitles?:
84
+ | string
85
+ | {
86
+ path?: string;
87
+ rawContent?: string;
88
+ alignment?: 'top' | 'middle' | 'bottom';
89
+ };
90
+ fps?: number;
91
+ resolution?: {
92
+ width: number;
93
+ height: number;
94
+ };
95
+ spectrum?: {
96
+ width?: SpectrumSizeValue;
97
+ height?: SpectrumSizeValue;
98
+ x?: number | PositionAliasName;
99
+ y?: number | PositionAliasName;
100
+ rotation?: RotationAliasName;
101
+ effect?: SpectrumEffect;
102
+ color?: Color | string;
103
+ opacity?: string;
104
+ };
105
+ polar?: {
106
+ x?: number | PositionAliasName;
107
+ y?: number | PositionAliasName;
108
+ innerRadius?: number;
109
+ maxBarLength?: number;
110
+ barWidth?: number;
111
+ effect?: SpectrumEffect;
112
+ color?: Color | string;
113
+ opacity?: string;
114
+ }
115
+ };
116
+ tweaks?: {
117
+ ffmpeg_cfr?: string;
118
+ ffmpeg_preset?: string;
119
+ frame_processing_delay?: number;
120
+ timeouts?: {
121
+ readVideoFrame?: number;
122
+ waitDrain?: number;
123
+ waitForProcessExit?: number;
124
+ };
125
+ };
126
+ }
127
+
128
+ export type SpectrumSizeValue = number | string;
129
+
130
+ export type PositionAliasName =
131
+ 'left' |
132
+ 'center' |
133
+ 'right' |
134
+ 'top' |
135
+ 'middle' |
136
+ 'bottom';
137
+
138
+ export type RotationAliasName = typeof rotationAliasValues[number];
139
+
140
+ const sleep = (timeout: number) =>
141
+ new Promise(resolve => setTimeout(resolve, timeout));
142
+
143
+ const createVisualizerFrameGenerator = (
144
+ config: Config,
145
+ backgroundWidth: number,
146
+ backgroundHeight: number,
147
+ defaultColor: Color,
148
+ spectrumBusMargin: number
149
+ ): (params: CommonVisualizerFrameProps) => EncodedBmp => {
150
+ if (config.outVideo.spectrum) {
151
+ const createSpectrumVisualizerFrame = createSpectrumVisualizerFrameGenerator();
152
+ const spectrumWidth = getSpectrumWidthAbsolute(config, backgroundWidth);
153
+ const spectrumHeight = getSpectrumHeightAbsolute(config, backgroundHeight);
154
+ const spectrumX = getSpectrumXAbsolute(config, spectrumWidth, backgroundWidth);
155
+ const spectrumY = getSpectrumYAbsolute(config, spectrumHeight, backgroundHeight);
156
+ const spectrumRotation = getSpectrumRotation(config);
157
+ const spectrumColor = getSpectrumColor(config) || invertColor(defaultColor);
158
+ const spectrumEffect = getSpectrumEffect(config);
159
+ const spectrumOpacity = getSpectrumOpacityParsed(config);
160
+
161
+ return (params: CommonVisualizerFrameProps) => {
162
+ return createSpectrumVisualizerFrame({
163
+ ...params,
164
+ size: { width: spectrumWidth, height: spectrumHeight },
165
+ position: { x: spectrumX, y: spectrumY },
166
+ rotation: spectrumRotation,
167
+ margin: spectrumBusMargin,
168
+ color: spectrumColor,
169
+ opacity: spectrumOpacity,
170
+ spectrumEffect,
171
+ });
172
+ };
173
+ }
174
+
175
+ if (config.outVideo.polar) {
176
+ const createPolarVisualizerFrame = createPolarVisualizerFrameGenerator();
177
+ const polarX = getPolarXAbsolute(config, backgroundWidth);
178
+ const polarY = getPolarYAbsolute(config, backgroundHeight);
179
+ const polarInnerRadius = getPolarInnerRadius(config);
180
+ const polarMaxBarLength = getPolarMaxBarLength(config);
181
+ const polarBarWidth = getPolarBarWidth(config);
182
+ const polarColor = getPolarColor(config) || invertColor(defaultColor);
183
+ const polarEffect = getPolarEffect(config);
184
+ const polarOpacity = getPolarOpacityParsed(config);
185
+
186
+ return (params: CommonVisualizerFrameProps) => {
187
+ return createPolarVisualizerFrame({
188
+ ...params,
189
+ centerX: polarX,
190
+ centerY: polarY,
191
+ innerRadius: polarInnerRadius,
192
+ maxBarLength: polarMaxBarLength,
193
+ barWidth: polarBarWidth,
194
+ color: polarColor,
195
+ opacity: polarOpacity,
196
+ spectrumEffect: polarEffect,
197
+ });
198
+ };
199
+ }
200
+
201
+ return (params: CommonVisualizerFrameProps) => params.backgroundImageBuffer;
202
+ };
203
+
204
+ interface PreProcessedAudio {
205
+ spectrums: number[][];
206
+ beatFrameIndices: number[];
207
+ beatEvents: { frameIndex: number; intensity: number }[];
208
+ }
209
+
210
+ const PRE_PROCESS_PROGRESS_SHARE = 60;
211
+ const POST_AUDIO_PROGRESS_SHARE = 10;
212
+ const RENDER_PROGRESS_SHARE = 30;
213
+
214
+ const preProcessAudio = async (
215
+ audioBuffer: Buffer,
216
+ sampleRate: number,
217
+ fps: number,
218
+ framesCount: number,
219
+ onPreProcessProgress?: (totalPercent: number) => void,
220
+ ): Promise<PreProcessedAudio> => {
221
+ if (framesCount === 0) {
222
+ for (let t = 1; t <= PRE_PROCESS_PROGRESS_SHARE; t += 1) {
223
+ onPreProcessProgress?.(t);
224
+ }
225
+ return { spectrums: [], beatFrameIndices: [], beatEvents: [] };
226
+ }
227
+ const audioDataStep = Math.trunc(audioBuffer.length / framesCount);
228
+ const processingBuffer = new Float32Array(PROCESSING_BUFFER_SIZE).fill(0);
229
+ const skipFramesCount = fps < 45 ? 1 : 2;
230
+ const processSpectrum = createSpectrumsProcessor(sampleRate, skipFramesCount);
231
+ const detectBeat = createBeatDetector(fps);
232
+
233
+ const spectrums: number[][] = [];
234
+ const beatFrameIndices: number[] = [];
235
+ const beatEvents: { frameIndex: number; intensity: number }[] = [];
236
+ let nextPreProcessMilestone = 1;
237
+
238
+ for (let i = 0; i < framesCount; i++) {
239
+ const currentFrameData = PCM_FORMAT.parseFunction(audioBuffer, i * audioDataStep, i * audioDataStep + audioDataStep);
240
+ const frameDataLength = Math.min(currentFrameData.length, PROCESSING_BUFFER_SIZE);
241
+ const frameDataTailStart = currentFrameData.length - frameDataLength;
242
+ const frameDataToProcess = currentFrameData.slice(frameDataTailStart);
243
+
244
+ processingBuffer.copyWithin(0, frameDataLength);
245
+ processingBuffer.set(frameDataToProcess, PROCESSING_BUFFER_SIZE - frameDataLength);
246
+
247
+ const audioDataParser = () => Array.from(processingBuffer);
248
+ const spectrum = processSpectrum(audioDataParser);
249
+ const beat = detectBeat(spectrum);
250
+
251
+ spectrums.push(spectrum);
252
+ if (beat.isBeat) {
253
+ beatFrameIndices.push(i);
254
+ beatEvents.push({ frameIndex: i, intensity: beat.intensity });
255
+ }
256
+
257
+ const p =
258
+ PRE_PROCESS_PROGRESS_SHARE * (i + 1) / framesCount;
259
+ while (
260
+ nextPreProcessMilestone <= PRE_PROCESS_PROGRESS_SHARE
261
+ && p >= nextPreProcessMilestone
262
+ ) {
263
+ onPreProcessProgress?.(nextPreProcessMilestone);
264
+ nextPreProcessMilestone += 1;
265
+ }
266
+
267
+ await waitForEventLoop();
268
+ }
269
+
270
+ return { spectrums, beatFrameIndices, beatEvents };
271
+ };
272
+
273
+ async function prepareBackgroundForRender(params: {
274
+ useVideoBackground: boolean;
275
+ backgroundVideoPaths: string[] | undefined;
276
+ backgroundImagePath: string | undefined;
277
+ beatFrameIndices: number[];
278
+ beatIntensities?: number[];
279
+ framesCount: number;
280
+ outputResolution: ReturnType<typeof getOutputResolution>;
281
+ fps: number;
282
+ autoEditVideo: boolean;
283
+ readVideoFrameTimeout: number;
284
+ tempo?: TempoEstimate | null;
285
+ /** First video to play for `video.path` arrays without `autoEdit`. */
286
+ startVideoIndex?: number;
287
+ }): Promise<{
288
+ backgroundWidth: number;
289
+ backgroundHeight: number;
290
+ defaultColor: Color;
291
+ staticBackgroundBuffer: EncodedBmp;
292
+ videoFrameReader?: ReturnType<typeof spawnVideoFrameReader>;
293
+ videoFrameSize: number;
294
+ encodeVideoFrame?: (bgrBuffer: Buffer) => EncodedBmp;
295
+ concatFilePath?: string;
296
+ cutFrameIndices: number[];
297
+ }> {
298
+ const {
299
+ useVideoBackground,
300
+ backgroundVideoPaths,
301
+ backgroundImagePath,
302
+ beatFrameIndices,
303
+ beatIntensities,
304
+ framesCount,
305
+ outputResolution,
306
+ fps,
307
+ autoEditVideo,
308
+ readVideoFrameTimeout,
309
+ tempo,
310
+ startVideoIndex = 0,
311
+ } = params;
312
+
313
+ if (useVideoBackground && backgroundVideoPaths && backgroundVideoPaths.length > 0) {
314
+ const videoInfos = await Promise.all(backgroundVideoPaths.map(videoPath => getVideoInfo(videoPath)));
315
+ const primaryVideoInfo = videoInfos[0];
316
+ const backgroundWidth = outputResolution?.width ?? primaryVideoInfo.width;
317
+ const backgroundHeight = outputResolution?.height ?? primaryVideoInfo.height;
318
+
319
+ const videoFrameSize = backgroundWidth * backgroundHeight * 3;
320
+ const encodeVideoFrame = createBgrFrameEncoder({ width: backgroundWidth, height: backgroundHeight });
321
+
322
+ let segments: VideoSegment[];
323
+ if (backgroundVideoPaths.length > 1) {
324
+ segments = autoEditVideo
325
+ ? buildShuffledVideoSegments(
326
+ beatFrameIndices,
327
+ framesCount,
328
+ backgroundVideoPaths.length,
329
+ fps,
330
+ {
331
+ beatIntensities,
332
+ ...(tempo ? { tempo } : {}),
333
+ },
334
+ )
335
+ : buildSequentialVideoSegments(
336
+ framesCount,
337
+ videoInfos.map(info => info.duration),
338
+ fps,
339
+ startVideoIndex % backgroundVideoPaths.length,
340
+ );
341
+ } else {
342
+ const sceneChanges = autoEditVideo
343
+ ? await detectSceneChanges(backgroundVideoPaths[0])
344
+ : [];
345
+ segments = buildBeatSyncedSegments(
346
+ beatFrameIndices,
347
+ framesCount,
348
+ sceneChanges,
349
+ primaryVideoInfo.duration,
350
+ fps,
351
+ {
352
+ beatIntensities,
353
+ ...(autoEditVideo && tempo ? { tempo } : {}),
354
+ },
355
+ );
356
+ }
357
+
358
+ const videoSources = videoInfos.map((info, i) => ({ path: backgroundVideoPaths[i], duration: info.duration }));
359
+ const concatFilePath = writeConcatFile(segments, videoSources, fps);
360
+ const cutFrameIndices = autoEditVideo ? getCutFrameIndices(segments) : [];
361
+
362
+ const videoFrameReader = spawnConcatVideoFrameReader({
363
+ concatFilePath,
364
+ fps,
365
+ totalFrames: framesCount,
366
+ ...(outputResolution && {
367
+ width: backgroundWidth,
368
+ height: backgroundHeight,
369
+ sourceWidth: primaryVideoInfo.width,
370
+ sourceHeight: primaryVideoInfo.height,
371
+ }),
372
+ });
373
+
374
+ const firstFrame = await readVideoFrame(
375
+ videoFrameReader.stdout,
376
+ videoFrameSize,
377
+ readVideoFrameTimeout,
378
+ );
379
+ if (!firstFrame) {
380
+ throw new Error(`Could not read frames from video: ${backgroundVideoPaths.join(', ')}`);
381
+ }
382
+ const defaultColor = getVideoFrameColor(firstFrame, backgroundWidth, backgroundHeight);
383
+ const staticBackgroundBuffer = encodeVideoFrame(firstFrame);
384
+ return {
385
+ backgroundWidth,
386
+ backgroundHeight,
387
+ defaultColor,
388
+ staticBackgroundBuffer,
389
+ videoFrameReader,
390
+ videoFrameSize,
391
+ encodeVideoFrame,
392
+ concatFilePath,
393
+ cutFrameIndices,
394
+ };
395
+ }
396
+
397
+ if (!backgroundImagePath) {
398
+ throw new Error('Background image path is required when not using video background.');
399
+ }
400
+ const backgroundImageBmpBuffer = await convertToBmp(
401
+ backgroundImagePath,
402
+ outputResolution?.width,
403
+ outputResolution?.height,
404
+ );
405
+ const backgroundImage = parseImage(backgroundImageBmpBuffer);
406
+ const backgroundWidth = backgroundImage.width;
407
+ const backgroundHeight = backgroundImage.height;
408
+ const defaultColor = getImageColor(backgroundImage);
409
+
410
+ const bpmEncoder = createBpmEncoder({ width: backgroundWidth, height: backgroundHeight });
411
+ const staticBackgroundBuffer = bpmEncoder(backgroundImage.data);
412
+ return {
413
+ backgroundWidth,
414
+ backgroundHeight,
415
+ defaultColor,
416
+ staticBackgroundBuffer,
417
+ videoFrameSize: 0,
418
+ cutFrameIndices: [],
419
+ };
420
+ }
421
+
422
+ async function resolveBackgroundFrameBuffer(params: {
423
+ frameIndex: number;
424
+ useVideoBackground: boolean;
425
+ videoFrameReader?: ReturnType<typeof spawnVideoFrameReader>;
426
+ videoFrameSize: number;
427
+ encodeVideoFrame?: (bgrBuffer: Buffer) => EncodedBmp;
428
+ staticBackgroundBuffer: EncodedBmp;
429
+ readVideoFrameTimeout: number;
430
+ }): Promise<{ frameBuffer: EncodedBmp; frameReadFailed: boolean }> {
431
+ const {
432
+ frameIndex,
433
+ useVideoBackground,
434
+ videoFrameReader,
435
+ videoFrameSize,
436
+ encodeVideoFrame,
437
+ staticBackgroundBuffer,
438
+ readVideoFrameTimeout,
439
+ } = params;
440
+
441
+ if (useVideoBackground && videoFrameReader && encodeVideoFrame) {
442
+ if (frameIndex === 0) {
443
+ return { frameBuffer: staticBackgroundBuffer, frameReadFailed: false };
444
+ }
445
+ const videoFrame = await readVideoFrame(
446
+ videoFrameReader.stdout,
447
+ videoFrameSize,
448
+ readVideoFrameTimeout,
449
+ );
450
+ if (videoFrame) {
451
+ return { frameBuffer: encodeVideoFrame(videoFrame), frameReadFailed: false };
452
+ }
453
+ return { frameBuffer: staticBackgroundBuffer, frameReadFailed: false };
454
+ }
455
+ return { frameBuffer: staticBackgroundBuffer, frameReadFailed: false };
456
+ }
457
+
458
+ export interface RenderAudioVisualizerResult {
459
+ exitCode: number;
460
+ /** Human-readable failure reason; omitted on full success (exitCode 0). */
461
+ reason?: string;
462
+ /** Absolute paths of video files written successfully (exit code 0, full pass, no early stop). */
463
+ outputVideoFiles: string[];
464
+ }
465
+
466
+ export const renderAudioVisualizer = (config: Config, onProgress?: (progress: number) => any, shouldStop?: () => boolean) =>
467
+ new Promise<RenderAudioVisualizerResult>(async (resolve) => {
468
+ if (config.outVideo.spectrum && config.outVideo.polar) {
469
+ throw new Error('Cannot use both "spectrum" and "polar" options. Please specify only one visualizer type.');
470
+ }
471
+ if (!config.image && !config.video) {
472
+ throw new Error('Either "image" or "video" must be specified as the background source.');
473
+ }
474
+ if (config.image && config.video) {
475
+ throw new Error('Cannot use both "image" and "video" options. Please specify only one background source.');
476
+ }
477
+
478
+ const audioFilePath = getAudioFilePath(config);
479
+ const outVideoPath = getOutVideoPath(config);
480
+ const subtitleSpec = getSubtitleRenderSpec(config);
481
+ let subtitleFilePath: string | undefined;
482
+ let subtitleFileIsTemporary = false;
483
+ let subtitleAlignmentAss = 2;
484
+ if (subtitleSpec) {
485
+ subtitleAlignmentAss = subtitleAlignmentToAss(subtitleSpec.alignment);
486
+ if (subtitleSpec.source.kind === 'file') {
487
+ const absPath = subtitleSpec.source.path;
488
+ const ext = path.extname(absPath).toLowerCase();
489
+ if (ext === '.lrc') {
490
+ const raw = readFileSync(absPath, 'utf-8');
491
+ subtitleFilePath = writeSubtitlesFile(lrcToSrt(raw));
492
+ subtitleFileIsTemporary = true;
493
+ } else {
494
+ subtitleFilePath = absPath;
495
+ }
496
+ } else {
497
+ subtitleFilePath = writeSubtitlesFile(
498
+ normalizeInlineSubtitlesToSrt(subtitleSpec.source.text),
499
+ );
500
+ subtitleFileIsTemporary = true;
501
+ }
502
+ }
503
+ const backgroundVideoPaths = getBackgroundVideoPaths(config);
504
+ const backgroundImagePath = getBackgroundImagePath(config);
505
+ const useVideoBackground = !!backgroundVideoPaths && backgroundVideoPaths.length > 0;
506
+
507
+ const audioReader = await createAudioBuffer(audioFilePath, FFMPEG_FORMAT);
508
+ const audioBuffer = audioReader.audioBuffer;
509
+ const sampleRate = audioReader.sampleRate;
510
+ if (!sampleRate) {
511
+ throw new Error('ffmpeg didn\'t show audio sample rate');
512
+ }
513
+
514
+ const spectrumBusMargin = getSpectrumBusMargin();
515
+ const FPS = getFPS(config);
516
+ const ffmpeg_cfr = getFfmpeg_cfr(config);
517
+ const ffmpeg_preset = getFfmpeg_preset(config);
518
+ const frame_processing_delay = getFrame_processing_delay(config);
519
+ const videoTimeouts = getVideoTimeouts(config);
520
+
521
+ const audioDuration = audioBuffer.length / sampleRate;
522
+ const framesCount = Math.trunc(audioDuration * FPS);
523
+ const outputResolution = getOutputResolution(config);
524
+
525
+ let maxProgressReported = -1;
526
+ const reportProgress = (progress: number) => {
527
+ if (!onProgress) {
528
+ return;
529
+ }
530
+ const normalized = +Math.min(100, Math.max(0, progress)).toFixed(2);
531
+ if (normalized <= maxProgressReported) {
532
+ return;
533
+ }
534
+ maxProgressReported = normalized;
535
+ onProgress(normalized);
536
+ };
537
+ reportProgress(0);
538
+
539
+ const preprocessed = await preProcessAudio(
540
+ audioBuffer,
541
+ sampleRate,
542
+ FPS,
543
+ framesCount,
544
+ (progress: number) => {
545
+ reportProgress(progress);
546
+ },
547
+ );
548
+ reportProgress(PRE_PROCESS_PROGRESS_SHARE);
549
+
550
+ const autoHighlight = getAudioAutoHighlight(config);
551
+ const autoEditVideo = getAutoEditVideo(config);
552
+ // Beat grid for video cuts (autoEdit) and for snapping highlight boundaries to beats.
553
+ let trackTempo: TempoEstimate | null = null;
554
+ if (autoEditVideo || autoHighlight) {
555
+ const sampleRateNum = Number(sampleRate);
556
+ const maxSamples = Math.floor(sampleRateNum * MAX_TEMPO_ANALYSIS_SECONDS);
557
+ const tempoBuffer = audioBuffer.length > maxSamples
558
+ ? audioBuffer.slice(0, maxSamples)
559
+ : audioBuffer;
560
+ trackTempo = estimateTempo(pcmU8ToFloatSamples(tempoBuffer), sampleRateNum, FPS);
561
+ }
562
+ let spectrumsForRender = preprocessed.spectrums;
563
+ let beatIndicesForRender = preprocessed.beatFrameIndices;
564
+ let beatIntensitiesForRender = preprocessed.beatEvents.map(event => event.intensity);
565
+ let framesCountForRender = framesCount;
566
+ type HighlightSliceResult = ReturnType<typeof computeHighlightSlice> extends Promise<
567
+ infer R
568
+ >
569
+ ? R
570
+ : never;
571
+ let highlightSlice: HighlightSliceResult | undefined;
572
+
573
+ if (autoHighlight) {
574
+ reportProgress(PRE_PROCESS_PROGRESS_SHARE + 1);
575
+ highlightSlice = await computeHighlightSlice(
576
+ FPS,
577
+ framesCount,
578
+ preprocessed.spectrums,
579
+ preprocessed.beatEvents,
580
+ getAudioAutoHighlightCount(config),
581
+ trackTempo,
582
+ );
583
+ spectrumsForRender = highlightSlice.spectrums;
584
+ beatIndicesForRender = highlightSlice.beatFrameIndices;
585
+ beatIntensitiesForRender = highlightSlice.beatIntensities;
586
+ framesCountForRender = highlightSlice.highlightFrames;
587
+ reportProgress(PRE_PROCESS_PROGRESS_SHARE + POST_AUDIO_PROGRESS_SHARE);
588
+ } else {
589
+ reportProgress(PRE_PROCESS_PROGRESS_SHARE + POST_AUDIO_PROGRESS_SHARE);
590
+ }
591
+
592
+ const cameraShakeEnabled = getCameraShakeEnabled(config);
593
+ const shakeDelayFrames = Math.round(FPS * CAMERA_SHAKE_DELAY_SECONDS);
594
+
595
+ const separateHighlightFiles =
596
+ autoHighlight &&
597
+ highlightSlice &&
598
+ highlightSlice.runs.length > 1;
599
+
600
+ type VideoRenderPass = {
601
+ outPath: string;
602
+ spectrums: number[][];
603
+ beatIndices: number[];
604
+ beatIntensities: number[];
605
+ frameCount: number;
606
+ startFrame: number;
607
+ audioSegment: import('./highlight').HighlightAudioSegment | undefined;
608
+ };
609
+
610
+ const passes: VideoRenderPass[] =
611
+ separateHighlightFiles && highlightSlice
612
+ ? highlightSlice.runs.map((run, i) => {
613
+ const dir = path.dirname(outVideoPath);
614
+ const ext = path.extname(outVideoPath);
615
+ const base = path.basename(outVideoPath, ext);
616
+ const numberedPath = path.resolve(dir, `${base}-${i + 1}${ext}`);
617
+ return {
618
+ outPath: numberedPath,
619
+ spectrums: run.spectrums,
620
+ beatIndices: run.beatFrameIndices,
621
+ beatIntensities: run.beatIntensities,
622
+ frameCount: run.highlightFrames,
623
+ startFrame: run.startFrame,
624
+ audioSegment: run.audioSegment,
625
+ };
626
+ })
627
+ : [
628
+ {
629
+ outPath: outVideoPath,
630
+ spectrums: spectrumsForRender,
631
+ beatIndices: beatIndicesForRender,
632
+ beatIntensities: beatIntensitiesForRender,
633
+ frameCount: framesCountForRender,
634
+ startFrame: highlightSlice?.startFrame ?? 0,
635
+ audioSegment:
636
+ autoHighlight &&
637
+ highlightSlice &&
638
+ highlightSlice.audioSegments.length > 0
639
+ ? highlightSlice.audioSegments[0]
640
+ : undefined,
641
+ },
642
+ ];
643
+
644
+ const totalPassFrames =
645
+ passes.reduce((sum, pass) => sum + pass.frameCount, 0);
646
+ const totalRenderMilestones = totalPassFrames + (passes.length * 2);
647
+ let renderMilestonesCompleted = 0;
648
+ const reportRenderProgress = (milestoneIncrement = 1) => {
649
+ renderMilestonesCompleted += milestoneIncrement;
650
+ reportProgress(
651
+ PRE_PROCESS_PROGRESS_SHARE
652
+ + POST_AUDIO_PROGRESS_SHARE
653
+ + (RENDER_PROGRESS_SHARE * renderMilestonesCompleted / Math.max(1, totalRenderMilestones)),
654
+ );
655
+ };
656
+ let lastExitCode = 0;
657
+ let exitReason: string | undefined;
658
+ const outputVideoFiles: string[] = [];
659
+ try {
660
+ passLoop: for (let passIndex = 0; passIndex < passes.length; passIndex++) {
661
+ const pass = passes[passIndex];
662
+ const tempo = autoEditVideo && trackTempo
663
+ ? tempoForWindow(trackTempo, pass.startFrame, FPS, pass.frameCount, pass.beatIndices)
664
+ : null;
665
+ const shakeAmplitudes = tempo
666
+ ? buildCutShakeAmplitudes(tempo.periodFrames)
667
+ : undefined;
668
+ const {
669
+ backgroundWidth,
670
+ backgroundHeight,
671
+ defaultColor,
672
+ staticBackgroundBuffer,
673
+ videoFrameReader,
674
+ videoFrameSize,
675
+ encodeVideoFrame,
676
+ concatFilePath,
677
+ cutFrameIndices,
678
+ } = await prepareBackgroundForRender({
679
+ useVideoBackground,
680
+ backgroundVideoPaths,
681
+ backgroundImagePath,
682
+ beatFrameIndices: pass.beatIndices,
683
+ beatIntensities: pass.beatIntensities,
684
+ framesCount: pass.frameCount,
685
+ outputResolution,
686
+ fps: FPS,
687
+ autoEditVideo,
688
+ readVideoFrameTimeout: videoTimeouts.readVideoFrame,
689
+ ...(tempo ? { tempo } : {}),
690
+ // Each separate highlight output opens with a different video from the array.
691
+ startVideoIndex: passIndex,
692
+ });
693
+ reportRenderProgress();
694
+
695
+ const beatShakeFrames = () => (tempo
696
+ ? beatGridFrameIndices(tempo, pass.frameCount, CAMERA_SHAKE_EVERY_BEATS)
697
+ : pass.beatIndices.filter(frameIndex => frameIndex > 0).filter((_, i) => i % CAMERA_SHAKE_EVERY_BEATS === 0));
698
+ const shakeFrames = new Set(
699
+ autoEditVideo && cameraShakeEnabled
700
+ ? (cutFrameIndices.length > 0 ? cutFrameIndices : beatShakeFrames())
701
+ : [],
702
+ );
703
+ const createVisualizerFrame = createVisualizerFrameGenerator(
704
+ config, backgroundWidth, backgroundHeight, defaultColor, spectrumBusMargin
705
+ );
706
+
707
+ const ffmpegVideoWriter = spawnFfmpegVideoWriter({
708
+ audioFilename: audioFilePath,
709
+ videoFileName: pass.outPath,
710
+ ...(subtitleFilePath && {
711
+ subtitleFilename: subtitleFilePath,
712
+ subtitleAlignmentAss,
713
+ }),
714
+ fps: FPS,
715
+ ...(pass.audioSegment && { audioSegment: pass.audioSegment }),
716
+ ...(ffmpeg_cfr && { crf: ffmpeg_cfr }),
717
+ ...(ffmpeg_preset && { preset: ffmpeg_preset }),
718
+ });
719
+ const exitPromise = waitForProcessExit(
720
+ ffmpegVideoWriter,
721
+ videoTimeouts.waitForProcessExit,
722
+ );
723
+
724
+ let stoppedEarly = false;
725
+ for (let i = 0; i < pass.frameCount; i++) {
726
+ const spectrum = pass.spectrums[i];
727
+ const { frameBuffer: backgroundImageBuffer, frameReadFailed } = await resolveBackgroundFrameBuffer({
728
+ frameIndex: i,
729
+ useVideoBackground,
730
+ videoFrameReader,
731
+ videoFrameSize,
732
+ encodeVideoFrame,
733
+ staticBackgroundBuffer,
734
+ readVideoFrameTimeout: videoTimeouts.readVideoFrame,
735
+ });
736
+
737
+ const commonVisualizerFrameProps: CommonVisualizerFrameProps = {
738
+ backgroundImageBuffer,
739
+ spectrum,
740
+ };
741
+ const frameImage = createVisualizerFrame(commonVisualizerFrameProps);
742
+ const shakeOffset = getCutShakeOffset(i, shakeFrames, shakeAmplitudes, shakeDelayFrames);
743
+ if (shakeOffset.x !== 0 || shakeOffset.y !== 0) {
744
+ applyCameraShake(frameImage, backgroundWidth, backgroundHeight, shakeOffset.x, shakeOffset.y);
745
+ }
746
+ const isFrameProcessed = ffmpegVideoWriter.stdin.write(frameImage.data);
747
+ if (!isFrameProcessed) {
748
+ const isDrained = await waitDrain(
749
+ ffmpegVideoWriter.stdin,
750
+ ffmpegVideoWriter,
751
+ videoTimeouts.waitDrain,
752
+ );
753
+ if (!isDrained) {
754
+ stoppedEarly = true;
755
+ exitReason = 'ffmpeg stdin drain failed';
756
+ break;
757
+ }
758
+ }
759
+ if (shouldStop && shouldStop()) {
760
+ stoppedEarly = true;
761
+ exitReason = 'render stopped by shouldStop callback';
762
+ break;
763
+ }
764
+ if (frame_processing_delay) {
765
+ await sleep(frame_processing_delay);
766
+ }
767
+ await waitForEventLoop();
768
+ reportRenderProgress();
769
+ }
770
+
771
+ if (videoFrameReader) {
772
+ videoFrameReader.kill();
773
+ }
774
+ if (concatFilePath) {
775
+ cleanupConcatFile(concatFilePath);
776
+ }
777
+ ffmpegVideoWriter.stdin.end();
778
+
779
+ const { exitCode, reason: ffmpegExitReason } = await exitPromise;
780
+ lastExitCode = exitCode;
781
+ if (!exitReason && ffmpegExitReason) {
782
+ exitReason = ffmpegExitReason;
783
+ }
784
+ if (lastExitCode === 0 && !stoppedEarly) {
785
+ reportRenderProgress();
786
+ }
787
+
788
+ if (lastExitCode === 0 && !stoppedEarly) {
789
+ outputVideoFiles.push(pass.outPath);
790
+ }
791
+
792
+ if (stoppedEarly || lastExitCode !== 0) {
793
+ if (exitReason && lastExitCode === 0) {
794
+ lastExitCode = 1;
795
+ }
796
+ break passLoop;
797
+ }
798
+ }
799
+
800
+ if (lastExitCode === 0 && outputVideoFiles.length === passes.length) {
801
+ reportProgress(100);
802
+ }
803
+ if (exitReason) {
804
+ console.error(exitReason);
805
+ }
806
+
807
+ resolve({ exitCode: lastExitCode, reason: exitReason, outputVideoFiles });
808
+ } finally {
809
+ if (subtitleFilePath && subtitleFileIsTemporary) {
810
+ cleanupTempFile(subtitleFilePath);
811
+ }
812
+ }
813
+ });