nodejs-audio-visualizer 5.2.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.
package/src/index.ts CHANGED
@@ -1,811 +1,813 @@
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, BeatFrameEvent, HighlightAudioSegment, HighlightRun } 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 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
- let spectrumsForRender = preprocessed.spectrums;
552
- let beatIndicesForRender = preprocessed.beatFrameIndices;
553
- let beatIntensitiesForRender = preprocessed.beatEvents.map(event => event.intensity);
554
- let framesCountForRender = framesCount;
555
- type HighlightSliceResult = ReturnType<typeof computeHighlightSlice> extends Promise<
556
- infer R
557
- >
558
- ? R
559
- : never;
560
- let highlightSlice: HighlightSliceResult | undefined;
561
-
562
- if (autoHighlight) {
563
- reportProgress(PRE_PROCESS_PROGRESS_SHARE + 1);
564
- highlightSlice = await computeHighlightSlice(
565
- FPS,
566
- framesCount,
567
- preprocessed.spectrums,
568
- preprocessed.beatEvents,
569
- getAudioAutoHighlightCount(config),
570
- );
571
- spectrumsForRender = highlightSlice.spectrums;
572
- beatIndicesForRender = highlightSlice.beatFrameIndices;
573
- beatIntensitiesForRender = highlightSlice.beatIntensities;
574
- framesCountForRender = highlightSlice.highlightFrames;
575
- reportProgress(PRE_PROCESS_PROGRESS_SHARE + POST_AUDIO_PROGRESS_SHARE);
576
- } else {
577
- reportProgress(PRE_PROCESS_PROGRESS_SHARE + POST_AUDIO_PROGRESS_SHARE);
578
- }
579
-
580
- const autoEditVideo = getAutoEditVideo(config);
581
- const cameraShakeEnabled = getCameraShakeEnabled(config);
582
- const shakeDelayFrames = Math.round(FPS * CAMERA_SHAKE_DELAY_SECONDS);
583
- let trackTempo: TempoEstimate | null = null;
584
- if (autoEditVideo) {
585
- const sampleRateNum = Number(sampleRate);
586
- const maxSamples = Math.floor(sampleRateNum * MAX_TEMPO_ANALYSIS_SECONDS);
587
- const tempoBuffer = audioBuffer.length > maxSamples
588
- ? audioBuffer.slice(0, maxSamples)
589
- : audioBuffer;
590
- trackTempo = estimateTempo(pcmU8ToFloatSamples(tempoBuffer), sampleRateNum, FPS);
591
- }
592
-
593
- const separateHighlightFiles =
594
- autoHighlight &&
595
- highlightSlice &&
596
- highlightSlice.runs.length > 1;
597
-
598
- type VideoRenderPass = {
599
- outPath: string;
600
- spectrums: number[][];
601
- beatIndices: number[];
602
- beatIntensities: number[];
603
- frameCount: number;
604
- startFrame: number;
605
- audioSegment: import('./highlight').HighlightAudioSegment | undefined;
606
- };
607
-
608
- const passes: VideoRenderPass[] =
609
- separateHighlightFiles && highlightSlice
610
- ? highlightSlice.runs.map((run, i) => {
611
- const dir = path.dirname(outVideoPath);
612
- const ext = path.extname(outVideoPath);
613
- const base = path.basename(outVideoPath, ext);
614
- const numberedPath = path.resolve(dir, `${base}-${i + 1}${ext}`);
615
- return {
616
- outPath: numberedPath,
617
- spectrums: run.spectrums,
618
- beatIndices: run.beatFrameIndices,
619
- beatIntensities: run.beatIntensities,
620
- frameCount: run.highlightFrames,
621
- startFrame: run.startFrame,
622
- audioSegment: run.audioSegment,
623
- };
624
- })
625
- : [
626
- {
627
- outPath: outVideoPath,
628
- spectrums: spectrumsForRender,
629
- beatIndices: beatIndicesForRender,
630
- beatIntensities: beatIntensitiesForRender,
631
- frameCount: framesCountForRender,
632
- startFrame: highlightSlice?.startFrame ?? 0,
633
- audioSegment:
634
- autoHighlight &&
635
- highlightSlice &&
636
- highlightSlice.audioSegments.length > 0
637
- ? highlightSlice.audioSegments[0]
638
- : undefined,
639
- },
640
- ];
641
-
642
- const totalPassFrames =
643
- passes.reduce((sum, pass) => sum + pass.frameCount, 0);
644
- const totalRenderMilestones = totalPassFrames + (passes.length * 2);
645
- let renderMilestonesCompleted = 0;
646
- const reportRenderProgress = (milestoneIncrement = 1) => {
647
- renderMilestonesCompleted += milestoneIncrement;
648
- reportProgress(
649
- PRE_PROCESS_PROGRESS_SHARE
650
- + POST_AUDIO_PROGRESS_SHARE
651
- + (RENDER_PROGRESS_SHARE * renderMilestonesCompleted / Math.max(1, totalRenderMilestones)),
652
- );
653
- };
654
- let lastExitCode = 0;
655
- let exitReason: string | undefined;
656
- const outputVideoFiles: string[] = [];
657
- try {
658
- passLoop: for (let passIndex = 0; passIndex < passes.length; passIndex++) {
659
- const pass = passes[passIndex];
660
- const tempo = trackTempo
661
- ? tempoForWindow(trackTempo, pass.startFrame, FPS, pass.frameCount, pass.beatIndices)
662
- : null;
663
- const shakeAmplitudes = tempo
664
- ? buildCutShakeAmplitudes(tempo.periodFrames)
665
- : undefined;
666
- const {
667
- backgroundWidth,
668
- backgroundHeight,
669
- defaultColor,
670
- staticBackgroundBuffer,
671
- videoFrameReader,
672
- videoFrameSize,
673
- encodeVideoFrame,
674
- concatFilePath,
675
- cutFrameIndices,
676
- } = await prepareBackgroundForRender({
677
- useVideoBackground,
678
- backgroundVideoPaths,
679
- backgroundImagePath,
680
- beatFrameIndices: pass.beatIndices,
681
- beatIntensities: pass.beatIntensities,
682
- framesCount: pass.frameCount,
683
- outputResolution,
684
- fps: FPS,
685
- autoEditVideo,
686
- readVideoFrameTimeout: videoTimeouts.readVideoFrame,
687
- ...(tempo ? { tempo } : {}),
688
- // Each separate highlight output opens with a different video from the array.
689
- startVideoIndex: passIndex,
690
- });
691
- reportRenderProgress();
692
-
693
- const beatShakeFrames = () => (tempo
694
- ? beatGridFrameIndices(tempo, pass.frameCount, CAMERA_SHAKE_EVERY_BEATS)
695
- : pass.beatIndices.filter(frameIndex => frameIndex > 0).filter((_, i) => i % CAMERA_SHAKE_EVERY_BEATS === 0));
696
- const shakeFrames = new Set(
697
- autoEditVideo && cameraShakeEnabled
698
- ? (cutFrameIndices.length > 0 ? cutFrameIndices : beatShakeFrames())
699
- : [],
700
- );
701
- const createVisualizerFrame = createVisualizerFrameGenerator(
702
- config, backgroundWidth, backgroundHeight, defaultColor, spectrumBusMargin
703
- );
704
-
705
- const ffmpegVideoWriter = spawnFfmpegVideoWriter({
706
- audioFilename: audioFilePath,
707
- videoFileName: pass.outPath,
708
- ...(subtitleFilePath && {
709
- subtitleFilename: subtitleFilePath,
710
- subtitleAlignmentAss,
711
- }),
712
- fps: FPS,
713
- ...(pass.audioSegment && { audioSegment: pass.audioSegment }),
714
- ...(ffmpeg_cfr && { crf: ffmpeg_cfr }),
715
- ...(ffmpeg_preset && { preset: ffmpeg_preset }),
716
- });
717
- const exitPromise = waitForProcessExit(
718
- ffmpegVideoWriter,
719
- videoTimeouts.waitForProcessExit,
720
- );
721
-
722
- let stoppedEarly = false;
723
- for (let i = 0; i < pass.frameCount; i++) {
724
- const spectrum = pass.spectrums[i];
725
- const { frameBuffer: backgroundImageBuffer, frameReadFailed } = await resolveBackgroundFrameBuffer({
726
- frameIndex: i,
727
- useVideoBackground,
728
- videoFrameReader,
729
- videoFrameSize,
730
- encodeVideoFrame,
731
- staticBackgroundBuffer,
732
- readVideoFrameTimeout: videoTimeouts.readVideoFrame,
733
- });
734
-
735
- const commonVisualizerFrameProps: CommonVisualizerFrameProps = {
736
- backgroundImageBuffer,
737
- spectrum,
738
- };
739
- const frameImage = createVisualizerFrame(commonVisualizerFrameProps);
740
- const shakeOffset = getCutShakeOffset(i, shakeFrames, shakeAmplitudes, shakeDelayFrames);
741
- if (shakeOffset.x !== 0 || shakeOffset.y !== 0) {
742
- applyCameraShake(frameImage, backgroundWidth, backgroundHeight, shakeOffset.x, shakeOffset.y);
743
- }
744
- const isFrameProcessed = ffmpegVideoWriter.stdin.write(frameImage.data);
745
- if (!isFrameProcessed) {
746
- const isDrained = await waitDrain(
747
- ffmpegVideoWriter.stdin,
748
- ffmpegVideoWriter,
749
- videoTimeouts.waitDrain,
750
- );
751
- if (!isDrained) {
752
- stoppedEarly = true;
753
- exitReason = 'ffmpeg stdin drain failed';
754
- break;
755
- }
756
- }
757
- if (shouldStop && shouldStop()) {
758
- stoppedEarly = true;
759
- exitReason = 'render stopped by shouldStop callback';
760
- break;
761
- }
762
- if (frame_processing_delay) {
763
- await sleep(frame_processing_delay);
764
- }
765
- await waitForEventLoop();
766
- reportRenderProgress();
767
- }
768
-
769
- if (videoFrameReader) {
770
- videoFrameReader.kill();
771
- }
772
- if (concatFilePath) {
773
- cleanupConcatFile(concatFilePath);
774
- }
775
- ffmpegVideoWriter.stdin.end();
776
-
777
- const { exitCode, reason: ffmpegExitReason } = await exitPromise;
778
- lastExitCode = exitCode;
779
- if (!exitReason && ffmpegExitReason) {
780
- exitReason = ffmpegExitReason;
781
- }
782
- if (lastExitCode === 0 && !stoppedEarly) {
783
- reportRenderProgress();
784
- }
785
-
786
- if (lastExitCode === 0 && !stoppedEarly) {
787
- outputVideoFiles.push(pass.outPath);
788
- }
789
-
790
- if (stoppedEarly || lastExitCode !== 0) {
791
- if (exitReason && lastExitCode === 0) {
792
- lastExitCode = 1;
793
- }
794
- break passLoop;
795
- }
796
- }
797
-
798
- if (lastExitCode === 0 && outputVideoFiles.length === passes.length) {
799
- reportProgress(100);
800
- }
801
- if (exitReason) {
802
- console.error(exitReason);
803
- }
804
-
805
- resolve({ exitCode: lastExitCode, reason: exitReason, outputVideoFiles });
806
- } finally {
807
- if (subtitleFilePath && subtitleFileIsTemporary) {
808
- cleanupTempFile(subtitleFilePath);
809
- }
810
- }
811
- });
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
+ });