nodejs-audio-visualizer 4.2.4 → 4.2.5

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/video.ts CHANGED
@@ -1,375 +1,403 @@
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
- videoFileName: string;
16
- fps: number;
17
- crf?: string;
18
- preset?: string;
19
- onStderr?: (data: any) => any;
20
- /** When set with `audioDurationSeconds`, passed to ffmpeg before `-i` for muxed highlight. */
21
- audioSeekSeconds?: number;
22
- audioDurationSeconds?: number;
23
- /** One contiguous trim of the same audio file (muxed highlight). */
24
- audioSegment?: AudioMuxSegment;
25
- }
26
-
27
- export const spawnFfmpegVideoWriter = (config: FfmpegVideoWriterConfig) => {
28
- if (!ffmpegPath) {
29
- throw new Error('ffmpeg path not found');
30
- }
31
- const crf = config.crf || '23';
32
- const preset = config.preset || 'medium';
33
- const args: string[] = ['-y'];
34
- const seek =
35
- config.audioSegment?.seekSeconds ?? config.audioSeekSeconds;
36
- const duration =
37
- config.audioSegment?.durationSeconds ?? config.audioDurationSeconds;
38
- if (seek !== undefined && duration !== undefined) {
39
- args.push('-ss', String(seek), '-t', String(duration));
40
- }
41
- args.push(
42
- '-i', config.audioFilename,
43
- '-crf', crf,
44
- '-c:a', 'aac', '-b:a', '384k', '-profile:a', 'aac_low',
45
- '-c:v', 'libx264', '-r', `${config.fps}`, '-pix_fmt', 'yuv420p', '-preset', preset, config.videoFileName,
46
- '-r', `${config.fps}`,
47
- '-i', '-'
48
- );
49
- const ffmpeg = spawn(ffmpegPath, args);
50
- ffmpeg.stdin.pipe(process.stdout);
51
- if (config.onStderr) {
52
- ffmpeg.stderr.on('data', config.onStderr);
53
- }
54
- return ffmpeg;
55
- };
56
-
57
- export interface VideoInfo {
58
- width: number;
59
- height: number;
60
- duration: number;
61
- }
62
-
63
- export interface SceneChange {
64
- frameNumber: number;
65
- pts: number;
66
- ptsTime: number;
67
- }
68
-
69
- export const detectSceneChanges = (videoPath: string, threshold = 0.4): Promise<SceneChange[]> =>
70
- new Promise((resolve, reject) => {
71
- if (!ffmpegPath) {
72
- reject(new Error('ffmpeg path not found'));
73
- return;
74
- }
75
- const ffmpeg = spawn(ffmpegPath, [
76
- '-i', videoPath,
77
- '-filter:v', `select='gt(scene,${threshold})',showinfo`,
78
- '-f', 'null',
79
- '-'
80
- ]);
81
- let stderr = '';
82
- ffmpeg.stderr.on('data', (data: Buffer) => { stderr += data.toString(); });
83
- ffmpeg.on('close', () => {
84
- const sceneChanges: SceneChange[] = [];
85
- for (const line of stderr.split('\n')) {
86
- if (!line.includes('Parsed_showinfo')) continue;
87
- const nMatch = line.match(/n:\s*(\d+)/);
88
- const ptsMatch = line.match(/pts:\s*(\d+)/);
89
- const ptsTimeMatch = line.match(/pts_time:\s*([\d.]+)/);
90
- if (nMatch && ptsTimeMatch) {
91
- sceneChanges.push({
92
- frameNumber: parseInt(nMatch[1]),
93
- pts: ptsMatch ? parseInt(ptsMatch[1]) : 0,
94
- ptsTime: parseFloat(ptsTimeMatch[1]),
95
- });
96
- }
97
- }
98
- resolve(sceneChanges);
99
- });
100
- ffmpeg.on('error', reject);
101
- });
102
-
103
- export const getVideoInfo = (videoPath: string): Promise<VideoInfo> =>
104
- new Promise((resolvePromise, reject) => {
105
- if (!ffmpegPath) {
106
- reject(new Error('ffmpeg path not found'));
107
- return;
108
- }
109
- const ffmpeg = spawn(ffmpegPath, ['-i', videoPath, '-hide_banner']);
110
- let stderr = '';
111
- ffmpeg.stderr.on('data', (data: Buffer) => { stderr += data.toString(); });
112
- ffmpeg.on('close', () => {
113
- const dimMatch = stderr.match(/Stream.*Video:.*?(\d{2,5})x(\d{2,5})/);
114
- if (!dimMatch) {
115
- reject(new Error(`Could not determine video dimensions for: ${videoPath}`));
116
- return;
117
- }
118
- const durMatch = stderr.match(/Duration:\s*(\d+):(\d+):([\d.]+)/);
119
- const duration = durMatch
120
- ? parseInt(durMatch[1]) * 3600 + parseInt(durMatch[2]) * 60 + parseFloat(durMatch[3])
121
- : 0;
122
- resolvePromise({
123
- width: parseInt(dimMatch[1]),
124
- height: parseInt(dimMatch[2]),
125
- duration,
126
- });
127
- });
128
- });
129
-
130
- const isOrientationMismatch = (sw: number, sh: number, tw: number, th: number): boolean =>
131
- (sw > sh && tw < th) || (sw < sh && tw > th);
132
-
133
- export const buildVideoFilter = (
134
- sourceWidth: number,
135
- sourceHeight: number,
136
- targetWidth: number,
137
- targetHeight: number,
138
- ): string => {
139
- if (!isOrientationMismatch(sourceWidth, sourceHeight, targetWidth, targetHeight)) {
140
- return `scale=${targetWidth}:${targetHeight}`;
141
- }
142
-
143
- const targetAspect = targetWidth / targetHeight;
144
- const makeEven = (n: number) => Math.floor(n / 2) * 2;
145
- let cropW: number, cropH: number, cropX: number, cropY: number;
146
-
147
- if (sourceWidth / sourceHeight > targetAspect) {
148
- cropW = makeEven(Math.round(sourceHeight * targetAspect));
149
- cropH = makeEven(sourceHeight);
150
- cropX = Math.floor((sourceWidth - cropW) / 2);
151
- cropY = Math.floor((sourceHeight - cropH) / 2);
152
- } else {
153
- cropW = makeEven(sourceWidth);
154
- cropH = makeEven(Math.round(sourceWidth / targetAspect));
155
- cropX = Math.floor((sourceWidth - cropW) / 2);
156
- cropY = Math.floor((sourceHeight - cropH) / 2);
157
- }
158
-
159
- return `crop=${cropW}:${cropH}:${cropX}:${cropY},scale=${targetWidth}:${targetHeight}`;
160
- };
161
-
162
- export const spawnVideoFrameReader = (config: {
163
- videoPath: string;
164
- fps: number;
165
- totalFrames: number;
166
- width?: number;
167
- height?: number;
168
- sourceWidth?: number;
169
- sourceHeight?: number;
170
- }) => {
171
- if (!ffmpegPath) {
172
- throw new Error('ffmpeg path not found');
173
- }
174
- const args = [
175
- '-stream_loop', '-1',
176
- '-i', config.videoPath,
177
- '-r', `${config.fps}`,
178
- '-frames:v', `${config.totalFrames}`,
179
- ];
180
- if (config.width && config.height) {
181
- const filter = config.sourceWidth && config.sourceHeight
182
- ? buildVideoFilter(config.sourceWidth, config.sourceHeight, config.width, config.height)
183
- : `scale=${config.width}:${config.height}`;
184
- args.push('-vf', filter);
185
- }
186
- args.push(
187
- '-f', 'rawvideo',
188
- '-pix_fmt', 'bgr24',
189
- '-v', 'quiet',
190
- 'pipe:1'
191
- );
192
- return spawn(ffmpegPath, args);
193
- };
194
-
195
- export const readVideoFrame = (stream: Readable, frameSize: number): Promise<Buffer | null> =>
196
- new Promise((resolve) => {
197
- const tryRead = () => {
198
- const data = stream.read(frameSize) as Buffer | null;
199
- if (data !== null) {
200
- resolve(data.length === frameSize ? data : null);
201
- return;
202
- }
203
- const onReadable = () => {
204
- cleanup();
205
- tryRead();
206
- };
207
- const onEnd = () => {
208
- cleanup();
209
- resolve(null);
210
- };
211
- const cleanup = () => {
212
- stream.removeListener('readable', onReadable);
213
- stream.removeListener('end', onEnd);
214
- };
215
- stream.once('readable', onReadable);
216
- stream.once('end', onEnd);
217
- };
218
- tryRead();
219
- });
220
-
221
- export const getProgress = (onProgress: (currentFrame: number) => any) =>
222
- (stderrOutput: Buffer) => {
223
- const matchResult = stderrOutput.toString().match(/frame=[ ]+(\d+)/);
224
- if (!matchResult) {
225
- return;
226
- }
227
- const currentFrame = +matchResult[1];
228
- if (isNaN(currentFrame)) {
229
- return;
230
- }
231
- onProgress(currentFrame);
232
- };
233
-
234
- export const calculateProgress = (framesCount: number, callback: (progress: number) => any) =>
235
- (currentFrame: number) =>
236
- callback(
237
- +(currentFrame / framesCount * 100).toFixed(2)
238
- );
239
-
240
- export const waitDrain = (stream: Writable) =>
241
- new Promise<void>(resolve => stream.once('drain', resolve));
242
-
243
- export interface VideoSegment {
244
- outputStartFrame: number;
245
- videoSeekSeconds: number;
246
- frameCount: number;
247
- }
248
-
249
- const mergeSmallScenes = (sceneChanges: SceneChange[], videoDuration: number, minDuration = 2): SceneChange[] => {
250
- if (sceneChanges.length === 0) return [];
251
- const merged: SceneChange[] = [sceneChanges[0]];
252
- for (let i = 1; i < sceneChanges.length; i++) {
253
- const lastKept = merged[merged.length - 1];
254
- const gap = sceneChanges[i].ptsTime - lastKept.ptsTime;
255
- if (gap >= minDuration) {
256
- merged.push(sceneChanges[i]);
257
- }
258
- }
259
- const lastScene = merged[merged.length - 1];
260
- if (videoDuration - lastScene.ptsTime < minDuration && merged.length > 1) {
261
- merged.pop();
262
- }
263
- return merged;
264
- };
265
-
266
- export const buildBeatSyncedSegments = (
267
- beatFrameIndices: number[],
268
- totalFrames: number,
269
- sceneChanges: SceneChange[],
270
- videoDuration: number,
271
- ): VideoSegment[] => {
272
- if (sceneChanges.length === 0) {
273
- return [
274
- {
275
- outputStartFrame: 0,
276
- videoSeekSeconds: 0,
277
- frameCount: totalFrames,
278
- },
279
- ];
280
- }
281
-
282
- const consolidated = mergeSmallScenes(sceneChanges, videoDuration);
283
- let seekPositions: number[];
284
- if (consolidated.length >= 2) {
285
- seekPositions = consolidated.map(sc => sc.ptsTime);
286
- } else {
287
- const count = Math.max(10, Math.ceil(videoDuration / 3));
288
- seekPositions = Array.from({ length: count }, (_, i) => (i * videoDuration) / count);
289
- }
290
-
291
- const boundaries = [0, ...beatFrameIndices];
292
- if (boundaries[boundaries.length - 1] !== totalFrames) {
293
- boundaries.push(totalFrames);
294
- }
295
- const unique = Array.from(new Set(boundaries)).sort((a, b) => a - b);
296
-
297
- const segments: VideoSegment[] = [];
298
- for (let i = 0; i < unique.length - 1; i++) {
299
- segments.push({
300
- outputStartFrame: unique[i],
301
- videoSeekSeconds: seekPositions[i % seekPositions.length],
302
- frameCount: unique[i + 1] - unique[i],
303
- });
304
- }
305
- return segments;
306
- };
307
-
308
- export const writeConcatFile = (
309
- segments: VideoSegment[],
310
- videoPath: string,
311
- videoDuration: number,
312
- fps: number,
313
- ): string => {
314
- const absVideoPath = resolvePath(videoPath).replace(/\\/g, '/');
315
- const escaped = absVideoPath.replace(/'/g, "'\\''");
316
- let content = '';
317
-
318
- for (const seg of segments) {
319
- const segDuration = seg.frameCount / fps;
320
- let remaining = segDuration;
321
- let pos = seg.videoSeekSeconds % videoDuration;
322
-
323
- while (remaining > 0.001) {
324
- const available = videoDuration - pos;
325
- const take = Math.min(remaining, available);
326
- content += `file '${escaped}'\n`;
327
- content += `inpoint ${pos.toFixed(6)}\n`;
328
- content += `outpoint ${(pos + take).toFixed(6)}\n\n`;
329
- remaining -= take;
330
- pos = 0;
331
- }
332
- }
333
-
334
- const concatPath = joinPath(tmpdir(), `av-concat-${Date.now()}.txt`);
335
- writeFileSync(concatPath, content, 'utf-8');
336
- return concatPath;
337
- };
338
-
339
- export const spawnConcatVideoFrameReader = (config: {
340
- concatFilePath: string;
341
- fps: number;
342
- totalFrames: number;
343
- width?: number;
344
- height?: number;
345
- sourceWidth?: number;
346
- sourceHeight?: number;
347
- }) => {
348
- if (!ffmpegPath) {
349
- throw new Error('ffmpeg path not found');
350
- }
351
- const args = [
352
- '-f', 'concat',
353
- '-safe', '0',
354
- '-i', config.concatFilePath,
355
- '-r', `${config.fps}`,
356
- '-frames:v', `${config.totalFrames}`,
357
- ];
358
- if (config.width && config.height) {
359
- const filter = config.sourceWidth && config.sourceHeight
360
- ? buildVideoFilter(config.sourceWidth, config.sourceHeight, config.width, config.height)
361
- : `scale=${config.width}:${config.height}`;
362
- args.push('-vf', filter);
363
- }
364
- args.push(
365
- '-f', 'rawvideo',
366
- '-pix_fmt', 'bgr24',
367
- '-v', 'quiet',
368
- 'pipe:1'
369
- );
370
- return spawn(ffmpegPath, args);
371
- };
372
-
373
- export const cleanupConcatFile = (filePath: string) => {
374
- try { unlinkSync(filePath); } catch {}
375
- };
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
+ videoFileName: string;
16
+ fps: number;
17
+ crf?: string;
18
+ preset?: string;
19
+ onStderr?: (data: any) => any;
20
+ /** When set with `audioDurationSeconds`, passed to ffmpeg before `-i` for muxed highlight. */
21
+ audioSeekSeconds?: number;
22
+ audioDurationSeconds?: number;
23
+ /** One contiguous trim of the same audio file (muxed highlight). */
24
+ audioSegment?: AudioMuxSegment;
25
+ }
26
+
27
+ export const spawnFfmpegVideoWriter = (config: FfmpegVideoWriterConfig) => {
28
+ if (!ffmpegPath) {
29
+ throw new Error('ffmpeg path not found');
30
+ }
31
+ const crf = config.crf || '23';
32
+ const preset = config.preset || 'medium';
33
+ const args: string[] = ['-y'];
34
+ const seek =
35
+ config.audioSegment?.seekSeconds ?? config.audioSeekSeconds;
36
+ const duration =
37
+ config.audioSegment?.durationSeconds ?? config.audioDurationSeconds;
38
+ if (seek !== undefined && duration !== undefined) {
39
+ args.push('-ss', String(seek), '-t', String(duration));
40
+ }
41
+ args.push(
42
+ '-i', config.audioFilename,
43
+ '-crf', crf,
44
+ '-c:a', 'aac', '-b:a', '384k', '-profile:a', 'aac_low',
45
+ '-c:v', 'libx264', '-r', `${config.fps}`, '-pix_fmt', 'yuv420p', '-preset', preset, config.videoFileName,
46
+ '-r', `${config.fps}`,
47
+ '-i', '-'
48
+ );
49
+ const ffmpeg = spawn(ffmpegPath, args);
50
+ if (config.onStderr) {
51
+ ffmpeg.stderr.on('data', config.onStderr);
52
+ }
53
+ return ffmpeg;
54
+ };
55
+
56
+ export interface VideoInfo {
57
+ width: number;
58
+ height: number;
59
+ duration: number;
60
+ }
61
+
62
+ export interface SceneChange {
63
+ frameNumber: number;
64
+ pts: number;
65
+ ptsTime: number;
66
+ }
67
+
68
+ export const detectSceneChanges = (videoPath: string, threshold = 0.4): Promise<SceneChange[]> =>
69
+ new Promise((resolve, reject) => {
70
+ if (!ffmpegPath) {
71
+ reject(new Error('ffmpeg path not found'));
72
+ return;
73
+ }
74
+ const ffmpeg = spawn(ffmpegPath, [
75
+ '-i', videoPath,
76
+ '-filter:v', `select='gt(scene,${threshold})',showinfo`,
77
+ '-f', 'null',
78
+ '-'
79
+ ]);
80
+ let stderr = '';
81
+ ffmpeg.stderr.on('data', (data: Buffer) => { stderr += data.toString(); });
82
+ ffmpeg.on('close', () => {
83
+ const sceneChanges: SceneChange[] = [];
84
+ for (const line of stderr.split('\n')) {
85
+ if (!line.includes('Parsed_showinfo')) continue;
86
+ const nMatch = line.match(/n:\s*(\d+)/);
87
+ const ptsMatch = line.match(/pts:\s*(\d+)/);
88
+ const ptsTimeMatch = line.match(/pts_time:\s*([\d.]+)/);
89
+ if (nMatch && ptsTimeMatch) {
90
+ sceneChanges.push({
91
+ frameNumber: parseInt(nMatch[1]),
92
+ pts: ptsMatch ? parseInt(ptsMatch[1]) : 0,
93
+ ptsTime: parseFloat(ptsTimeMatch[1]),
94
+ });
95
+ }
96
+ }
97
+ resolve(sceneChanges);
98
+ });
99
+ ffmpeg.on('error', reject);
100
+ });
101
+
102
+ export const getVideoInfo = (videoPath: string): Promise<VideoInfo> =>
103
+ new Promise((resolvePromise, reject) => {
104
+ if (!ffmpegPath) {
105
+ reject(new Error('ffmpeg path not found'));
106
+ return;
107
+ }
108
+ const ffmpeg = spawn(ffmpegPath, ['-i', videoPath, '-hide_banner']);
109
+ let stderr = '';
110
+ ffmpeg.stderr.on('data', (data: Buffer) => { stderr += data.toString(); });
111
+ ffmpeg.on('close', () => {
112
+ const dimMatch = stderr.match(/Stream.*Video:.*?(\d{2,5})x(\d{2,5})/);
113
+ if (!dimMatch) {
114
+ reject(new Error(`Could not determine video dimensions for: ${videoPath}`));
115
+ return;
116
+ }
117
+ const durMatch = stderr.match(/Duration:\s*(\d+):(\d+):([\d.]+)/);
118
+ const duration = durMatch
119
+ ? parseInt(durMatch[1]) * 3600 + parseInt(durMatch[2]) * 60 + parseFloat(durMatch[3])
120
+ : 0;
121
+ resolvePromise({
122
+ width: parseInt(dimMatch[1]),
123
+ height: parseInt(dimMatch[2]),
124
+ duration,
125
+ });
126
+ });
127
+ });
128
+
129
+ const isOrientationMismatch = (sw: number, sh: number, tw: number, th: number): boolean =>
130
+ (sw > sh && tw < th) || (sw < sh && tw > th);
131
+
132
+ export const buildVideoFilter = (
133
+ sourceWidth: number,
134
+ sourceHeight: number,
135
+ targetWidth: number,
136
+ targetHeight: number,
137
+ ): string => {
138
+ if (!isOrientationMismatch(sourceWidth, sourceHeight, targetWidth, targetHeight)) {
139
+ return `scale=${targetWidth}:${targetHeight}`;
140
+ }
141
+
142
+ const targetAspect = targetWidth / targetHeight;
143
+ const makeEven = (n: number) => Math.floor(n / 2) * 2;
144
+ let cropW: number, cropH: number, cropX: number, cropY: number;
145
+
146
+ if (sourceWidth / sourceHeight > targetAspect) {
147
+ cropW = makeEven(Math.round(sourceHeight * targetAspect));
148
+ cropH = makeEven(sourceHeight);
149
+ cropX = Math.floor((sourceWidth - cropW) / 2);
150
+ cropY = Math.floor((sourceHeight - cropH) / 2);
151
+ } else {
152
+ cropW = makeEven(sourceWidth);
153
+ cropH = makeEven(Math.round(sourceWidth / targetAspect));
154
+ cropX = Math.floor((sourceWidth - cropW) / 2);
155
+ cropY = Math.floor((sourceHeight - cropH) / 2);
156
+ }
157
+
158
+ return `crop=${cropW}:${cropH}:${cropX}:${cropY},scale=${targetWidth}:${targetHeight}`;
159
+ };
160
+
161
+ export const spawnVideoFrameReader = (config: {
162
+ videoPath: string;
163
+ fps: number;
164
+ totalFrames: number;
165
+ width?: number;
166
+ height?: number;
167
+ sourceWidth?: number;
168
+ sourceHeight?: number;
169
+ }) => {
170
+ if (!ffmpegPath) {
171
+ throw new Error('ffmpeg path not found');
172
+ }
173
+ const args = [
174
+ '-stream_loop', '-1',
175
+ '-i', config.videoPath,
176
+ '-r', `${config.fps}`,
177
+ '-frames:v', `${config.totalFrames}`,
178
+ ];
179
+ if (config.width && config.height) {
180
+ const filter = config.sourceWidth && config.sourceHeight
181
+ ? buildVideoFilter(config.sourceWidth, config.sourceHeight, config.width, config.height)
182
+ : `scale=${config.width}:${config.height}`;
183
+ args.push('-vf', filter);
184
+ }
185
+ args.push(
186
+ '-f', 'rawvideo',
187
+ '-pix_fmt', 'bgr24',
188
+ '-v', 'quiet',
189
+ 'pipe:1'
190
+ );
191
+ return spawn(ffmpegPath, args);
192
+ };
193
+
194
+ export const readVideoFrame = (stream: Readable, frameSize: number): Promise<Buffer | null> =>
195
+ new Promise((resolve) => {
196
+ const tryRead = () => {
197
+ const data = stream.read(frameSize) as Buffer | null;
198
+ if (data !== null) {
199
+ resolve(data.length === frameSize ? data : null);
200
+ return;
201
+ }
202
+ const onReadable = () => {
203
+ cleanup();
204
+ tryRead();
205
+ };
206
+ const onEnd = () => {
207
+ cleanup();
208
+ resolve(null);
209
+ };
210
+ const cleanup = () => {
211
+ stream.removeListener('readable', onReadable);
212
+ stream.removeListener('end', onEnd);
213
+ };
214
+ stream.once('readable', onReadable);
215
+ stream.once('end', onEnd);
216
+ };
217
+ tryRead();
218
+ });
219
+
220
+ export const getProgress = (onProgress: (currentFrame: number) => any) =>
221
+ (stderrOutput: Buffer) => {
222
+ const matchResult = stderrOutput.toString().match(/frame=[ ]+(\d+)/);
223
+ if (!matchResult) {
224
+ return;
225
+ }
226
+ const currentFrame = +matchResult[1];
227
+ if (isNaN(currentFrame)) {
228
+ return;
229
+ }
230
+ onProgress(currentFrame);
231
+ };
232
+
233
+ export const calculateProgress = (framesCount: number, callback: (progress: number) => any) =>
234
+ (currentFrame: number) =>
235
+ callback(
236
+ +(currentFrame / framesCount * 100).toFixed(2)
237
+ );
238
+
239
+ export const waitDrain = (
240
+ stream: Writable,
241
+ processStream?: {
242
+ once: (eventName: string, listener: (...args: any[]) => void) => any;
243
+ removeListener: (eventName: string, listener: (...args: any[]) => void) => any;
244
+ },
245
+ ) =>
246
+ new Promise<boolean>(resolve => {
247
+ const cleanup = () => {
248
+ stream.removeListener('drain', onDrain);
249
+ stream.removeListener('error', onErrorOrClose);
250
+ stream.removeListener('close', onErrorOrClose);
251
+ processStream?.removeListener('error', onErrorOrClose);
252
+ processStream?.removeListener('exit', onErrorOrClose);
253
+ processStream?.removeListener('close', onErrorOrClose);
254
+ };
255
+ const onDrain = () => {
256
+ cleanup();
257
+ resolve(true);
258
+ };
259
+ const onErrorOrClose = () => {
260
+ cleanup();
261
+ resolve(false);
262
+ };
263
+ stream.once('drain', onDrain);
264
+ stream.once('error', onErrorOrClose);
265
+ stream.once('close', onErrorOrClose);
266
+ processStream?.once('error', onErrorOrClose);
267
+ processStream?.once('exit', onErrorOrClose);
268
+ processStream?.once('close', onErrorOrClose);
269
+ });
270
+
271
+ export interface VideoSegment {
272
+ outputStartFrame: number;
273
+ videoSeekSeconds: number;
274
+ frameCount: number;
275
+ }
276
+
277
+ const mergeSmallScenes = (sceneChanges: SceneChange[], videoDuration: number, minDuration = 2): SceneChange[] => {
278
+ if (sceneChanges.length === 0) return [];
279
+ const merged: SceneChange[] = [sceneChanges[0]];
280
+ for (let i = 1; i < sceneChanges.length; i++) {
281
+ const lastKept = merged[merged.length - 1];
282
+ const gap = sceneChanges[i].ptsTime - lastKept.ptsTime;
283
+ if (gap >= minDuration) {
284
+ merged.push(sceneChanges[i]);
285
+ }
286
+ }
287
+ const lastScene = merged[merged.length - 1];
288
+ if (videoDuration - lastScene.ptsTime < minDuration && merged.length > 1) {
289
+ merged.pop();
290
+ }
291
+ return merged;
292
+ };
293
+
294
+ export const buildBeatSyncedSegments = (
295
+ beatFrameIndices: number[],
296
+ totalFrames: number,
297
+ sceneChanges: SceneChange[],
298
+ videoDuration: number,
299
+ ): VideoSegment[] => {
300
+ if (sceneChanges.length === 0) {
301
+ return [
302
+ {
303
+ outputStartFrame: 0,
304
+ videoSeekSeconds: 0,
305
+ frameCount: totalFrames,
306
+ },
307
+ ];
308
+ }
309
+
310
+ const consolidated = mergeSmallScenes(sceneChanges, videoDuration);
311
+ let seekPositions: number[];
312
+ if (consolidated.length >= 2) {
313
+ seekPositions = consolidated.map(sc => sc.ptsTime);
314
+ } else {
315
+ const count = Math.max(10, Math.ceil(videoDuration / 3));
316
+ seekPositions = Array.from({ length: count }, (_, i) => (i * videoDuration) / count);
317
+ }
318
+
319
+ const boundaries = [0, ...beatFrameIndices];
320
+ if (boundaries[boundaries.length - 1] !== totalFrames) {
321
+ boundaries.push(totalFrames);
322
+ }
323
+ const unique = Array.from(new Set(boundaries)).sort((a, b) => a - b);
324
+
325
+ const segments: VideoSegment[] = [];
326
+ for (let i = 0; i < unique.length - 1; i++) {
327
+ segments.push({
328
+ outputStartFrame: unique[i],
329
+ videoSeekSeconds: seekPositions[i % seekPositions.length],
330
+ frameCount: unique[i + 1] - unique[i],
331
+ });
332
+ }
333
+ return segments;
334
+ };
335
+
336
+ export const writeConcatFile = (
337
+ segments: VideoSegment[],
338
+ videoPath: string,
339
+ videoDuration: number,
340
+ fps: number,
341
+ ): string => {
342
+ const absVideoPath = resolvePath(videoPath).replace(/\\/g, '/');
343
+ const escaped = absVideoPath.replace(/'/g, "'\\''");
344
+ let content = '';
345
+
346
+ for (const seg of segments) {
347
+ const segDuration = seg.frameCount / fps;
348
+ let remaining = segDuration;
349
+ let pos = seg.videoSeekSeconds % videoDuration;
350
+
351
+ while (remaining > 0.001) {
352
+ const available = videoDuration - pos;
353
+ const take = Math.min(remaining, available);
354
+ content += `file '${escaped}'\n`;
355
+ content += `inpoint ${pos.toFixed(6)}\n`;
356
+ content += `outpoint ${(pos + take).toFixed(6)}\n\n`;
357
+ remaining -= take;
358
+ pos = 0;
359
+ }
360
+ }
361
+
362
+ const concatPath = joinPath(tmpdir(), `av-concat-${Date.now()}.txt`);
363
+ writeFileSync(concatPath, content, 'utf-8');
364
+ return concatPath;
365
+ };
366
+
367
+ export const spawnConcatVideoFrameReader = (config: {
368
+ concatFilePath: string;
369
+ fps: number;
370
+ totalFrames: number;
371
+ width?: number;
372
+ height?: number;
373
+ sourceWidth?: number;
374
+ sourceHeight?: number;
375
+ }) => {
376
+ if (!ffmpegPath) {
377
+ throw new Error('ffmpeg path not found');
378
+ }
379
+ const args = [
380
+ '-f', 'concat',
381
+ '-safe', '0',
382
+ '-i', config.concatFilePath,
383
+ '-r', `${config.fps}`,
384
+ '-frames:v', `${config.totalFrames}`,
385
+ ];
386
+ if (config.width && config.height) {
387
+ const filter = config.sourceWidth && config.sourceHeight
388
+ ? buildVideoFilter(config.sourceWidth, config.sourceHeight, config.width, config.height)
389
+ : `scale=${config.width}:${config.height}`;
390
+ args.push('-vf', filter);
391
+ }
392
+ args.push(
393
+ '-f', 'rawvideo',
394
+ '-pix_fmt', 'bgr24',
395
+ '-v', 'quiet',
396
+ 'pipe:1'
397
+ );
398
+ return spawn(ffmpegPath, args);
399
+ };
400
+
401
+ export const cleanupConcatFile = (filePath: string) => {
402
+ try { unlinkSync(filePath); } catch {}
403
+ };