nodejs-audio-visualizer 4.3.7 → 4.3.9

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 (47) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +75 -75
  3. package/dist/audio.d.ts +12 -12
  4. package/dist/audio.js +120 -120
  5. package/dist/beats.d.ts +19 -19
  6. package/dist/beats.js +43 -43
  7. package/dist/bpmEncoder.d.ts +14 -14
  8. package/dist/bpmEncoder.js +97 -97
  9. package/dist/config.d.ts +67 -67
  10. package/dist/config.js +356 -356
  11. package/dist/dsp.d.ts +16 -16
  12. package/dist/dsp.js +76 -76
  13. package/dist/highlight.d.ts +32 -32
  14. package/dist/highlight.js +325 -325
  15. package/dist/image.d.ts +79 -79
  16. package/dist/image.js +458 -458
  17. package/dist/index.d.ts +72 -72
  18. package/dist/index.js +539 -541
  19. package/dist/index.js.map +1 -1
  20. package/dist/subtitleConvert.d.ts +3 -3
  21. package/dist/subtitleConvert.js +61 -61
  22. package/dist/video.d.ts +77 -72
  23. package/dist/video.js +407 -338
  24. package/dist/video.js.map +1 -1
  25. package/dist/waitForEventLoop.d.ts +1 -1
  26. package/dist/waitForEventLoop.js +5 -5
  27. package/package.json +61 -61
  28. package/src/audio.ts +120 -120
  29. package/src/beats.ts +68 -68
  30. package/src/bpmEncoder.ts +97 -97
  31. package/src/config.ts +462 -462
  32. package/src/dsp.ts +95 -95
  33. package/src/highlight.ts +284 -284
  34. package/src/image.ts +602 -602
  35. package/src/index.ts +693 -678
  36. package/src/subtitleConvert.ts +63 -63
  37. package/src/tests/audio.test.ts +96 -96
  38. package/src/tests/config.test.ts +475 -475
  39. package/src/tests/dsp.test.ts +24 -24
  40. package/src/tests/highlight.test.ts +178 -178
  41. package/src/tests/image.test.ts +222 -222
  42. package/src/tests/index.test.ts +156 -63
  43. package/src/tests/subtitleConvert.test.ts +23 -23
  44. package/src/tests/video.test.ts +214 -138
  45. package/src/typings.d.ts +6 -6
  46. package/src/video.ts +517 -437
  47. package/src/waitForEventLoop.ts +2 -2
package/src/video.ts CHANGED
@@ -1,437 +1,517 @@
1
- import { Readable, Writable } from 'stream';
2
- import { spawn } from 'child_process';
3
- import { writeFileSync, unlinkSync } from 'fs';
4
- import { resolve as resolvePath, join as joinPath } from 'path';
5
- import { tmpdir } from 'os';
6
- import ffmpegPath from 'ffmpeg-static';
7
-
8
- export interface AudioMuxSegment {
9
- seekSeconds: number;
10
- durationSeconds: number;
11
- }
12
-
13
- interface FfmpegVideoWriterConfig {
14
- audioFilename: string;
15
- subtitleFilename?: string;
16
- /** ASS `Alignment` in FFmpeg `subtitles` `force_style` (e.g. 2 bottom, 5 middle, 8 top). Default 2. */
17
- subtitleAlignmentAss?: number;
18
- videoFileName: string;
19
- fps: number;
20
- crf?: string;
21
- preset?: string;
22
- onStderr?: (data: any) => any;
23
- /** When set with `audioDurationSeconds`, passed to ffmpeg before `-i` for muxed highlight. */
24
- audioSeekSeconds?: number;
25
- audioDurationSeconds?: number;
26
- /** One contiguous trim of the same audio file (muxed highlight). */
27
- audioSegment?: AudioMuxSegment;
28
- }
29
-
30
- const escapeSubtitleFilterPath = (subtitlePath: string) =>
31
- subtitlePath
32
- .replace(/\\/g, '\\\\')
33
- .replace(/:/g, '\\:')
34
- .replace(/'/g, "\\'")
35
- .replace(/,/g, '\\,')
36
- .replace(/\[/g, '\\[')
37
- .replace(/\]/g, '\\]');
38
-
39
- export const spawnFfmpegVideoWriter = (config: FfmpegVideoWriterConfig) => {
40
- if (!ffmpegPath) {
41
- throw new Error('ffmpeg path not found');
42
- }
43
- const crf = config.crf || '23';
44
- const preset = config.preset || 'medium';
45
- const args: string[] = ['-y'];
46
- const seek =
47
- config.audioSegment?.seekSeconds ?? config.audioSeekSeconds;
48
- const duration =
49
- config.audioSegment?.durationSeconds ?? config.audioDurationSeconds;
50
- if (seek !== undefined && duration !== undefined) {
51
- args.push('-ss', String(seek), '-t', String(duration));
52
- }
53
- args.push(
54
- '-i', config.audioFilename,
55
- '-crf', crf,
56
- '-c:a', 'aac', '-b:a', '384k', '-profile:a', 'aac_low',
57
- '-c:v', 'libx264',
58
- '-r', `${config.fps}`,
59
- '-pix_fmt', 'yuv420p',
60
- '-preset', preset,
61
- );
62
- if (config.subtitleFilename) {
63
- const subPath = escapeSubtitleFilterPath(config.subtitleFilename);
64
- const alignment = config.subtitleAlignmentAss ?? 2;
65
- args.push(
66
- '-vf',
67
- `subtitles='${subPath}':force_style='Alignment=${alignment}'`,
68
- );
69
- }
70
- args.push(
71
- config.videoFileName,
72
- '-r', `${config.fps}`,
73
- '-i', '-'
74
- );
75
- const ffmpeg = spawn(ffmpegPath, args);
76
- if (config.onStderr) {
77
- ffmpeg.stderr.on('data', config.onStderr);
78
- }
79
- return ffmpeg;
80
- };
81
-
82
- export interface VideoInfo {
83
- width: number;
84
- height: number;
85
- duration: number;
86
- }
87
-
88
- export interface SceneChange {
89
- frameNumber: number;
90
- pts: number;
91
- ptsTime: number;
92
- }
93
-
94
- export const detectSceneChanges = (videoPath: string, threshold = 0.4): Promise<SceneChange[]> =>
95
- new Promise((resolve, reject) => {
96
- if (!ffmpegPath) {
97
- reject(new Error('ffmpeg path not found'));
98
- return;
99
- }
100
- const ffmpeg = spawn(ffmpegPath, [
101
- '-i', videoPath,
102
- '-filter:v', `select='gt(scene,${threshold})',showinfo`,
103
- '-f', 'null',
104
- '-'
105
- ]);
106
- let stderr = '';
107
- ffmpeg.stderr.on('data', (data: Buffer) => { stderr += data.toString(); });
108
- ffmpeg.on('close', () => {
109
- const sceneChanges: SceneChange[] = [];
110
- for (const line of stderr.split('\n')) {
111
- if (!line.includes('Parsed_showinfo')) continue;
112
- const nMatch = line.match(/n:\s*(\d+)/);
113
- const ptsMatch = line.match(/pts:\s*(\d+)/);
114
- const ptsTimeMatch = line.match(/pts_time:\s*([\d.]+)/);
115
- if (nMatch && ptsTimeMatch) {
116
- sceneChanges.push({
117
- frameNumber: parseInt(nMatch[1]),
118
- pts: ptsMatch ? parseInt(ptsMatch[1]) : 0,
119
- ptsTime: parseFloat(ptsTimeMatch[1]),
120
- });
121
- }
122
- }
123
- resolve(sceneChanges);
124
- });
125
- ffmpeg.on('error', reject);
126
- });
127
-
128
- export const getVideoInfo = (videoPath: string): Promise<VideoInfo> =>
129
- new Promise((resolvePromise, reject) => {
130
- if (!ffmpegPath) {
131
- reject(new Error('ffmpeg path not found'));
132
- return;
133
- }
134
- const ffmpeg = spawn(ffmpegPath, ['-i', videoPath, '-hide_banner']);
135
- let stderr = '';
136
- ffmpeg.stderr.on('data', (data: Buffer) => { stderr += data.toString(); });
137
- ffmpeg.on('close', () => {
138
- const dimMatch = stderr.match(/Stream.*Video:.*?(\d{2,5})x(\d{2,5})/);
139
- if (!dimMatch) {
140
- reject(new Error(`Could not determine video dimensions for: ${videoPath}`));
141
- return;
142
- }
143
- const durMatch = stderr.match(/Duration:\s*(\d+):(\d+):([\d.]+)/);
144
- const duration = durMatch
145
- ? parseInt(durMatch[1]) * 3600 + parseInt(durMatch[2]) * 60 + parseFloat(durMatch[3])
146
- : 0;
147
- resolvePromise({
148
- width: parseInt(dimMatch[1]),
149
- height: parseInt(dimMatch[2]),
150
- duration,
151
- });
152
- });
153
- });
154
-
155
- const isOrientationMismatch = (sw: number, sh: number, tw: number, th: number): boolean =>
156
- (sw > sh && tw < th) || (sw < sh && tw > th);
157
-
158
- export const buildVideoFilter = (
159
- sourceWidth: number,
160
- sourceHeight: number,
161
- targetWidth: number,
162
- targetHeight: number,
163
- ): string => {
164
- if (!isOrientationMismatch(sourceWidth, sourceHeight, targetWidth, targetHeight)) {
165
- return `scale=${targetWidth}:${targetHeight}`;
166
- }
167
-
168
- const targetAspect = targetWidth / targetHeight;
169
- const makeEven = (n: number) => Math.floor(n / 2) * 2;
170
- let cropW: number, cropH: number, cropX: number, cropY: number;
171
-
172
- if (sourceWidth / sourceHeight > targetAspect) {
173
- cropW = makeEven(Math.round(sourceHeight * targetAspect));
174
- cropH = makeEven(sourceHeight);
175
- cropX = Math.floor((sourceWidth - cropW) / 2);
176
- cropY = Math.floor((sourceHeight - cropH) / 2);
177
- } else {
178
- cropW = makeEven(sourceWidth);
179
- cropH = makeEven(Math.round(sourceWidth / targetAspect));
180
- cropX = Math.floor((sourceWidth - cropW) / 2);
181
- cropY = Math.floor((sourceHeight - cropH) / 2);
182
- }
183
-
184
- return `crop=${cropW}:${cropH}:${cropX}:${cropY},scale=${targetWidth}:${targetHeight}`;
185
- };
186
-
187
- export const spawnVideoFrameReader = (config: {
188
- videoPath: string;
189
- fps: number;
190
- totalFrames: number;
191
- width?: number;
192
- height?: number;
193
- sourceWidth?: number;
194
- sourceHeight?: number;
195
- }) => {
196
- if (!ffmpegPath) {
197
- throw new Error('ffmpeg path not found');
198
- }
199
- const args = [
200
- '-stream_loop', '-1',
201
- '-i', config.videoPath,
202
- '-r', `${config.fps}`,
203
- '-frames:v', `${config.totalFrames}`,
204
- ];
205
- if (config.width && config.height) {
206
- const filter = config.sourceWidth && config.sourceHeight
207
- ? buildVideoFilter(config.sourceWidth, config.sourceHeight, config.width, config.height)
208
- : `scale=${config.width}:${config.height}`;
209
- args.push('-vf', filter);
210
- }
211
- args.push(
212
- '-f', 'rawvideo',
213
- '-pix_fmt', 'bgr24',
214
- '-v', 'quiet',
215
- 'pipe:1'
216
- );
217
- return spawn(ffmpegPath, args);
218
- };
219
-
220
- export const readVideoFrame = (stream: Readable, frameSize: number): Promise<Buffer | null> =>
221
- new Promise((resolve) => {
222
- const tryRead = () => {
223
- const data = stream.read(frameSize) as Buffer | null;
224
- if (data !== null) {
225
- resolve(data.length === frameSize ? data : null);
226
- return;
227
- }
228
- const onReadable = () => {
229
- cleanup();
230
- tryRead();
231
- };
232
- const onEnd = () => {
233
- cleanup();
234
- resolve(null);
235
- };
236
- const cleanup = () => {
237
- stream.removeListener('readable', onReadable);
238
- stream.removeListener('end', onEnd);
239
- };
240
- stream.once('readable', onReadable);
241
- stream.once('end', onEnd);
242
- };
243
- tryRead();
244
- });
245
-
246
- export const getProgress = (onProgress: (currentFrame: number) => any) =>
247
- (stderrOutput: Buffer) => {
248
- const matchResult = stderrOutput.toString().match(/frame=[ ]+(\d+)/);
249
- if (!matchResult) {
250
- return;
251
- }
252
- const currentFrame = +matchResult[1];
253
- if (isNaN(currentFrame)) {
254
- return;
255
- }
256
- onProgress(currentFrame);
257
- };
258
-
259
- export const calculateProgress = (framesCount: number, callback: (progress: number) => any) =>
260
- (currentFrame: number) =>
261
- callback(
262
- +(currentFrame / framesCount * 100).toFixed(2)
263
- );
264
-
265
- export const waitDrain = (
266
- stream: Writable,
267
- processStream?: {
268
- once: (eventName: string, listener: (...args: any[]) => void) => any;
269
- removeListener: (eventName: string, listener: (...args: any[]) => void) => any;
270
- },
271
- ) =>
272
- new Promise<boolean>(resolve => {
273
- const cleanup = () => {
274
- stream.removeListener('drain', onDrain);
275
- stream.removeListener('error', onErrorOrClose);
276
- stream.removeListener('close', onErrorOrClose);
277
- processStream?.removeListener('error', onErrorOrClose);
278
- processStream?.removeListener('exit', onErrorOrClose);
279
- processStream?.removeListener('close', onErrorOrClose);
280
- };
281
- const onDrain = () => {
282
- cleanup();
283
- resolve(true);
284
- };
285
- const onErrorOrClose = () => {
286
- cleanup();
287
- resolve(false);
288
- };
289
- stream.once('drain', onDrain);
290
- stream.once('error', onErrorOrClose);
291
- stream.once('close', onErrorOrClose);
292
- processStream?.once('error', onErrorOrClose);
293
- processStream?.once('exit', onErrorOrClose);
294
- processStream?.once('close', onErrorOrClose);
295
- });
296
-
297
- export interface VideoSegment {
298
- outputStartFrame: number;
299
- videoSeekSeconds: number;
300
- frameCount: number;
301
- }
302
-
303
- const mergeSmallScenes = (sceneChanges: SceneChange[], videoDuration: number, minDuration = 2): SceneChange[] => {
304
- if (sceneChanges.length === 0) return [];
305
- const merged: SceneChange[] = [sceneChanges[0]];
306
- for (let i = 1; i < sceneChanges.length; i++) {
307
- const lastKept = merged[merged.length - 1];
308
- const gap = sceneChanges[i].ptsTime - lastKept.ptsTime;
309
- if (gap >= minDuration) {
310
- merged.push(sceneChanges[i]);
311
- }
312
- }
313
- const lastScene = merged[merged.length - 1];
314
- if (videoDuration - lastScene.ptsTime < minDuration && merged.length > 1) {
315
- merged.pop();
316
- }
317
- return merged;
318
- };
319
-
320
- export const buildBeatSyncedSegments = (
321
- beatFrameIndices: number[],
322
- totalFrames: number,
323
- sceneChanges: SceneChange[],
324
- videoDuration: number,
325
- ): VideoSegment[] => {
326
- if (sceneChanges.length === 0) {
327
- return [
328
- {
329
- outputStartFrame: 0,
330
- videoSeekSeconds: 0,
331
- frameCount: totalFrames,
332
- },
333
- ];
334
- }
335
-
336
- const consolidated = mergeSmallScenes(sceneChanges, videoDuration);
337
- let seekPositions: number[];
338
- if (consolidated.length >= 2) {
339
- seekPositions = consolidated.map(sc => sc.ptsTime);
340
- } else {
341
- const count = Math.max(10, Math.ceil(videoDuration / 3));
342
- seekPositions = Array.from({ length: count }, (_, i) => (i * videoDuration) / count);
343
- }
344
-
345
- const boundaries = [0, ...beatFrameIndices];
346
- if (boundaries[boundaries.length - 1] !== totalFrames) {
347
- boundaries.push(totalFrames);
348
- }
349
- const unique = Array.from(new Set(boundaries)).sort((a, b) => a - b);
350
-
351
- const segments: VideoSegment[] = [];
352
- for (let i = 0; i < unique.length - 1; i++) {
353
- segments.push({
354
- outputStartFrame: unique[i],
355
- videoSeekSeconds: seekPositions[i % seekPositions.length],
356
- frameCount: unique[i + 1] - unique[i],
357
- });
358
- }
359
- return segments;
360
- };
361
-
362
- export const writeConcatFile = (
363
- segments: VideoSegment[],
364
- videoPath: string,
365
- videoDuration: number,
366
- fps: number,
367
- ): string => {
368
- const absVideoPath = resolvePath(videoPath).replace(/\\/g, '/');
369
- const escaped = absVideoPath.replace(/'/g, "'\\''");
370
- let content = '';
371
-
372
- for (const seg of segments) {
373
- const segDuration = seg.frameCount / fps;
374
- let remaining = segDuration;
375
- let pos = seg.videoSeekSeconds % videoDuration;
376
-
377
- while (remaining > 0.001) {
378
- const available = videoDuration - pos;
379
- const take = Math.min(remaining, available);
380
- content += `file '${escaped}'\n`;
381
- content += `inpoint ${pos.toFixed(6)}\n`;
382
- content += `outpoint ${(pos + take).toFixed(6)}\n\n`;
383
- remaining -= take;
384
- pos = 0;
385
- }
386
- }
387
-
388
- const concatPath = joinPath(tmpdir(), `av-concat-${Date.now()}.txt`);
389
- writeFileSync(concatPath, content, 'utf-8');
390
- return concatPath;
391
- };
392
-
393
- export const writeSubtitlesFile = (subtitles: string): string => {
394
- const subtitlePath = joinPath(tmpdir(), `av-subtitles-${Date.now()}.srt`);
395
- writeFileSync(subtitlePath, subtitles, 'utf-8');
396
- return subtitlePath;
397
- };
398
-
399
- export const spawnConcatVideoFrameReader = (config: {
400
- concatFilePath: string;
401
- fps: number;
402
- totalFrames: number;
403
- width?: number;
404
- height?: number;
405
- sourceWidth?: number;
406
- sourceHeight?: number;
407
- }) => {
408
- if (!ffmpegPath) {
409
- throw new Error('ffmpeg path not found');
410
- }
411
- const args = [
412
- '-f', 'concat',
413
- '-safe', '0',
414
- '-i', config.concatFilePath,
415
- '-r', `${config.fps}`,
416
- '-frames:v', `${config.totalFrames}`,
417
- ];
418
- if (config.width && config.height) {
419
- const filter = config.sourceWidth && config.sourceHeight
420
- ? buildVideoFilter(config.sourceWidth, config.sourceHeight, config.width, config.height)
421
- : `scale=${config.width}:${config.height}`;
422
- args.push('-vf', filter);
423
- }
424
- args.push(
425
- '-f', 'rawvideo',
426
- '-pix_fmt', 'bgr24',
427
- '-v', 'quiet',
428
- 'pipe:1'
429
- );
430
- return spawn(ffmpegPath, args);
431
- };
432
-
433
- export const cleanupTempFile = (filePath: string) => {
434
- try { unlinkSync(filePath); } catch {}
435
- };
436
-
437
- export const cleanupConcatFile = cleanupTempFile;
1
+ import { Readable, Writable } from 'stream';
2
+ import { spawn } from 'child_process';
3
+ import { writeFileSync, unlinkSync } from 'fs';
4
+ import { resolve as resolvePath, join as joinPath } from 'path';
5
+ import { tmpdir } from 'os';
6
+ import ffmpegPath from 'ffmpeg-static';
7
+
8
+ export const DEFAULT_WAIT_TIMEOUT_MS = 1000;
9
+
10
+ export interface AudioMuxSegment {
11
+ seekSeconds: number;
12
+ durationSeconds: number;
13
+ }
14
+
15
+ interface FfmpegVideoWriterConfig {
16
+ audioFilename: string;
17
+ subtitleFilename?: string;
18
+ /** ASS `Alignment` in FFmpeg `subtitles` `force_style` (e.g. 2 bottom, 5 middle, 8 top). Default 2. */
19
+ subtitleAlignmentAss?: number;
20
+ videoFileName: string;
21
+ fps: number;
22
+ crf?: string;
23
+ preset?: string;
24
+ onStderr?: (data: any) => any;
25
+ /** When set with `audioDurationSeconds`, passed to ffmpeg before `-i` for muxed highlight. */
26
+ audioSeekSeconds?: number;
27
+ audioDurationSeconds?: number;
28
+ /** One contiguous trim of the same audio file (muxed highlight). */
29
+ audioSegment?: AudioMuxSegment;
30
+ }
31
+
32
+ const escapeSubtitleFilterPath = (subtitlePath: string) =>
33
+ subtitlePath
34
+ .replace(/\\/g, '\\\\')
35
+ .replace(/:/g, '\\:')
36
+ .replace(/'/g, "\\'")
37
+ .replace(/,/g, '\\,')
38
+ .replace(/\[/g, '\\[')
39
+ .replace(/\]/g, '\\]');
40
+
41
+ export const spawnFfmpegVideoWriter = (config: FfmpegVideoWriterConfig) => {
42
+ if (!ffmpegPath) {
43
+ throw new Error('ffmpeg path not found');
44
+ }
45
+ const crf = config.crf || '23';
46
+ const preset = config.preset || 'medium';
47
+ const args: string[] = ['-y'];
48
+ const seek =
49
+ config.audioSegment?.seekSeconds ?? config.audioSeekSeconds;
50
+ const duration =
51
+ config.audioSegment?.durationSeconds ?? config.audioDurationSeconds;
52
+ if (seek !== undefined && duration !== undefined) {
53
+ args.push('-ss', String(seek), '-t', String(duration));
54
+ }
55
+ args.push(
56
+ '-i', config.audioFilename,
57
+ '-f', 'image2pipe',
58
+ '-vcodec', 'bmp',
59
+ '-framerate', `${config.fps}`,
60
+ '-i', '-',
61
+ '-crf', crf,
62
+ '-c:a', 'aac', '-b:a', '384k', '-profile:a', 'aac_low',
63
+ '-c:v', 'libx264',
64
+ '-r', `${config.fps}`,
65
+ '-pix_fmt', 'yuv420p',
66
+ '-preset', preset,
67
+ '-shortest',
68
+ );
69
+ if (config.subtitleFilename) {
70
+ const subPath = escapeSubtitleFilterPath(config.subtitleFilename);
71
+ const alignment = config.subtitleAlignmentAss ?? 2;
72
+ args.push(
73
+ '-vf',
74
+ `subtitles='${subPath}':force_style='Alignment=${alignment}'`,
75
+ );
76
+ }
77
+ args.push(config.videoFileName);
78
+ const ffmpeg = spawn(ffmpegPath, args);
79
+ if (config.onStderr) {
80
+ ffmpeg.stderr.on('data', config.onStderr);
81
+ }
82
+ return ffmpeg;
83
+ };
84
+
85
+ export interface VideoInfo {
86
+ width: number;
87
+ height: number;
88
+ duration: number;
89
+ }
90
+
91
+ export interface SceneChange {
92
+ frameNumber: number;
93
+ pts: number;
94
+ ptsTime: number;
95
+ }
96
+
97
+ export const detectSceneChanges = (videoPath: string, threshold = 0.4): Promise<SceneChange[]> =>
98
+ new Promise((resolve, reject) => {
99
+ if (!ffmpegPath) {
100
+ reject(new Error('ffmpeg path not found'));
101
+ return;
102
+ }
103
+ const ffmpeg = spawn(ffmpegPath, [
104
+ '-i', videoPath,
105
+ '-filter:v', `select='gt(scene,${threshold})',showinfo`,
106
+ '-f', 'null',
107
+ '-'
108
+ ]);
109
+ let stderr = '';
110
+ ffmpeg.stderr.on('data', (data: Buffer) => { stderr += data.toString(); });
111
+ ffmpeg.on('close', () => {
112
+ const sceneChanges: SceneChange[] = [];
113
+ for (const line of stderr.split('\n')) {
114
+ if (!line.includes('Parsed_showinfo')) continue;
115
+ const nMatch = line.match(/n:\s*(\d+)/);
116
+ const ptsMatch = line.match(/pts:\s*(\d+)/);
117
+ const ptsTimeMatch = line.match(/pts_time:\s*([\d.]+)/);
118
+ if (nMatch && ptsTimeMatch) {
119
+ sceneChanges.push({
120
+ frameNumber: parseInt(nMatch[1]),
121
+ pts: ptsMatch ? parseInt(ptsMatch[1]) : 0,
122
+ ptsTime: parseFloat(ptsTimeMatch[1]),
123
+ });
124
+ }
125
+ }
126
+ resolve(sceneChanges);
127
+ });
128
+ ffmpeg.on('error', reject);
129
+ });
130
+
131
+ export const getVideoInfo = (videoPath: string): Promise<VideoInfo> =>
132
+ new Promise((resolvePromise, reject) => {
133
+ if (!ffmpegPath) {
134
+ reject(new Error('ffmpeg path not found'));
135
+ return;
136
+ }
137
+ const ffmpeg = spawn(ffmpegPath, ['-i', videoPath, '-hide_banner']);
138
+ let stderr = '';
139
+ ffmpeg.stderr.on('data', (data: Buffer) => { stderr += data.toString(); });
140
+ ffmpeg.on('close', () => {
141
+ const dimMatch = stderr.match(/Stream.*Video:.*?(\d{2,5})x(\d{2,5})/);
142
+ if (!dimMatch) {
143
+ reject(new Error(`Could not determine video dimensions for: ${videoPath}`));
144
+ return;
145
+ }
146
+ const durMatch = stderr.match(/Duration:\s*(\d+):(\d+):([\d.]+)/);
147
+ const duration = durMatch
148
+ ? parseInt(durMatch[1]) * 3600 + parseInt(durMatch[2]) * 60 + parseFloat(durMatch[3])
149
+ : 0;
150
+ resolvePromise({
151
+ width: parseInt(dimMatch[1]),
152
+ height: parseInt(dimMatch[2]),
153
+ duration,
154
+ });
155
+ });
156
+ });
157
+
158
+ const isOrientationMismatch = (sw: number, sh: number, tw: number, th: number): boolean =>
159
+ (sw > sh && tw < th) || (sw < sh && tw > th);
160
+
161
+ export const buildVideoFilter = (
162
+ sourceWidth: number,
163
+ sourceHeight: number,
164
+ targetWidth: number,
165
+ targetHeight: number,
166
+ ): string => {
167
+ if (!isOrientationMismatch(sourceWidth, sourceHeight, targetWidth, targetHeight)) {
168
+ return `scale=${targetWidth}:${targetHeight}`;
169
+ }
170
+
171
+ const targetAspect = targetWidth / targetHeight;
172
+ const makeEven = (n: number) => Math.floor(n / 2) * 2;
173
+ let cropW: number, cropH: number, cropX: number, cropY: number;
174
+
175
+ if (sourceWidth / sourceHeight > targetAspect) {
176
+ cropW = makeEven(Math.round(sourceHeight * targetAspect));
177
+ cropH = makeEven(sourceHeight);
178
+ cropX = Math.floor((sourceWidth - cropW) / 2);
179
+ cropY = Math.floor((sourceHeight - cropH) / 2);
180
+ } else {
181
+ cropW = makeEven(sourceWidth);
182
+ cropH = makeEven(Math.round(sourceWidth / targetAspect));
183
+ cropX = Math.floor((sourceWidth - cropW) / 2);
184
+ cropY = Math.floor((sourceHeight - cropH) / 2);
185
+ }
186
+
187
+ return `crop=${cropW}:${cropH}:${cropX}:${cropY},scale=${targetWidth}:${targetHeight}`;
188
+ };
189
+
190
+ export const spawnVideoFrameReader = (config: {
191
+ videoPath: string;
192
+ fps: number;
193
+ totalFrames: number;
194
+ width?: number;
195
+ height?: number;
196
+ sourceWidth?: number;
197
+ sourceHeight?: number;
198
+ }) => {
199
+ if (!ffmpegPath) {
200
+ throw new Error('ffmpeg path not found');
201
+ }
202
+ const args = [
203
+ '-stream_loop', '-1',
204
+ '-i', config.videoPath,
205
+ '-r', `${config.fps}`,
206
+ '-frames:v', `${config.totalFrames}`,
207
+ ];
208
+ if (config.width && config.height) {
209
+ const filter = config.sourceWidth && config.sourceHeight
210
+ ? buildVideoFilter(config.sourceWidth, config.sourceHeight, config.width, config.height)
211
+ : `scale=${config.width}:${config.height}`;
212
+ args.push('-vf', filter);
213
+ }
214
+ args.push(
215
+ '-f', 'rawvideo',
216
+ '-pix_fmt', 'bgr24',
217
+ '-v', 'quiet',
218
+ 'pipe:1'
219
+ );
220
+ return spawn(ffmpegPath, args);
221
+ };
222
+
223
+ export const readVideoFrame = (
224
+ stream: Readable,
225
+ frameSize: number,
226
+ timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
227
+ ): Promise<Buffer | null> =>
228
+ new Promise((resolve) => {
229
+ let timer: NodeJS.Timeout | undefined;
230
+ const cleanup = () => {
231
+ if (timer) {
232
+ clearTimeout(timer);
233
+ timer = undefined;
234
+ }
235
+ stream.removeListener('readable', onReadable);
236
+ stream.removeListener('end', onEnd);
237
+ stream.removeListener('error', onErrorOrClose);
238
+ stream.removeListener('close', onErrorOrClose);
239
+ };
240
+ const onReadable = () => {
241
+ tryRead();
242
+ };
243
+ const onEnd = () => {
244
+ cleanup();
245
+ resolve(null);
246
+ };
247
+ const onErrorOrClose = () => {
248
+ cleanup();
249
+ resolve(null);
250
+ };
251
+ const tryRead = () => {
252
+ const data = stream.read(frameSize) as Buffer | null;
253
+ if (data !== null) {
254
+ cleanup();
255
+ resolve(data.length === frameSize ? data : null);
256
+ return;
257
+ }
258
+ if (timeoutMs > 0) {
259
+ timer = setTimeout(() => {
260
+ cleanup();
261
+ resolve(null);
262
+ }, timeoutMs);
263
+ }
264
+ stream.once('readable', onReadable);
265
+ stream.once('end', onEnd);
266
+ stream.once('error', onErrorOrClose);
267
+ stream.once('close', onErrorOrClose);
268
+ };
269
+ tryRead();
270
+ });
271
+
272
+ export const getProgress = (onProgress: (currentFrame: number) => any) =>
273
+ (stderrOutput: Buffer) => {
274
+ const matchResult = stderrOutput.toString().match(/frame=[ ]+(\d+)/);
275
+ if (!matchResult) {
276
+ return;
277
+ }
278
+ const currentFrame = +matchResult[1];
279
+ if (isNaN(currentFrame)) {
280
+ return;
281
+ }
282
+ onProgress(currentFrame);
283
+ };
284
+
285
+ export const calculateProgress = (framesCount: number, callback: (progress: number) => any) =>
286
+ (currentFrame: number) =>
287
+ callback(
288
+ +(currentFrame / framesCount * 100).toFixed(2)
289
+ );
290
+
291
+ export const waitDrain = (
292
+ stream: Writable,
293
+ processStream?: {
294
+ once: (eventName: string, listener: (...args: any[]) => void) => any;
295
+ removeListener: (eventName: string, listener: (...args: any[]) => void) => any;
296
+ },
297
+ timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
298
+ ) =>
299
+ new Promise<boolean>(resolve => {
300
+ const cleanup = () => {
301
+ if (timer) {
302
+ clearTimeout(timer);
303
+ timer = undefined;
304
+ }
305
+ stream.removeListener('drain', onDrain);
306
+ stream.removeListener('error', onErrorOrClose);
307
+ stream.removeListener('close', onErrorOrClose);
308
+ processStream?.removeListener('error', onErrorOrClose);
309
+ processStream?.removeListener('exit', onErrorOrClose);
310
+ processStream?.removeListener('close', onErrorOrClose);
311
+ };
312
+ const onDrain = () => {
313
+ cleanup();
314
+ resolve(true);
315
+ };
316
+ const onErrorOrClose = () => {
317
+ cleanup();
318
+ resolve(false);
319
+ };
320
+ let timer: NodeJS.Timeout | undefined;
321
+ if (timeoutMs > 0) {
322
+ timer = setTimeout(() => {
323
+ cleanup();
324
+ resolve(false);
325
+ }, timeoutMs);
326
+ }
327
+ stream.once('drain', onDrain);
328
+ stream.once('error', onErrorOrClose);
329
+ stream.once('close', onErrorOrClose);
330
+ processStream?.once('error', onErrorOrClose);
331
+ processStream?.once('exit', onErrorOrClose);
332
+ processStream?.once('close', onErrorOrClose);
333
+ });
334
+
335
+ export const waitForProcessExit = (
336
+ processStream: {
337
+ once: (eventName: string, listener: (...args: any[]) => void) => any;
338
+ removeListener: (eventName: string, listener: (...args: any[]) => void) => any;
339
+ },
340
+ timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
341
+ ) =>
342
+ new Promise<number>(resolve => {
343
+ const cleanup = () => {
344
+ if (timer) {
345
+ clearTimeout(timer);
346
+ timer = undefined;
347
+ }
348
+ processStream.removeListener('exit', onExit);
349
+ processStream.removeListener('close', onClose);
350
+ processStream.removeListener('error', onError);
351
+ };
352
+ const onExit = (code: number | null) => {
353
+ cleanup();
354
+ resolve(code ?? 0);
355
+ };
356
+ const onClose = (code: number | null) => {
357
+ cleanup();
358
+ resolve(code ?? 0);
359
+ };
360
+ const onError = () => {
361
+ cleanup();
362
+ resolve(1);
363
+ };
364
+ let timer: NodeJS.Timeout | undefined;
365
+ if (timeoutMs > 0) {
366
+ timer = setTimeout(() => {
367
+ cleanup();
368
+ resolve(1);
369
+ }, timeoutMs);
370
+ }
371
+
372
+ processStream.once('exit', onExit);
373
+ processStream.once('close', onClose);
374
+ processStream.once('error', onError);
375
+ });
376
+
377
+ export interface VideoSegment {
378
+ outputStartFrame: number;
379
+ videoSeekSeconds: number;
380
+ frameCount: number;
381
+ }
382
+
383
+ const mergeSmallScenes = (sceneChanges: SceneChange[], videoDuration: number, minDuration = 2): SceneChange[] => {
384
+ if (sceneChanges.length === 0) return [];
385
+ const merged: SceneChange[] = [sceneChanges[0]];
386
+ for (let i = 1; i < sceneChanges.length; i++) {
387
+ const lastKept = merged[merged.length - 1];
388
+ const gap = sceneChanges[i].ptsTime - lastKept.ptsTime;
389
+ if (gap >= minDuration) {
390
+ merged.push(sceneChanges[i]);
391
+ }
392
+ }
393
+ const lastScene = merged[merged.length - 1];
394
+ if (videoDuration - lastScene.ptsTime < minDuration && merged.length > 1) {
395
+ merged.pop();
396
+ }
397
+ return merged;
398
+ };
399
+
400
+ export const buildBeatSyncedSegments = (
401
+ beatFrameIndices: number[],
402
+ totalFrames: number,
403
+ sceneChanges: SceneChange[],
404
+ videoDuration: number,
405
+ ): VideoSegment[] => {
406
+ if (sceneChanges.length === 0) {
407
+ return [
408
+ {
409
+ outputStartFrame: 0,
410
+ videoSeekSeconds: 0,
411
+ frameCount: totalFrames,
412
+ },
413
+ ];
414
+ }
415
+
416
+ const consolidated = mergeSmallScenes(sceneChanges, videoDuration);
417
+ let seekPositions: number[];
418
+ if (consolidated.length >= 2) {
419
+ seekPositions = consolidated.map(sc => sc.ptsTime);
420
+ } else {
421
+ const count = Math.max(10, Math.ceil(videoDuration / 3));
422
+ seekPositions = Array.from({ length: count }, (_, i) => (i * videoDuration) / count);
423
+ }
424
+
425
+ const boundaries = [0, ...beatFrameIndices];
426
+ if (boundaries[boundaries.length - 1] !== totalFrames) {
427
+ boundaries.push(totalFrames);
428
+ }
429
+ const unique = Array.from(new Set(boundaries)).sort((a, b) => a - b);
430
+
431
+ const segments: VideoSegment[] = [];
432
+ for (let i = 0; i < unique.length - 1; i++) {
433
+ segments.push({
434
+ outputStartFrame: unique[i],
435
+ videoSeekSeconds: seekPositions[i % seekPositions.length],
436
+ frameCount: unique[i + 1] - unique[i],
437
+ });
438
+ }
439
+ return segments;
440
+ };
441
+
442
+ export const writeConcatFile = (
443
+ segments: VideoSegment[],
444
+ videoPath: string,
445
+ videoDuration: number,
446
+ fps: number,
447
+ ): string => {
448
+ const absVideoPath = resolvePath(videoPath).replace(/\\/g, '/');
449
+ const escaped = absVideoPath.replace(/'/g, "'\\''");
450
+ let content = '';
451
+
452
+ for (const seg of segments) {
453
+ const segDuration = seg.frameCount / fps;
454
+ let remaining = segDuration;
455
+ let pos = seg.videoSeekSeconds % videoDuration;
456
+
457
+ while (remaining > 0.001) {
458
+ const available = videoDuration - pos;
459
+ const take = Math.min(remaining, available);
460
+ content += `file '${escaped}'\n`;
461
+ content += `inpoint ${pos.toFixed(6)}\n`;
462
+ content += `outpoint ${(pos + take).toFixed(6)}\n\n`;
463
+ remaining -= take;
464
+ pos = 0;
465
+ }
466
+ }
467
+
468
+ const concatPath = joinPath(tmpdir(), `av-concat-${Date.now()}.txt`);
469
+ writeFileSync(concatPath, content, 'utf-8');
470
+ return concatPath;
471
+ };
472
+
473
+ export const writeSubtitlesFile = (subtitles: string): string => {
474
+ const subtitlePath = joinPath(tmpdir(), `av-subtitles-${Date.now()}.srt`);
475
+ writeFileSync(subtitlePath, subtitles, 'utf-8');
476
+ return subtitlePath;
477
+ };
478
+
479
+ export const spawnConcatVideoFrameReader = (config: {
480
+ concatFilePath: string;
481
+ fps: number;
482
+ totalFrames: number;
483
+ width?: number;
484
+ height?: number;
485
+ sourceWidth?: number;
486
+ sourceHeight?: number;
487
+ }) => {
488
+ if (!ffmpegPath) {
489
+ throw new Error('ffmpeg path not found');
490
+ }
491
+ const args = [
492
+ '-f', 'concat',
493
+ '-safe', '0',
494
+ '-i', config.concatFilePath,
495
+ '-r', `${config.fps}`,
496
+ '-frames:v', `${config.totalFrames}`,
497
+ ];
498
+ if (config.width && config.height) {
499
+ const filter = config.sourceWidth && config.sourceHeight
500
+ ? buildVideoFilter(config.sourceWidth, config.sourceHeight, config.width, config.height)
501
+ : `scale=${config.width}:${config.height}`;
502
+ args.push('-vf', filter);
503
+ }
504
+ args.push(
505
+ '-f', 'rawvideo',
506
+ '-pix_fmt', 'bgr24',
507
+ '-v', 'quiet',
508
+ 'pipe:1'
509
+ );
510
+ return spawn(ffmpegPath, args);
511
+ };
512
+
513
+ export const cleanupTempFile = (filePath: string) => {
514
+ try { unlinkSync(filePath); } catch {}
515
+ };
516
+
517
+ export const cleanupConcatFile = cleanupTempFile;