@happyvertical/video 0.80.0 → 0.80.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1176 +1,1114 @@
1
- import { execFile as execFile$1 } from "node:child_process";
1
+ import { execFile } from "node:child_process";
2
2
  import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
- import { writeFile, readFile } from "node:fs/promises";
3
+ import { readFile, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
- import { join, basename, extname } from "node:path";
5
+ import { basename, extname, join } from "node:path";
6
6
  import { promisify } from "node:util";
7
7
  import { createLogger } from "@happyvertical/logger";
8
8
  import { ValidationError } from "@happyvertical/utils";
9
9
  import sharp from "sharp";
10
10
  import { getImageMetadata } from "@happyvertical/images";
11
- const execFileAsync = promisify(execFile$1);
12
- class FFmpegProcessor {
13
- options;
14
- logger;
15
- constructor(options = {}) {
16
- this.options = {
17
- ffmpegPath: options.ffmpegPath ?? "ffmpeg",
18
- ffprobePath: options.ffprobePath ?? "ffprobe",
19
- tempDir: options.tempDir ?? tmpdir(),
20
- timeout: options.timeout ?? 3e5
21
- };
22
- this.logger = createLogger({ level: "info" });
23
- }
24
- /**
25
- * Create a temporary directory for processing
26
- */
27
- createTempDir() {
28
- return mkdtempSync(join(this.options.tempDir, "video-"));
29
- }
30
- /**
31
- * Save buffer to a temporary file
32
- */
33
- async saveToTemp(buffer, ext, tempDir) {
34
- const filename = `${crypto.randomUUID()}.${ext}`;
35
- const filepath = join(tempDir, filename);
36
- await writeFile(filepath, buffer);
37
- return filepath;
38
- }
39
- /**
40
- * Get input path (save buffer to temp if needed)
41
- */
42
- async getInputPath(input, ext, tempDir) {
43
- if (Buffer.isBuffer(input)) {
44
- return this.saveToTemp(input, ext, tempDir);
45
- }
46
- return input;
47
- }
48
- /**
49
- * Run FFmpeg command
50
- * Uses execFile with array arguments to prevent command injection
51
- */
52
- async runFFmpeg(args, timeout) {
53
- this.logger.debug("Running FFmpeg", {
54
- path: this.options.ffmpegPath,
55
- args
56
- });
57
- await execFileAsync(this.options.ffmpegPath, args, {
58
- timeout: timeout ?? this.options.timeout,
59
- maxBuffer: 100 * 1024 * 1024
60
- // 100MB buffer
61
- });
62
- }
63
- /**
64
- * Run FFprobe command and parse JSON output
65
- * Uses execFile with array arguments to prevent command injection
66
- */
67
- async runFFprobe(input) {
68
- const args = [
69
- "-v",
70
- "quiet",
71
- "-print_format",
72
- "json",
73
- "-show_format",
74
- "-show_streams",
75
- input
76
- ];
77
- const { stdout } = await execFileAsync(this.options.ffprobePath, args, {
78
- timeout: 3e4
79
- });
80
- return JSON.parse(stdout);
81
- }
82
- /**
83
- * Get video metadata
84
- */
85
- async getMetadata(video) {
86
- let tempDir = null;
87
- let inputPath;
88
- try {
89
- if (Buffer.isBuffer(video)) {
90
- tempDir = this.createTempDir();
91
- inputPath = await this.saveToTemp(video, "mp4", tempDir);
92
- } else {
93
- inputPath = video;
94
- }
95
- const probe = await this.runFFprobe(inputPath);
96
- const videoStream = probe.streams?.find(
97
- (s) => s.codec_type === "video"
98
- );
99
- const audioStream = probe.streams?.find(
100
- (s) => s.codec_type === "audio"
101
- );
102
- const format = probe.format;
103
- if (!videoStream) {
104
- throw new ValidationError("No video stream found in file");
105
- }
106
- const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
107
- const aspectGcd = gcd(videoStream.width, videoStream.height);
108
- const aspectRatio = `${videoStream.width / aspectGcd}:${videoStream.height / aspectGcd}`;
109
- let fps = 30;
110
- if (videoStream.r_frame_rate) {
111
- const [num, den] = videoStream.r_frame_rate.split("/").map(Number);
112
- fps = den ? num / den : num;
113
- }
114
- return {
115
- duration: parseFloat(format.duration) || 0,
116
- width: videoStream.width,
117
- height: videoStream.height,
118
- fps,
119
- codec: videoStream.codec_name,
120
- bitrate: parseInt(format.bit_rate, 10),
121
- aspectRatio,
122
- hasAudio: !!audioStream,
123
- audioCodec: audioStream?.codec_name,
124
- audioSampleRate: audioStream?.sample_rate ? parseInt(audioStream.sample_rate, 10) : void 0,
125
- fileSize: parseInt(format.size, 10),
126
- format: format.format_name.split(",")[0]
127
- };
128
- } finally {
129
- if (tempDir) {
130
- rmSync(tempDir, { recursive: true, force: true });
131
- }
132
- }
133
- }
134
- /**
135
- * Extract a single frame from video
136
- */
137
- async extractFrame(video, timestamp, options = {}) {
138
- const tempDir = this.createTempDir();
139
- try {
140
- const inputPath = await this.getInputPath(video, "mp4", tempDir);
141
- const format = options.format ?? "png";
142
- const outputPath = join(tempDir, `frame.${format}`);
143
- const args = [
144
- "-y",
145
- "-ss",
146
- timestamp.toFixed(3),
147
- "-i",
148
- inputPath,
149
- "-vframes",
150
- "1"
151
- ];
152
- if (options.width || options.height) {
153
- const w = options.width ?? -1;
154
- const h = options.height ?? -1;
155
- args.push("-vf", `scale=${w}:${h}`);
156
- }
157
- if (format === "jpg" || format === "webp") {
158
- const quality = options.quality ?? 90;
159
- args.push("-q:v", Math.round((100 - quality) / 100 * 31).toString());
160
- }
161
- args.push(outputPath);
162
- await this.runFFmpeg(args);
163
- return await readFile(outputPath);
164
- } finally {
165
- rmSync(tempDir, { recursive: true, force: true });
166
- }
167
- }
168
- /**
169
- * Transcode video to different format/codec
170
- */
171
- async transcode(video, options) {
172
- const tempDir = this.createTempDir();
173
- try {
174
- const inputPath = await this.getInputPath(video, "mp4", tempDir);
175
- const outputPath = join(tempDir, `output.${options.format}`);
176
- const args = ["-y", "-i", inputPath];
177
- if (options.startTime !== void 0) {
178
- args.push("-ss", options.startTime.toFixed(3));
179
- }
180
- if (options.endTime !== void 0) {
181
- args.push("-to", options.endTime.toFixed(3));
182
- }
183
- if (options.video) {
184
- args.push(...this.getVideoCodecArgs(options.video));
185
- }
186
- if (options.audio) {
187
- args.push("-c:a", options.audio.codec);
188
- if (options.audio.bitrate) args.push("-b:a", options.audio.bitrate);
189
- if (options.audio.sampleRate)
190
- args.push("-ar", options.audio.sampleRate.toString());
191
- if (options.audio.channels)
192
- args.push("-ac", options.audio.channels.toString());
193
- }
194
- if (options.width || options.height) {
195
- const w = options.width ?? -1;
196
- const h = options.height ?? -1;
197
- args.push("-vf", `scale=${w}:${h}`);
198
- }
199
- if (options.fps) {
200
- args.push("-r", options.fps.toString());
201
- }
202
- args.push(outputPath);
203
- await this.runFFmpeg(args);
204
- return await readFile(outputPath);
205
- } finally {
206
- rmSync(tempDir, { recursive: true, force: true });
207
- }
208
- }
209
- /**
210
- * Get FFmpeg args for video codec options
211
- */
212
- getVideoCodecArgs(options) {
213
- const args = [];
214
- const codecMap = {
215
- h264: "libx264",
216
- h265: "libx265",
217
- vp9: "libvpx-vp9",
218
- av1: "libaom-av1"
219
- };
220
- args.push("-c:v", codecMap[options.codec] ?? options.codec);
221
- if (options.preset) {
222
- args.push("-preset", options.preset);
223
- }
224
- if (options.crf !== void 0) {
225
- args.push("-crf", options.crf.toString());
226
- }
227
- if (options.bitrate) {
228
- args.push("-b:v", options.bitrate);
229
- }
230
- if (options.pixelFormat) {
231
- args.push("-pix_fmt", options.pixelFormat);
232
- } else {
233
- args.push("-pix_fmt", "yuv420p");
234
- }
235
- return args;
236
- }
237
- /**
238
- * Add an overlay to video
239
- */
240
- async addOverlay(video, overlay) {
241
- const tempDir = this.createTempDir();
242
- try {
243
- const inputPath = await this.getInputPath(video, "mp4", tempDir);
244
- const outputPath = join(tempDir, "output.mp4");
245
- let filterComplex = "";
246
- const inputs = ["-i", inputPath];
247
- if (overlay.type === "image") {
248
- const imagePath = await this.getInputPath(
249
- overlay.content,
250
- "png",
251
- tempDir
252
- );
253
- inputs.push("-i", imagePath);
254
- const pos = this.getOverlayPosition(overlay.position);
255
- filterComplex = `[1:v]${overlay.width ? `scale=${overlay.width}:-1,` : ""}format=rgba,colorchannelmixer=aa=${overlay.opacity ?? 1}[ovr];[0:v][ovr]overlay=${pos.x}:${pos.y}`;
256
- if (overlay.startTime !== void 0 || overlay.endTime !== void 0) {
257
- const enable = this.getEnableExpression(
258
- overlay.startTime,
259
- overlay.endTime
260
- );
261
- filterComplex += `:enable='${enable}'`;
262
- }
263
- } else if (overlay.type === "text") {
264
- const textOpts = overlay.textOptions ?? {};
265
- const pos = this.getOverlayPosition(overlay.position);
266
- filterComplex = `drawtext=text='${this.escapeFFmpegText(overlay.content)}'`;
267
- filterComplex += `:x=${pos.x}:y=${pos.y}`;
268
- filterComplex += `:fontsize=${textOpts.fontSize ?? 24}`;
269
- filterComplex += `:fontcolor=${textOpts.fontColor ?? "white"}`;
270
- if (textOpts.fontFamily) {
271
- filterComplex += `:fontfile=${textOpts.fontFamily}`;
272
- }
273
- if (textOpts.backgroundColor) {
274
- filterComplex += `:box=1:boxcolor=${textOpts.backgroundColor}:boxborderw=${textOpts.padding ?? 10}`;
275
- }
276
- if (overlay.startTime !== void 0 || overlay.endTime !== void 0) {
277
- const enable = this.getEnableExpression(
278
- overlay.startTime,
279
- overlay.endTime
280
- );
281
- filterComplex += `:enable='${enable}'`;
282
- }
283
- }
284
- const args = [
285
- "-y",
286
- ...inputs,
287
- "-filter_complex",
288
- filterComplex,
289
- "-c:a",
290
- "copy",
291
- outputPath
292
- ];
293
- await this.runFFmpeg(args);
294
- return await readFile(outputPath);
295
- } finally {
296
- rmSync(tempDir, { recursive: true, force: true });
297
- }
298
- }
299
- /**
300
- * Add a lower-third overlay
301
- */
302
- async addLowerThird(video, config) {
303
- const tempDir = this.createTempDir();
304
- try {
305
- const inputPath = await this.getInputPath(video, "mp4", tempDir);
306
- const outputPath = join(tempDir, "output.mp4");
307
- const metadata = await this.getMetadata(inputPath);
308
- const startTime = config.startTime ?? 0;
309
- const duration = config.duration ?? 5;
310
- const endTime = startTime + duration;
311
- const primaryColor = config.primaryColor ?? "0x1a1a1a";
312
- const titleY = metadata.height - 100;
313
- const subtitleY = metadata.height - 60;
314
- let filter = `drawtext=text='${this.escapeFFmpegText(config.title)}':x=50:y=${titleY}:fontsize=32:fontcolor=white:box=1:boxcolor=${primaryColor}@0.8:boxborderw=10:enable='between(t,${startTime},${endTime})'`;
315
- if (config.subtitle) {
316
- filter += `,drawtext=text='${this.escapeFFmpegText(config.subtitle)}':x=50:y=${subtitleY}:fontsize=20:fontcolor=white@0.9:enable='between(t,${startTime},${endTime})'`;
317
- }
318
- const args = [
319
- "-y",
320
- "-i",
321
- inputPath,
322
- "-vf",
323
- filter,
324
- "-c:a",
325
- "copy",
326
- outputPath
327
- ];
328
- await this.runFFmpeg(args);
329
- return await readFile(outputPath);
330
- } finally {
331
- rmSync(tempDir, { recursive: true, force: true });
332
- }
333
- }
334
- /**
335
- * Compose video with overlays and audio
336
- */
337
- async compose(options) {
338
- const tempDir = this.createTempDir();
339
- try {
340
- const inputPath = await this.getInputPath(
341
- options.baseVideo,
342
- "mp4",
343
- tempDir
344
- );
345
- let currentVideo = inputPath;
346
- if (options.overlays) {
347
- for (const overlay of options.overlays) {
348
- const result = await this.addOverlay(currentVideo, overlay);
349
- const tempOutput = join(
350
- tempDir,
351
- `overlay_${crypto.randomUUID()}.mp4`
352
- );
353
- await writeFile(tempOutput, result);
354
- currentVideo = tempOutput;
355
- }
356
- }
357
- if (options.audio) {
358
- const result = await this.mixAudio(currentVideo, options.audio);
359
- const tempOutput = join(tempDir, `audio_${crypto.randomUUID()}.mp4`);
360
- await writeFile(tempOutput, result);
361
- currentVideo = tempOutput;
362
- }
363
- const format = options.outputFormat ?? "mp4";
364
- const outputPath = join(tempDir, `output.${format}`);
365
- const args = ["-y", "-i", currentVideo];
366
- if (options.width || options.height) {
367
- const w = options.width ?? -1;
368
- const h = options.height ?? -1;
369
- args.push("-vf", `scale=${w}:${h}`);
370
- }
371
- if (options.fps) {
372
- args.push("-r", options.fps.toString());
373
- }
374
- const quality = options.quality ?? 23;
375
- args.push("-crf", quality.toString());
376
- args.push("-preset", "medium");
377
- args.push("-c:a", "aac", "-b:a", "128k");
378
- args.push(outputPath);
379
- await this.runFFmpeg(args);
380
- return await readFile(outputPath);
381
- } finally {
382
- rmSync(tempDir, { recursive: true, force: true });
383
- }
384
- }
385
- /**
386
- * Concatenate multiple videos
387
- */
388
- async concatenate(videos) {
389
- const tempDir = this.createTempDir();
390
- try {
391
- const videoPaths = [];
392
- for (let i = 0; i < videos.length; i++) {
393
- const path = await this.getInputPath(videos[i], "mp4", tempDir);
394
- videoPaths.push(path);
395
- }
396
- const listPath = join(tempDir, "concat.txt");
397
- const listContent = videoPaths.map((p) => `file '${p}'`).join("\n");
398
- writeFileSync(listPath, listContent);
399
- const outputPath = join(tempDir, "output.mp4");
400
- const args = [
401
- "-y",
402
- "-f",
403
- "concat",
404
- "-safe",
405
- "0",
406
- "-i",
407
- listPath,
408
- "-c",
409
- "copy",
410
- outputPath
411
- ];
412
- await this.runFFmpeg(args);
413
- return await readFile(outputPath);
414
- } finally {
415
- rmSync(tempDir, { recursive: true, force: true });
416
- }
417
- }
418
- /**
419
- * Mix audio into video
420
- */
421
- async mixAudio(video, audio, options = {}) {
422
- const tempDir = this.createTempDir();
423
- try {
424
- const videoPath = await this.getInputPath(video, "mp4", tempDir);
425
- const audioPath = await this.getInputPath(audio, "mp3", tempDir);
426
- const outputPath = join(tempDir, "output.mp4");
427
- const mode = options.mode ?? "replace";
428
- const args = ["-y", "-i", videoPath, "-i", audioPath];
429
- if (mode === "replace") {
430
- args.push("-map", "0:v", "-map", "1:a");
431
- if (options.newVolume !== void 0 && options.newVolume !== 1) {
432
- args.push("-af", `volume=${options.newVolume}`);
433
- }
434
- if (options.fadeIn || options.fadeOut) {
435
- const fadeFilters = [];
436
- if (options.fadeIn) {
437
- fadeFilters.push(`afade=t=in:d=${options.fadeIn}`);
438
- }
439
- if (options.fadeOut) {
440
- fadeFilters.push(`afade=t=out:d=${options.fadeOut}`);
441
- }
442
- args.push("-af", fadeFilters.join(","));
443
- }
444
- } else {
445
- const origVol = options.originalVolume ?? 0.5;
446
- const newVol = options.newVolume ?? 1;
447
- args.push(
448
- "-filter_complex",
449
- `[0:a]volume=${origVol}[a0];[1:a]volume=${newVol}[a1];[a0][a1]amix=inputs=2:duration=first[a]`,
450
- "-map",
451
- "0:v",
452
- "-map",
453
- "[a]"
454
- );
455
- }
456
- args.push("-c:v", "copy", "-shortest", outputPath);
457
- await this.runFFmpeg(args);
458
- return await readFile(outputPath);
459
- } finally {
460
- rmSync(tempDir, { recursive: true, force: true });
461
- }
462
- }
463
- /**
464
- * Convert animated WEBP to MP4
465
- *
466
- * Uses sharp to extract frames from animated WEBP (which ffmpeg can't decode
467
- * natively), then assembles them into an MP4 using ffmpeg.
468
- */
469
- async convertWebpToMp4(webp, options = {}) {
470
- const fps = options.fps ?? 16;
471
- const tempDir = this.createTempDir();
472
- try {
473
- const metadata = await sharp(webp, {
474
- animated: true,
475
- pages: -1
476
- }).metadata();
477
- const pageHeight = metadata.pageHeight ?? metadata.height ?? 480;
478
- const frameCount = metadata.pages ?? 1;
479
- this.logger.debug("Extracting WEBP frames", {
480
- frameCount,
481
- width: metadata.width,
482
- pageHeight
483
- });
484
- for (let i = 0; i < frameCount; i++) {
485
- const frame = await sharp(webp, { page: i, pages: 1 }).png().toBuffer();
486
- const framePath = join(
487
- tempDir,
488
- `frame_${String(i + 1).padStart(4, "0")}.png`
489
- );
490
- await writeFile(framePath, frame);
491
- }
492
- const outputPath = join(tempDir, "output.mp4");
493
- const args = [
494
- "-y",
495
- "-framerate",
496
- fps.toString(),
497
- "-start_number",
498
- "1",
499
- "-i",
500
- join(tempDir, "frame_%04d.png")
501
- ];
502
- if (options.video) {
503
- args.push(...this.getVideoCodecArgs(options.video));
504
- } else {
505
- args.push("-c:v", "libx264", "-pix_fmt", "yuv420p");
506
- }
507
- args.push(outputPath);
508
- await this.runFFmpeg(args);
509
- return await readFile(outputPath);
510
- } finally {
511
- rmSync(tempDir, { recursive: true, force: true });
512
- }
513
- }
514
- /**
515
- * Get overlay position as FFmpeg expression
516
- */
517
- getOverlayPosition(position) {
518
- const padding = position.padding ?? 20;
519
- let x;
520
- let y;
521
- if (typeof position.x === "number") {
522
- x = position.x.toString();
523
- } else {
524
- switch (position.x) {
525
- case "left":
526
- x = padding.toString();
527
- break;
528
- case "center":
529
- x = "(W-w)/2";
530
- break;
531
- case "right":
532
- x = `W-w-${padding}`;
533
- break;
534
- }
535
- }
536
- if (typeof position.y === "number") {
537
- y = position.y.toString();
538
- } else {
539
- switch (position.y) {
540
- case "top":
541
- y = padding.toString();
542
- break;
543
- case "center":
544
- y = "(H-h)/2";
545
- break;
546
- case "bottom":
547
- y = `H-h-${padding}`;
548
- break;
549
- }
550
- }
551
- return { x, y };
552
- }
553
- /**
554
- * Get FFmpeg enable expression for time-based visibility
555
- */
556
- getEnableExpression(startTime, endTime) {
557
- if (startTime !== void 0 && endTime !== void 0) {
558
- return `between(t,${startTime},${endTime})`;
559
- }
560
- if (startTime !== void 0) {
561
- return `gte(t,${startTime})`;
562
- }
563
- if (endTime !== void 0) {
564
- return `lte(t,${endTime})`;
565
- }
566
- return "1";
567
- }
568
- /**
569
- * Escape text for FFmpeg drawtext filter
570
- */
571
- escapeFFmpegText(text) {
572
- return text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/:/g, "\\:").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
573
- }
574
- }
575
- const execFile = promisify(execFile$1);
576
- const VIDEO_EXTENSIONS = /* @__PURE__ */ new Set([
577
- ".mp4",
578
- ".mov",
579
- ".m4v",
580
- ".avi",
581
- ".webm",
582
- ".insv",
583
- ".lrv"
11
+ //#region src/adapters/ffmpeg.ts
12
+ /**
13
+ * FFmpeg Video Processor Adapter
14
+ *
15
+ * Implements video processing using FFmpeg command-line tools.
16
+ */
17
+ var execFileAsync = promisify(execFile);
18
+ /**
19
+ * FFmpeg-based video processor
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * import { FFmpegProcessor } from '@happyvertical/video';
24
+ *
25
+ * const processor = new FFmpegProcessor();
26
+ *
27
+ * // Get video metadata
28
+ * const metadata = await processor.getMetadata('input.mp4');
29
+ * console.log(`Duration: ${metadata.duration}s`);
30
+ *
31
+ * // Extract thumbnail
32
+ * const thumbnail = await processor.extractFrame('input.mp4', 2.0, {
33
+ * format: 'jpg',
34
+ * width: 1280,
35
+ * });
36
+ *
37
+ * // Add lower-third overlay
38
+ * const output = await processor.addLowerThird('input.mp4', {
39
+ * title: 'John Smith',
40
+ * subtitle: 'News Anchor',
41
+ * style: 'news',
42
+ * duration: 5,
43
+ * });
44
+ * ```
45
+ */
46
+ var FFmpegProcessor = class {
47
+ options;
48
+ logger;
49
+ constructor(options = {}) {
50
+ this.options = {
51
+ ffmpegPath: options.ffmpegPath ?? "ffmpeg",
52
+ ffprobePath: options.ffprobePath ?? "ffprobe",
53
+ tempDir: options.tempDir ?? tmpdir(),
54
+ timeout: options.timeout ?? 3e5
55
+ };
56
+ this.logger = createLogger({ level: "info" });
57
+ }
58
+ /**
59
+ * Create a temporary directory for processing
60
+ */
61
+ createTempDir() {
62
+ return mkdtempSync(join(this.options.tempDir, "video-"));
63
+ }
64
+ /**
65
+ * Save buffer to a temporary file
66
+ */
67
+ async saveToTemp(buffer, ext, tempDir) {
68
+ const filepath = join(tempDir, `${crypto.randomUUID()}.${ext}`);
69
+ await writeFile(filepath, buffer);
70
+ return filepath;
71
+ }
72
+ /**
73
+ * Get input path (save buffer to temp if needed)
74
+ */
75
+ async getInputPath(input, ext, tempDir) {
76
+ if (Buffer.isBuffer(input)) return this.saveToTemp(input, ext, tempDir);
77
+ return input;
78
+ }
79
+ /**
80
+ * Run FFmpeg command
81
+ * Uses execFile with array arguments to prevent command injection
82
+ */
83
+ async runFFmpeg(args, timeout) {
84
+ this.logger.debug("Running FFmpeg", {
85
+ path: this.options.ffmpegPath,
86
+ args
87
+ });
88
+ await execFileAsync(this.options.ffmpegPath, args, {
89
+ timeout: timeout ?? this.options.timeout,
90
+ maxBuffer: 100 * 1024 * 1024
91
+ });
92
+ }
93
+ /**
94
+ * Run FFprobe command and parse JSON output
95
+ * Uses execFile with array arguments to prevent command injection
96
+ */
97
+ async runFFprobe(input) {
98
+ const args = [
99
+ "-v",
100
+ "quiet",
101
+ "-print_format",
102
+ "json",
103
+ "-show_format",
104
+ "-show_streams",
105
+ input
106
+ ];
107
+ const { stdout } = await execFileAsync(this.options.ffprobePath, args, { timeout: 3e4 });
108
+ return JSON.parse(stdout);
109
+ }
110
+ /**
111
+ * Get video metadata
112
+ */
113
+ async getMetadata(video) {
114
+ let tempDir = null;
115
+ let inputPath;
116
+ try {
117
+ if (Buffer.isBuffer(video)) {
118
+ tempDir = this.createTempDir();
119
+ inputPath = await this.saveToTemp(video, "mp4", tempDir);
120
+ } else inputPath = video;
121
+ const probe = await this.runFFprobe(inputPath);
122
+ const videoStream = probe.streams?.find((s) => s.codec_type === "video");
123
+ const audioStream = probe.streams?.find((s) => s.codec_type === "audio");
124
+ const format = probe.format;
125
+ if (!videoStream) throw new ValidationError("No video stream found in file");
126
+ const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
127
+ const aspectGcd = gcd(videoStream.width, videoStream.height);
128
+ const aspectRatio = `${videoStream.width / aspectGcd}:${videoStream.height / aspectGcd}`;
129
+ let fps = 30;
130
+ if (videoStream.r_frame_rate) {
131
+ const [num, den] = videoStream.r_frame_rate.split("/").map(Number);
132
+ fps = den ? num / den : num;
133
+ }
134
+ return {
135
+ duration: parseFloat(format.duration) || 0,
136
+ width: videoStream.width,
137
+ height: videoStream.height,
138
+ fps,
139
+ codec: videoStream.codec_name,
140
+ bitrate: parseInt(format.bit_rate, 10),
141
+ aspectRatio,
142
+ hasAudio: !!audioStream,
143
+ audioCodec: audioStream?.codec_name,
144
+ audioSampleRate: audioStream?.sample_rate ? parseInt(audioStream.sample_rate, 10) : void 0,
145
+ fileSize: parseInt(format.size, 10),
146
+ format: format.format_name.split(",")[0]
147
+ };
148
+ } finally {
149
+ if (tempDir) rmSync(tempDir, {
150
+ recursive: true,
151
+ force: true
152
+ });
153
+ }
154
+ }
155
+ /**
156
+ * Extract a single frame from video
157
+ */
158
+ async extractFrame(video, timestamp, options = {}) {
159
+ const tempDir = this.createTempDir();
160
+ try {
161
+ const inputPath = await this.getInputPath(video, "mp4", tempDir);
162
+ const format = options.format ?? "png";
163
+ const outputPath = join(tempDir, `frame.${format}`);
164
+ const args = [
165
+ "-y",
166
+ "-ss",
167
+ timestamp.toFixed(3),
168
+ "-i",
169
+ inputPath,
170
+ "-vframes",
171
+ "1"
172
+ ];
173
+ if (options.width || options.height) {
174
+ const w = options.width ?? -1;
175
+ const h = options.height ?? -1;
176
+ args.push("-vf", `scale=${w}:${h}`);
177
+ }
178
+ if (format === "jpg" || format === "webp") {
179
+ const quality = options.quality ?? 90;
180
+ args.push("-q:v", Math.round((100 - quality) / 100 * 31).toString());
181
+ }
182
+ args.push(outputPath);
183
+ await this.runFFmpeg(args);
184
+ return await readFile(outputPath);
185
+ } finally {
186
+ rmSync(tempDir, {
187
+ recursive: true,
188
+ force: true
189
+ });
190
+ }
191
+ }
192
+ /**
193
+ * Transcode video to different format/codec
194
+ */
195
+ async transcode(video, options) {
196
+ const tempDir = this.createTempDir();
197
+ try {
198
+ const inputPath = await this.getInputPath(video, "mp4", tempDir);
199
+ const outputPath = join(tempDir, `output.${options.format}`);
200
+ const args = [
201
+ "-y",
202
+ "-i",
203
+ inputPath
204
+ ];
205
+ if (options.startTime !== void 0) args.push("-ss", options.startTime.toFixed(3));
206
+ if (options.endTime !== void 0) args.push("-to", options.endTime.toFixed(3));
207
+ if (options.video) args.push(...this.getVideoCodecArgs(options.video));
208
+ if (options.audio) {
209
+ args.push("-c:a", options.audio.codec);
210
+ if (options.audio.bitrate) args.push("-b:a", options.audio.bitrate);
211
+ if (options.audio.sampleRate) args.push("-ar", options.audio.sampleRate.toString());
212
+ if (options.audio.channels) args.push("-ac", options.audio.channels.toString());
213
+ }
214
+ if (options.width || options.height) {
215
+ const w = options.width ?? -1;
216
+ const h = options.height ?? -1;
217
+ args.push("-vf", `scale=${w}:${h}`);
218
+ }
219
+ if (options.fps) args.push("-r", options.fps.toString());
220
+ args.push(outputPath);
221
+ await this.runFFmpeg(args);
222
+ return await readFile(outputPath);
223
+ } finally {
224
+ rmSync(tempDir, {
225
+ recursive: true,
226
+ force: true
227
+ });
228
+ }
229
+ }
230
+ /**
231
+ * Get FFmpeg args for video codec options
232
+ */
233
+ getVideoCodecArgs(options) {
234
+ const args = [];
235
+ args.push("-c:v", {
236
+ h264: "libx264",
237
+ h265: "libx265",
238
+ vp9: "libvpx-vp9",
239
+ av1: "libaom-av1"
240
+ }[options.codec] ?? options.codec);
241
+ if (options.preset) args.push("-preset", options.preset);
242
+ if (options.crf !== void 0) args.push("-crf", options.crf.toString());
243
+ if (options.bitrate) args.push("-b:v", options.bitrate);
244
+ if (options.pixelFormat) args.push("-pix_fmt", options.pixelFormat);
245
+ else args.push("-pix_fmt", "yuv420p");
246
+ return args;
247
+ }
248
+ /**
249
+ * Add an overlay to video
250
+ */
251
+ async addOverlay(video, overlay) {
252
+ const tempDir = this.createTempDir();
253
+ try {
254
+ const inputPath = await this.getInputPath(video, "mp4", tempDir);
255
+ const outputPath = join(tempDir, "output.mp4");
256
+ let filterComplex = "";
257
+ const inputs = ["-i", inputPath];
258
+ if (overlay.type === "image") {
259
+ const imagePath = await this.getInputPath(overlay.content, "png", tempDir);
260
+ inputs.push("-i", imagePath);
261
+ const pos = this.getOverlayPosition(overlay.position);
262
+ filterComplex = `[1:v]${overlay.width ? `scale=${overlay.width}:-1,` : ""}format=rgba,colorchannelmixer=aa=${overlay.opacity ?? 1}[ovr];[0:v][ovr]overlay=${pos.x}:${pos.y}`;
263
+ if (overlay.startTime !== void 0 || overlay.endTime !== void 0) {
264
+ const enable = this.getEnableExpression(overlay.startTime, overlay.endTime);
265
+ filterComplex += `:enable='${enable}'`;
266
+ }
267
+ } else if (overlay.type === "text") {
268
+ const textOpts = overlay.textOptions ?? {};
269
+ const pos = this.getOverlayPosition(overlay.position);
270
+ filterComplex = `drawtext=text='${this.escapeFFmpegText(overlay.content)}'`;
271
+ filterComplex += `:x=${pos.x}:y=${pos.y}`;
272
+ filterComplex += `:fontsize=${textOpts.fontSize ?? 24}`;
273
+ filterComplex += `:fontcolor=${textOpts.fontColor ?? "white"}`;
274
+ if (textOpts.fontFamily) filterComplex += `:fontfile=${textOpts.fontFamily}`;
275
+ if (textOpts.backgroundColor) filterComplex += `:box=1:boxcolor=${textOpts.backgroundColor}:boxborderw=${textOpts.padding ?? 10}`;
276
+ if (overlay.startTime !== void 0 || overlay.endTime !== void 0) {
277
+ const enable = this.getEnableExpression(overlay.startTime, overlay.endTime);
278
+ filterComplex += `:enable='${enable}'`;
279
+ }
280
+ }
281
+ const args = [
282
+ "-y",
283
+ ...inputs,
284
+ "-filter_complex",
285
+ filterComplex,
286
+ "-c:a",
287
+ "copy",
288
+ outputPath
289
+ ];
290
+ await this.runFFmpeg(args);
291
+ return await readFile(outputPath);
292
+ } finally {
293
+ rmSync(tempDir, {
294
+ recursive: true,
295
+ force: true
296
+ });
297
+ }
298
+ }
299
+ /**
300
+ * Add a lower-third overlay
301
+ */
302
+ async addLowerThird(video, config) {
303
+ const tempDir = this.createTempDir();
304
+ try {
305
+ const inputPath = await this.getInputPath(video, "mp4", tempDir);
306
+ const outputPath = join(tempDir, "output.mp4");
307
+ const metadata = await this.getMetadata(inputPath);
308
+ const startTime = config.startTime ?? 0;
309
+ const endTime = startTime + (config.duration ?? 5);
310
+ const primaryColor = config.primaryColor ?? "0x1a1a1a";
311
+ const titleY = metadata.height - 100;
312
+ const subtitleY = metadata.height - 60;
313
+ let filter = `drawtext=text='${this.escapeFFmpegText(config.title)}':x=50:y=${titleY}:fontsize=32:fontcolor=white:box=1:boxcolor=${primaryColor}@0.8:boxborderw=10:enable='between(t,${startTime},${endTime})'`;
314
+ if (config.subtitle) filter += `,drawtext=text='${this.escapeFFmpegText(config.subtitle)}':x=50:y=${subtitleY}:fontsize=20:fontcolor=white@0.9:enable='between(t,${startTime},${endTime})'`;
315
+ const args = [
316
+ "-y",
317
+ "-i",
318
+ inputPath,
319
+ "-vf",
320
+ filter,
321
+ "-c:a",
322
+ "copy",
323
+ outputPath
324
+ ];
325
+ await this.runFFmpeg(args);
326
+ return await readFile(outputPath);
327
+ } finally {
328
+ rmSync(tempDir, {
329
+ recursive: true,
330
+ force: true
331
+ });
332
+ }
333
+ }
334
+ /**
335
+ * Compose video with overlays and audio
336
+ */
337
+ async compose(options) {
338
+ const tempDir = this.createTempDir();
339
+ try {
340
+ let currentVideo = await this.getInputPath(options.baseVideo, "mp4", tempDir);
341
+ if (options.overlays) for (const overlay of options.overlays) {
342
+ const result = await this.addOverlay(currentVideo, overlay);
343
+ const tempOutput = join(tempDir, `overlay_${crypto.randomUUID()}.mp4`);
344
+ await writeFile(tempOutput, result);
345
+ currentVideo = tempOutput;
346
+ }
347
+ if (options.audio) {
348
+ const result = await this.mixAudio(currentVideo, options.audio);
349
+ const tempOutput = join(tempDir, `audio_${crypto.randomUUID()}.mp4`);
350
+ await writeFile(tempOutput, result);
351
+ currentVideo = tempOutput;
352
+ }
353
+ const outputPath = join(tempDir, `output.${options.outputFormat ?? "mp4"}`);
354
+ const args = [
355
+ "-y",
356
+ "-i",
357
+ currentVideo
358
+ ];
359
+ if (options.width || options.height) {
360
+ const w = options.width ?? -1;
361
+ const h = options.height ?? -1;
362
+ args.push("-vf", `scale=${w}:${h}`);
363
+ }
364
+ if (options.fps) args.push("-r", options.fps.toString());
365
+ const quality = options.quality ?? 23;
366
+ args.push("-crf", quality.toString());
367
+ args.push("-preset", "medium");
368
+ args.push("-c:a", "aac", "-b:a", "128k");
369
+ args.push(outputPath);
370
+ await this.runFFmpeg(args);
371
+ return await readFile(outputPath);
372
+ } finally {
373
+ rmSync(tempDir, {
374
+ recursive: true,
375
+ force: true
376
+ });
377
+ }
378
+ }
379
+ /**
380
+ * Concatenate multiple videos
381
+ */
382
+ async concatenate(videos) {
383
+ const tempDir = this.createTempDir();
384
+ try {
385
+ const videoPaths = [];
386
+ for (let i = 0; i < videos.length; i++) {
387
+ const path = await this.getInputPath(videos[i], "mp4", tempDir);
388
+ videoPaths.push(path);
389
+ }
390
+ const listPath = join(tempDir, "concat.txt");
391
+ writeFileSync(listPath, videoPaths.map((p) => `file '${p}'`).join("\n"));
392
+ const outputPath = join(tempDir, "output.mp4");
393
+ const args = [
394
+ "-y",
395
+ "-f",
396
+ "concat",
397
+ "-safe",
398
+ "0",
399
+ "-i",
400
+ listPath,
401
+ "-c",
402
+ "copy",
403
+ outputPath
404
+ ];
405
+ await this.runFFmpeg(args);
406
+ return await readFile(outputPath);
407
+ } finally {
408
+ rmSync(tempDir, {
409
+ recursive: true,
410
+ force: true
411
+ });
412
+ }
413
+ }
414
+ /**
415
+ * Mix audio into video
416
+ */
417
+ async mixAudio(video, audio, options = {}) {
418
+ const tempDir = this.createTempDir();
419
+ try {
420
+ const videoPath = await this.getInputPath(video, "mp4", tempDir);
421
+ const audioPath = await this.getInputPath(audio, "mp3", tempDir);
422
+ const outputPath = join(tempDir, "output.mp4");
423
+ const mode = options.mode ?? "replace";
424
+ const args = [
425
+ "-y",
426
+ "-i",
427
+ videoPath,
428
+ "-i",
429
+ audioPath
430
+ ];
431
+ if (mode === "replace") {
432
+ args.push("-map", "0:v", "-map", "1:a");
433
+ if (options.newVolume !== void 0 && options.newVolume !== 1) args.push("-af", `volume=${options.newVolume}`);
434
+ if (options.fadeIn || options.fadeOut) {
435
+ const fadeFilters = [];
436
+ if (options.fadeIn) fadeFilters.push(`afade=t=in:d=${options.fadeIn}`);
437
+ if (options.fadeOut) fadeFilters.push(`afade=t=out:d=${options.fadeOut}`);
438
+ args.push("-af", fadeFilters.join(","));
439
+ }
440
+ } else {
441
+ const origVol = options.originalVolume ?? .5;
442
+ const newVol = options.newVolume ?? 1;
443
+ args.push("-filter_complex", `[0:a]volume=${origVol}[a0];[1:a]volume=${newVol}[a1];[a0][a1]amix=inputs=2:duration=first[a]`, "-map", "0:v", "-map", "[a]");
444
+ }
445
+ args.push("-c:v", "copy", "-shortest", outputPath);
446
+ await this.runFFmpeg(args);
447
+ return await readFile(outputPath);
448
+ } finally {
449
+ rmSync(tempDir, {
450
+ recursive: true,
451
+ force: true
452
+ });
453
+ }
454
+ }
455
+ /**
456
+ * Convert animated WEBP to MP4
457
+ *
458
+ * Uses sharp to extract frames from animated WEBP (which ffmpeg can't decode
459
+ * natively), then assembles them into an MP4 using ffmpeg.
460
+ */
461
+ async convertWebpToMp4(webp, options = {}) {
462
+ const fps = options.fps ?? 16;
463
+ const tempDir = this.createTempDir();
464
+ try {
465
+ const metadata = await sharp(webp, {
466
+ animated: true,
467
+ pages: -1
468
+ }).metadata();
469
+ const pageHeight = metadata.pageHeight ?? metadata.height ?? 480;
470
+ const frameCount = metadata.pages ?? 1;
471
+ this.logger.debug("Extracting WEBP frames", {
472
+ frameCount,
473
+ width: metadata.width,
474
+ pageHeight
475
+ });
476
+ for (let i = 0; i < frameCount; i++) {
477
+ const frame = await sharp(webp, {
478
+ page: i,
479
+ pages: 1
480
+ }).png().toBuffer();
481
+ await writeFile(join(tempDir, `frame_${String(i + 1).padStart(4, "0")}.png`), frame);
482
+ }
483
+ const outputPath = join(tempDir, "output.mp4");
484
+ const args = [
485
+ "-y",
486
+ "-framerate",
487
+ fps.toString(),
488
+ "-start_number",
489
+ "1",
490
+ "-i",
491
+ join(tempDir, "frame_%04d.png")
492
+ ];
493
+ if (options.video) args.push(...this.getVideoCodecArgs(options.video));
494
+ else args.push("-c:v", "libx264", "-pix_fmt", "yuv420p");
495
+ args.push(outputPath);
496
+ await this.runFFmpeg(args);
497
+ return await readFile(outputPath);
498
+ } finally {
499
+ rmSync(tempDir, {
500
+ recursive: true,
501
+ force: true
502
+ });
503
+ }
504
+ }
505
+ /**
506
+ * Get overlay position as FFmpeg expression
507
+ */
508
+ getOverlayPosition(position) {
509
+ const padding = position.padding ?? 20;
510
+ let x;
511
+ let y;
512
+ if (typeof position.x === "number") x = position.x.toString();
513
+ else switch (position.x) {
514
+ case "left":
515
+ x = padding.toString();
516
+ break;
517
+ case "center":
518
+ x = "(W-w)/2";
519
+ break;
520
+ case "right":
521
+ x = `W-w-${padding}`;
522
+ break;
523
+ }
524
+ if (typeof position.y === "number") y = position.y.toString();
525
+ else switch (position.y) {
526
+ case "top":
527
+ y = padding.toString();
528
+ break;
529
+ case "center":
530
+ y = "(H-h)/2";
531
+ break;
532
+ case "bottom":
533
+ y = `H-h-${padding}`;
534
+ break;
535
+ }
536
+ return {
537
+ x,
538
+ y
539
+ };
540
+ }
541
+ /**
542
+ * Get FFmpeg enable expression for time-based visibility
543
+ */
544
+ getEnableExpression(startTime, endTime) {
545
+ if (startTime !== void 0 && endTime !== void 0) return `between(t,${startTime},${endTime})`;
546
+ if (startTime !== void 0) return `gte(t,${startTime})`;
547
+ if (endTime !== void 0) return `lte(t,${endTime})`;
548
+ return "1";
549
+ }
550
+ /**
551
+ * Escape text for FFmpeg drawtext filter
552
+ */
553
+ escapeFFmpegText(text) {
554
+ return text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/:/g, "\\:").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
555
+ }
556
+ };
557
+ //#endregion
558
+ //#region src/media-bundles/utils.ts
559
+ var execFile$1 = promisify(execFile);
560
+ var VIDEO_EXTENSIONS = /* @__PURE__ */ new Set([
561
+ ".mp4",
562
+ ".mov",
563
+ ".m4v",
564
+ ".avi",
565
+ ".webm",
566
+ ".insv",
567
+ ".lrv"
584
568
  ]);
585
- const IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
586
- ".jpg",
587
- ".jpeg",
588
- ".png",
589
- ".webp",
590
- ".gif",
591
- ".tif",
592
- ".tiff",
593
- ".heic",
594
- ".insp"
569
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
570
+ ".jpg",
571
+ ".jpeg",
572
+ ".png",
573
+ ".webp",
574
+ ".gif",
575
+ ".tif",
576
+ ".tiff",
577
+ ".heic",
578
+ ".insp"
595
579
  ]);
596
580
  function displayName(file) {
597
- return file.name || basename(file.relativePath || file.path);
581
+ return file.name || basename(file.relativePath || file.path);
598
582
  }
599
583
  function fileExtension(file) {
600
- return extname(displayName(file)).toLowerCase();
584
+ return extname(displayName(file)).toLowerCase();
601
585
  }
602
586
  function isVideoFile(file) {
603
- const mime = (file.mimeType || "").toLowerCase();
604
- return mime.startsWith("video/") || VIDEO_EXTENSIONS.has(fileExtension(file));
587
+ return (file.mimeType || "").toLowerCase().startsWith("video/") || VIDEO_EXTENSIONS.has(fileExtension(file));
605
588
  }
606
589
  function isImageFile(file) {
607
- const mime = (file.mimeType || "").toLowerCase();
608
- return mime.startsWith("image/") || IMAGE_EXTENSIONS.has(fileExtension(file));
590
+ return (file.mimeType || "").toLowerCase().startsWith("image/") || IMAGE_EXTENSIONS.has(fileExtension(file));
609
591
  }
610
592
  function formatError(error) {
611
- return error instanceof Error ? error.message : String(error);
593
+ return error instanceof Error ? error.message : String(error);
612
594
  }
613
595
  async function runJsonCommand(bin, args) {
614
- const { stdout } = await execFile(bin, args, {
615
- maxBuffer: 100 * 1024 * 1024
616
- });
617
- return JSON.parse(stdout || "{}");
596
+ const { stdout } = await execFile$1(bin, args, { maxBuffer: 100 * 1024 * 1024 });
597
+ return JSON.parse(stdout || "{}");
618
598
  }
619
599
  async function runJsonArrayCommand(bin, args) {
620
- const { stdout } = await execFile(bin, args, {
621
- maxBuffer: 100 * 1024 * 1024
622
- });
623
- return JSON.parse(stdout || "[]");
600
+ const { stdout } = await execFile$1(bin, args, { maxBuffer: 100 * 1024 * 1024 });
601
+ return JSON.parse(stdout || "[]");
624
602
  }
625
603
  async function probeVideoMetadata(file, ffprobePath = "ffprobe") {
626
- const probe = await runJsonCommand(ffprobePath, [
627
- "-v",
628
- "error",
629
- "-print_format",
630
- "json",
631
- "-show_streams",
632
- "-show_format",
633
- file.path
634
- ]);
635
- const format = isRecord(probe.format) ? probe.format : {};
636
- const streams = Array.isArray(probe.streams) ? probe.streams.filter(isRecord) : [];
637
- const normalizedStreams = streams.map(normalizeFfprobeStream);
638
- const videoStream = normalizedStreams.find(
639
- (stream) => stream.kind === "video"
640
- );
641
- const tags = isRecord(format.tags) ? format.tags : {};
642
- const durationMs = toDurationMs(format.duration);
643
- return {
644
- captureTime: parseDateString(String(tags.creation_time || tags.CreateDate || "")) ?? null,
645
- width: videoStream?.width,
646
- height: videoStream?.height,
647
- durationMs,
648
- mimeType: file.mimeType,
649
- streams: normalizedStreams,
650
- raw: { ffprobe: probe }
651
- };
604
+ const probe = await runJsonCommand(ffprobePath, [
605
+ "-v",
606
+ "error",
607
+ "-print_format",
608
+ "json",
609
+ "-show_streams",
610
+ "-show_format",
611
+ file.path
612
+ ]);
613
+ const format = isRecord(probe.format) ? probe.format : {};
614
+ const normalizedStreams = (Array.isArray(probe.streams) ? probe.streams.filter(isRecord) : []).map(normalizeFfprobeStream);
615
+ const videoStream = normalizedStreams.find((stream) => stream.kind === "video");
616
+ const tags = isRecord(format.tags) ? format.tags : {};
617
+ const durationMs = toDurationMs(format.duration);
618
+ return {
619
+ captureTime: parseDateString(String(tags.creation_time || tags.CreateDate || "")) ?? null,
620
+ width: videoStream?.width,
621
+ height: videoStream?.height,
622
+ durationMs,
623
+ mimeType: file.mimeType,
624
+ streams: normalizedStreams,
625
+ raw: { ffprobe: probe }
626
+ };
652
627
  }
653
628
  async function probeEmbeddedMetadata(file, exiftoolPath = "exiftool") {
654
- const rows = await runJsonArrayCommand(exiftoolPath, [
655
- "-ee",
656
- "-G3:1",
657
- "-json",
658
- "-n",
659
- file.path
660
- ]);
661
- const row = rows[0] && isRecord(rows[0]) ? rows[0] : {};
662
- const flat = flattenExiftoolRecord(row);
663
- const device = readDevice(flat);
664
- const gpsTrack = parseExiftoolGpsRecord(row, file.path);
665
- const captureTime = flat.DateTimeOriginal || flat.CreateDate || flat.MediaCreateDate || flat.GPSDateTime || "";
666
- return {
667
- captureTime: parseDateString(String(captureTime)) ?? null,
668
- device,
669
- width: toInteger(flat.ImageWidth ?? flat.ExifImageWidth),
670
- height: toInteger(flat.ImageHeight ?? flat.ExifImageHeight),
671
- gpsTrack,
672
- raw: { exiftool: row }
673
- };
629
+ const rows = await runJsonArrayCommand(exiftoolPath, [
630
+ "-ee",
631
+ "-G3:1",
632
+ "-json",
633
+ "-n",
634
+ file.path
635
+ ]);
636
+ const row = rows[0] && isRecord(rows[0]) ? rows[0] : {};
637
+ const flat = flattenExiftoolRecord(row);
638
+ const device = readDevice(flat);
639
+ const gpsTrack = parseExiftoolGpsRecord(row, file.path);
640
+ const captureTime = flat.DateTimeOriginal || flat.CreateDate || flat.MediaCreateDate || flat.GPSDateTime || "";
641
+ return {
642
+ captureTime: parseDateString(String(captureTime)) ?? null,
643
+ device,
644
+ width: toInteger(flat.ImageWidth ?? flat.ExifImageWidth),
645
+ height: toInteger(flat.ImageHeight ?? flat.ExifImageHeight),
646
+ gpsTrack,
647
+ raw: { exiftool: row }
648
+ };
674
649
  }
675
650
  function mergeMetadata(primary, fallback) {
676
- return {
677
- captureTime: primary.captureTime ?? fallback.captureTime,
678
- device: {
679
- ...fallback.device,
680
- ...primary.device
681
- },
682
- width: primary.width ?? fallback.width,
683
- height: primary.height ?? fallback.height,
684
- durationMs: primary.durationMs ?? fallback.durationMs,
685
- mimeType: primary.mimeType ?? fallback.mimeType,
686
- streams: primary.streams && primary.streams.length > 0 ? primary.streams : fallback.streams,
687
- gpsTrack: primary.gpsTrack && primary.gpsTrack.length > 0 ? primary.gpsTrack : fallback.gpsTrack,
688
- raw: {
689
- ...fallback.raw,
690
- ...primary.raw
691
- },
692
- private: {
693
- ...fallback.private,
694
- ...primary.private
695
- }
696
- };
651
+ return {
652
+ captureTime: primary.captureTime ?? fallback.captureTime,
653
+ device: {
654
+ ...fallback.device,
655
+ ...primary.device
656
+ },
657
+ width: primary.width ?? fallback.width,
658
+ height: primary.height ?? fallback.height,
659
+ durationMs: primary.durationMs ?? fallback.durationMs,
660
+ mimeType: primary.mimeType ?? fallback.mimeType,
661
+ streams: primary.streams && primary.streams.length > 0 ? primary.streams : fallback.streams,
662
+ gpsTrack: primary.gpsTrack && primary.gpsTrack.length > 0 ? primary.gpsTrack : fallback.gpsTrack,
663
+ raw: {
664
+ ...fallback.raw,
665
+ ...primary.raw
666
+ },
667
+ private: {
668
+ ...fallback.private,
669
+ ...primary.private
670
+ }
671
+ };
697
672
  }
698
673
  function normalizeFfprobeStream(stream) {
699
- const kind = String(
700
- stream.codec_type || "unknown"
701
- );
702
- return {
703
- kind: ["video", "audio", "data"].includes(kind) ? kind : "unknown",
704
- codec: readString(stream.codec_name),
705
- width: toInteger(stream.width),
706
- height: toInteger(stream.height),
707
- fps: parseFrameRate(readString(stream.r_frame_rate)),
708
- durationMs: toDurationMs(stream.duration),
709
- bitrate: toInteger(stream.bit_rate),
710
- metadata: stream
711
- };
674
+ const kind = String(stream.codec_type || "unknown");
675
+ return {
676
+ kind: [
677
+ "video",
678
+ "audio",
679
+ "data"
680
+ ].includes(kind) ? kind : "unknown",
681
+ codec: readString(stream.codec_name),
682
+ width: toInteger(stream.width),
683
+ height: toInteger(stream.height),
684
+ fps: parseFrameRate(readString(stream.r_frame_rate)),
685
+ durationMs: toDurationMs(stream.duration),
686
+ bitrate: toInteger(stream.bit_rate),
687
+ metadata: stream
688
+ };
712
689
  }
713
690
  function flattenExiftoolRecord(row) {
714
- const out = {};
715
- for (const [key, value] of Object.entries(row)) {
716
- out[key] = value;
717
- const suffix = key.split(":").at(-1);
718
- if (suffix && !(suffix in out)) out[suffix] = value;
719
- }
720
- return out;
691
+ const out = {};
692
+ for (const [key, value] of Object.entries(row)) {
693
+ out[key] = value;
694
+ const suffix = key.split(":").at(-1);
695
+ if (suffix && !(suffix in out)) out[suffix] = value;
696
+ }
697
+ return out;
721
698
  }
722
699
  function readDevice(row) {
723
- const model = readString(row.Model);
724
- const make = readString(row.Make) || inferMake(model);
725
- const serialNumber = readString(row.SerialNumber);
726
- const firmwareVersion = readString(row.Firmware);
727
- if (!make && !model && !serialNumber && !firmwareVersion) return void 0;
728
- return { make, model, serialNumber, firmwareVersion };
700
+ const model = readString(row.Model);
701
+ const make = readString(row.Make) || inferMake(model);
702
+ const serialNumber = readString(row.SerialNumber);
703
+ const firmwareVersion = readString(row.Firmware);
704
+ if (!make && !model && !serialNumber && !firmwareVersion) return void 0;
705
+ return {
706
+ make,
707
+ model,
708
+ serialNumber,
709
+ firmwareVersion
710
+ };
729
711
  }
730
712
  function inferMake(model) {
731
- if (!model) return void 0;
732
- const vendors = [
733
- "Insta360",
734
- "GoPro",
735
- "DJI",
736
- "Sony",
737
- "Canon",
738
- "Nikon",
739
- "Ricoh",
740
- "Panasonic",
741
- "Fujifilm"
742
- ];
743
- const lowered = model.toLowerCase();
744
- return vendors.find((vendor) => lowered.startsWith(vendor.toLowerCase()));
713
+ if (!model) return void 0;
714
+ const vendors = [
715
+ "Insta360",
716
+ "GoPro",
717
+ "DJI",
718
+ "Sony",
719
+ "Canon",
720
+ "Nikon",
721
+ "Ricoh",
722
+ "Panasonic",
723
+ "Fujifilm"
724
+ ];
725
+ const lowered = model.toLowerCase();
726
+ return vendors.find((vendor) => lowered.startsWith(vendor.toLowerCase()));
745
727
  }
746
728
  function parseExiftoolGpsRecord(row, sourceFilePath) {
747
- const grouped = /* @__PURE__ */ new Map();
748
- const mainFields = {};
749
- for (const [key, value] of Object.entries(row)) {
750
- const docMatch = /^(Doc\d+):[^:]+:(\w+)$/.exec(key);
751
- if (docMatch) {
752
- const bucket = grouped.get(docMatch[1]) ?? {};
753
- bucket[docMatch[2]] = value;
754
- grouped.set(docMatch[1], bucket);
755
- continue;
756
- }
757
- const mainMatch = /^Main:[^:]+:(\w+)$/.exec(key);
758
- if (mainMatch) mainFields[mainMatch[1]] = value;
759
- }
760
- const out = [];
761
- let firstEpochMs = null;
762
- let lastLat = null;
763
- let lastLon = null;
764
- for (const docId of [...grouped.keys()].sort(compareDocIds)) {
765
- const record = grouped.get(docId);
766
- if (!record) continue;
767
- const lat2 = toNumber(record.GPSLatitude);
768
- const lon2 = toNumber(record.GPSLongitude);
769
- const epochMs2 = record.GPSDateTime == null ? null : parseDateMs(String(record.GPSDateTime));
770
- if (lat2 == null || lon2 == null || epochMs2 == null) continue;
771
- if (firstEpochMs == null) firstEpochMs = epochMs2;
772
- if (lat2 === lastLat && lon2 === lastLon) continue;
773
- lastLat = lat2;
774
- lastLon = lon2;
775
- out.push({
776
- tSeconds: Math.max(0, (epochMs2 - firstEpochMs) / 1e3),
777
- recordedAt: new Date(epochMs2).toISOString(),
778
- latitude: lat2,
779
- longitude: lon2,
780
- altitude: toNumber(record.GPSAltitude),
781
- heading: toNumber(record.GPSTrack),
782
- speedMps: toNumber(record.GPSSpeed),
783
- sourceFilePath
784
- });
785
- }
786
- if (out.length > 0) return out;
787
- const flat = flattenExiftoolRecord(row);
788
- const fallback = Object.keys(mainFields).length > 0 ? mainFields : flat;
789
- const lat = toNumber(fallback.GPSLatitude);
790
- const lon = toNumber(fallback.GPSLongitude);
791
- const epochMs = fallback.GPSDateTime == null ? null : parseDateMs(String(fallback.GPSDateTime));
792
- if (lat == null || lon == null || epochMs == null) return [];
793
- return [
794
- {
795
- tSeconds: 0,
796
- recordedAt: new Date(epochMs).toISOString(),
797
- latitude: lat,
798
- longitude: lon,
799
- altitude: toNumber(fallback.GPSAltitude),
800
- heading: toNumber(fallback.GPSTrack ?? fallback.GPSImgDirection),
801
- speedMps: toNumber(fallback.GPSSpeed),
802
- sourceFilePath
803
- }
804
- ];
729
+ const grouped = /* @__PURE__ */ new Map();
730
+ const mainFields = {};
731
+ for (const [key, value] of Object.entries(row)) {
732
+ const docMatch = /^(Doc\d+):[^:]+:(\w+)$/.exec(key);
733
+ if (docMatch) {
734
+ const bucket = grouped.get(docMatch[1]) ?? {};
735
+ bucket[docMatch[2]] = value;
736
+ grouped.set(docMatch[1], bucket);
737
+ continue;
738
+ }
739
+ const mainMatch = /^Main:[^:]+:(\w+)$/.exec(key);
740
+ if (mainMatch) mainFields[mainMatch[1]] = value;
741
+ }
742
+ const out = [];
743
+ let firstEpochMs = null;
744
+ let lastLat = null;
745
+ let lastLon = null;
746
+ for (const docId of [...grouped.keys()].sort(compareDocIds)) {
747
+ const record = grouped.get(docId);
748
+ if (!record) continue;
749
+ const lat = toNumber(record.GPSLatitude);
750
+ const lon = toNumber(record.GPSLongitude);
751
+ const epochMs = record.GPSDateTime == null ? null : parseDateMs(String(record.GPSDateTime));
752
+ if (lat == null || lon == null || epochMs == null) continue;
753
+ if (firstEpochMs == null) firstEpochMs = epochMs;
754
+ if (lat === lastLat && lon === lastLon) continue;
755
+ lastLat = lat;
756
+ lastLon = lon;
757
+ out.push({
758
+ tSeconds: Math.max(0, (epochMs - firstEpochMs) / 1e3),
759
+ recordedAt: new Date(epochMs).toISOString(),
760
+ latitude: lat,
761
+ longitude: lon,
762
+ altitude: toNumber(record.GPSAltitude),
763
+ heading: toNumber(record.GPSTrack),
764
+ speedMps: toNumber(record.GPSSpeed),
765
+ sourceFilePath
766
+ });
767
+ }
768
+ if (out.length > 0) return out;
769
+ const flat = flattenExiftoolRecord(row);
770
+ const fallback = Object.keys(mainFields).length > 0 ? mainFields : flat;
771
+ const lat = toNumber(fallback.GPSLatitude);
772
+ const lon = toNumber(fallback.GPSLongitude);
773
+ const epochMs = fallback.GPSDateTime == null ? null : parseDateMs(String(fallback.GPSDateTime));
774
+ if (lat == null || lon == null || epochMs == null) return [];
775
+ return [{
776
+ tSeconds: 0,
777
+ recordedAt: new Date(epochMs).toISOString(),
778
+ latitude: lat,
779
+ longitude: lon,
780
+ altitude: toNumber(fallback.GPSAltitude),
781
+ heading: toNumber(fallback.GPSTrack ?? fallback.GPSImgDirection),
782
+ speedMps: toNumber(fallback.GPSSpeed),
783
+ sourceFilePath
784
+ }];
805
785
  }
806
786
  function compareDocIds(left, right) {
807
- return Number(left.replace(/\D+/g, "")) - Number(right.replace(/\D+/g, ""));
787
+ return Number(left.replace(/\D+/g, "")) - Number(right.replace(/\D+/g, ""));
808
788
  }
809
789
  function parseFrameRate(value) {
810
- if (!value) return void 0;
811
- const [num, den] = value.split("/").map(Number);
812
- const fps = den ? num / den : num;
813
- return Number.isFinite(fps) && fps > 0 ? fps : void 0;
790
+ if (!value) return void 0;
791
+ const [num, den] = value.split("/").map(Number);
792
+ const fps = den ? num / den : num;
793
+ return Number.isFinite(fps) && fps > 0 ? fps : void 0;
814
794
  }
815
795
  function toDurationMs(value) {
816
- const seconds = Number(value);
817
- return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1e3) : void 0;
796
+ const seconds = Number(value);
797
+ return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1e3) : void 0;
818
798
  }
819
799
  function toInteger(value) {
820
- const number = Number(value);
821
- return Number.isInteger(number) && number > 0 ? number : void 0;
800
+ const number = Number(value);
801
+ return Number.isInteger(number) && number > 0 ? number : void 0;
822
802
  }
823
803
  function toNumber(value) {
824
- if (value == null || value === "") return null;
825
- const number = Number(value);
826
- return Number.isFinite(number) ? number : null;
804
+ if (value == null || value === "") return null;
805
+ const number = Number(value);
806
+ return Number.isFinite(number) ? number : null;
827
807
  }
828
808
  function readString(value) {
829
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
809
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
830
810
  }
831
811
  function parseDateString(value) {
832
- const ms = parseDateMs(value);
833
- return ms == null ? null : new Date(ms).toISOString();
812
+ const ms = parseDateMs(value);
813
+ return ms == null ? null : new Date(ms).toISOString();
834
814
  }
835
815
  function parseDateMs(value) {
836
- const normalized = value.trim().replace(/^(\d{4}):(\d{2}):(\d{2})/, "$1-$2-$3");
837
- if (!normalized) return null;
838
- const ms = Date.parse(normalized);
839
- return Number.isFinite(ms) ? ms : null;
816
+ const normalized = value.trim().replace(/^(\d{4}):(\d{2}):(\d{2})/, "$1-$2-$3");
817
+ if (!normalized) return null;
818
+ const ms = Date.parse(normalized);
819
+ return Number.isFinite(ms) ? ms : null;
840
820
  }
841
821
  function isRecord(value) {
842
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
822
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
843
823
  }
844
- const genericImageBundleHandler = {
845
- id: "generic-image",
846
- version: "1.0.0",
847
- priority: 10,
848
- capabilities: ["image-metadata"],
849
- supports(files) {
850
- return files.some(isImageFile);
851
- },
852
- async inspect(files, context) {
853
- const primary = files.find(isImageFile) ?? files[0];
854
- const warnings = [];
855
- let metadata = {
856
- mimeType: primary.mimeType
857
- };
858
- if (context.probe === false) {
859
- warnings.push(
860
- "probe disabled; returning file-level generic image inspection"
861
- );
862
- } else {
863
- try {
864
- const image = await getImageMetadata(primary.path);
865
- metadata = {
866
- width: image.width,
867
- height: image.height,
868
- mimeType: primary.mimeType,
869
- raw: { image }
870
- };
871
- } catch (error) {
872
- warnings.push(
873
- `image metadata probe failed for ${displayName(primary)}: ${formatError(error)}`
874
- );
875
- }
876
- }
877
- return {
878
- handlerId: genericImageBundleHandler.id,
879
- handlerVersion: genericImageBundleHandler.version,
880
- formatFamily: "generic-image",
881
- primary: { ...primary, role: "primary" },
882
- supportFiles: files.filter((file) => file !== primary).map((file) => ({
883
- file: { ...file, role: file.role ?? "support" },
884
- role: "support",
885
- relationship: "co-located-file",
886
- visibility: context.defaultSupportFileVisibility ?? "hidden-retained"
887
- })),
888
- metadata,
889
- capabilities: [...genericImageBundleHandler.capabilities ?? []],
890
- warnings,
891
- errors: []
892
- };
893
- }
824
+ //#endregion
825
+ //#region src/media-bundles/handlers/generic-image.ts
826
+ var genericImageBundleHandler = {
827
+ id: "generic-image",
828
+ version: "1.0.0",
829
+ priority: 10,
830
+ capabilities: ["image-metadata"],
831
+ supports(files) {
832
+ return files.some(isImageFile);
833
+ },
834
+ async inspect(files, context) {
835
+ const primary = files.find(isImageFile) ?? files[0];
836
+ const warnings = [];
837
+ let metadata = { mimeType: primary.mimeType };
838
+ if (context.probe === false) warnings.push("probe disabled; returning file-level generic image inspection");
839
+ else try {
840
+ const image = await getImageMetadata(primary.path);
841
+ metadata = {
842
+ width: image.width,
843
+ height: image.height,
844
+ mimeType: primary.mimeType,
845
+ raw: { image }
846
+ };
847
+ } catch (error) {
848
+ warnings.push(`image metadata probe failed for ${displayName(primary)}: ${formatError(error)}`);
849
+ }
850
+ return {
851
+ handlerId: genericImageBundleHandler.id,
852
+ handlerVersion: genericImageBundleHandler.version,
853
+ formatFamily: "generic-image",
854
+ primary: {
855
+ ...primary,
856
+ role: "primary"
857
+ },
858
+ supportFiles: files.filter((file) => file !== primary).map((file) => ({
859
+ file: {
860
+ ...file,
861
+ role: file.role ?? "support"
862
+ },
863
+ role: "support",
864
+ relationship: "co-located-file",
865
+ visibility: context.defaultSupportFileVisibility ?? "hidden-retained"
866
+ })),
867
+ metadata,
868
+ capabilities: [...genericImageBundleHandler.capabilities ?? []],
869
+ warnings,
870
+ errors: []
871
+ };
872
+ }
894
873
  };
895
- const genericVideoBundleHandler = {
896
- id: "generic-video",
897
- version: "1.0.0",
898
- priority: 10,
899
- capabilities: ["stream-info"],
900
- supports(files) {
901
- return files.some(isVideoFile);
902
- },
903
- async inspect(files, context) {
904
- const primary = files.find(isVideoFile) ?? files[0];
905
- const warnings = [];
906
- const supportFiles = files.filter((file) => file !== primary).map((file) => ({
907
- file: { ...file, role: file.role ?? "support" },
908
- role: "support",
909
- relationship: "co-located-file",
910
- visibility: context.defaultSupportFileVisibility ?? "hidden-retained"
911
- }));
912
- let metadata = {
913
- mimeType: primary.mimeType
914
- };
915
- if (context.probe === false) {
916
- warnings.push(
917
- "probe disabled; returning file-level generic video inspection"
918
- );
919
- } else {
920
- try {
921
- metadata = mergeMetadata(
922
- await probeVideoMetadata(primary, context.tools?.ffprobePath),
923
- metadata
924
- );
925
- } catch (error) {
926
- warnings.push(
927
- `ffprobe failed for ${displayName(primary)}: ${formatError(error)}`
928
- );
929
- }
930
- try {
931
- metadata = mergeMetadata(
932
- await probeEmbeddedMetadata(primary, context.tools?.exiftoolPath),
933
- metadata
934
- );
935
- } catch (error) {
936
- warnings.push(
937
- `exiftool failed for ${displayName(primary)}: ${formatError(error)}`
938
- );
939
- }
940
- }
941
- const capabilities = new Set(genericVideoBundleHandler.capabilities);
942
- if (metadata.gpsTrack && metadata.gpsTrack.length > 0)
943
- capabilities.add("gps-track");
944
- return {
945
- handlerId: genericVideoBundleHandler.id,
946
- handlerVersion: genericVideoBundleHandler.version,
947
- formatFamily: "generic-video",
948
- primary: { ...primary, role: "primary" },
949
- supportFiles,
950
- metadata,
951
- capabilities: [...capabilities],
952
- warnings,
953
- errors: []
954
- };
955
- }
874
+ //#endregion
875
+ //#region src/media-bundles/handlers/generic-video.ts
876
+ var genericVideoBundleHandler = {
877
+ id: "generic-video",
878
+ version: "1.0.0",
879
+ priority: 10,
880
+ capabilities: ["stream-info"],
881
+ supports(files) {
882
+ return files.some(isVideoFile);
883
+ },
884
+ async inspect(files, context) {
885
+ const primary = files.find(isVideoFile) ?? files[0];
886
+ const warnings = [];
887
+ const supportFiles = files.filter((file) => file !== primary).map((file) => ({
888
+ file: {
889
+ ...file,
890
+ role: file.role ?? "support"
891
+ },
892
+ role: "support",
893
+ relationship: "co-located-file",
894
+ visibility: context.defaultSupportFileVisibility ?? "hidden-retained"
895
+ }));
896
+ let metadata = { mimeType: primary.mimeType };
897
+ if (context.probe === false) warnings.push("probe disabled; returning file-level generic video inspection");
898
+ else {
899
+ try {
900
+ metadata = mergeMetadata(await probeVideoMetadata(primary, context.tools?.ffprobePath), metadata);
901
+ } catch (error) {
902
+ warnings.push(`ffprobe failed for ${displayName(primary)}: ${formatError(error)}`);
903
+ }
904
+ try {
905
+ metadata = mergeMetadata(await probeEmbeddedMetadata(primary, context.tools?.exiftoolPath), metadata);
906
+ } catch (error) {
907
+ warnings.push(`exiftool failed for ${displayName(primary)}: ${formatError(error)}`);
908
+ }
909
+ }
910
+ const capabilities = new Set(genericVideoBundleHandler.capabilities);
911
+ if (metadata.gpsTrack && metadata.gpsTrack.length > 0) capabilities.add("gps-track");
912
+ return {
913
+ handlerId: genericVideoBundleHandler.id,
914
+ handlerVersion: genericVideoBundleHandler.version,
915
+ formatFamily: "generic-video",
916
+ primary: {
917
+ ...primary,
918
+ role: "primary"
919
+ },
920
+ supportFiles,
921
+ metadata,
922
+ capabilities: [...capabilities],
923
+ warnings,
924
+ errors: []
925
+ };
926
+ }
956
927
  };
957
- const INSTA360_RE = /^(VID|LRV)_(\d{8})_(\d{6})_(\d{2})_(\d+)\.(insv|lrv)$/i;
958
- const insta360BundleHandler = {
959
- id: "insta360-insv-lrv",
960
- version: "1.0.0",
961
- priority: 100,
962
- capabilities: ["sidecar-binding", "stitch-export", "stream-info"],
963
- supports(files) {
964
- return files.some((file) => parseInsta360FileName(file));
965
- },
966
- async inspect(files, context) {
967
- const parsedByPath = new Map(
968
- files.map((file) => [file.path, parseInsta360FileName(file)])
969
- );
970
- const bundleKey = chooseBundleKey(files, parsedByPath);
971
- const bundleFiles = files.filter((file) => {
972
- const parsed = parsedByPath.get(file.path);
973
- return Boolean(parsed && (!bundleKey || parsed.bundleKey === bundleKey));
974
- });
975
- const ignoredFiles = files.filter((file) => !bundleFiles.includes(file));
976
- const primary = choosePrimary(bundleFiles, parsedByPath);
977
- const warnings = [];
978
- if (ignoredFiles.length > 0) {
979
- warnings.push(
980
- `ignored ${ignoredFiles.length} file(s) outside Insta360 bundle ${bundleKey ?? "unknown"}: ${ignoredFiles.map(displayName).join(", ")}`
981
- );
982
- }
983
- let metadata = {
984
- mimeType: primary.mimeType,
985
- private: {
986
- "happyvertical.video.insta360": {
987
- primary: parsedByPath.get(primary.path) ?? null,
988
- supportFiles: bundleFiles.filter((file) => file !== primary).map((file) => parsedByPath.get(file.path) ?? null)
989
- }
990
- }
991
- };
992
- const nonPrimaryBundleFiles = bundleFiles.filter(
993
- (file) => file !== primary
994
- );
995
- const supportFiles = await Promise.all(
996
- nonPrimaryBundleFiles.map(async (file) => {
997
- const parsed = parsedByPath.get(file.path);
998
- let supportMetadata;
999
- if (context.probe !== false) {
1000
- try {
1001
- supportMetadata = await probeEmbeddedMetadata(
1002
- file,
1003
- context.tools?.exiftoolPath
1004
- );
1005
- } catch (error) {
1006
- warnings.push(
1007
- `exiftool failed for support file ${displayName(file)}: ${formatError(error)}`
1008
- );
1009
- }
1010
- }
1011
- return {
1012
- file: { ...file, role: "support" },
1013
- role: "support",
1014
- relationship: relationshipForInsta360SupportFile(file, parsed),
1015
- visibility: context.defaultSupportFileVisibility ?? "hidden-retained",
1016
- metadata: supportMetadata
1017
- };
1018
- })
1019
- );
1020
- if (context.probe === false) {
1021
- warnings.push(
1022
- "probe disabled; returning file-level Insta360 bundle inspection"
1023
- );
1024
- } else {
1025
- try {
1026
- metadata = mergeMetadata(
1027
- await probeVideoMetadata(primary, context.tools?.ffprobePath),
1028
- metadata
1029
- );
1030
- } catch (error) {
1031
- warnings.push(
1032
- `ffprobe failed for primary ${displayName(primary)}: ${formatError(error)}`
1033
- );
1034
- }
1035
- try {
1036
- metadata = mergeMetadata(
1037
- await probeEmbeddedMetadata(primary, context.tools?.exiftoolPath),
1038
- metadata
1039
- );
1040
- } catch (error) {
1041
- warnings.push(
1042
- `exiftool failed for primary ${displayName(primary)}: ${formatError(error)}`
1043
- );
1044
- }
1045
- }
1046
- if (!metadata.gpsTrack || metadata.gpsTrack.length === 0) {
1047
- const supportGps = supportFiles.map((support) => support.metadata).find(
1048
- (candidate) => candidate?.gpsTrack && candidate.gpsTrack.length > 0
1049
- );
1050
- if (supportGps) {
1051
- metadata = { ...metadata, gpsTrack: supportGps.gpsTrack };
1052
- }
1053
- }
1054
- const capabilities = new Set(insta360BundleHandler.capabilities);
1055
- if (metadata.gpsTrack && metadata.gpsTrack.length > 0)
1056
- capabilities.add("gps-track");
1057
- return {
1058
- handlerId: insta360BundleHandler.id,
1059
- handlerVersion: insta360BundleHandler.version,
1060
- formatFamily: "insta360",
1061
- primary: { ...primary, role: "primary" },
1062
- supportFiles,
1063
- metadata,
1064
- capabilities: [...capabilities],
1065
- warnings,
1066
- errors: [],
1067
- raw: {
1068
- insta360: {
1069
- bundleKey,
1070
- files: Object.fromEntries(
1071
- bundleFiles.map((file) => [file.path, parsedByPath.get(file.path)])
1072
- ),
1073
- ignoredFiles: ignoredFiles.map((file) => ({
1074
- file,
1075
- identity: parsedByPath.get(file.path) ?? null
1076
- }))
1077
- }
1078
- }
1079
- };
1080
- }
928
+ //#endregion
929
+ //#region src/media-bundles/handlers/insta360.ts
930
+ var INSTA360_RE = /^(VID|LRV)_(\d{8})_(\d{6})_(\d{2})_(\d+)\.(insv|lrv)$/i;
931
+ var insta360BundleHandler = {
932
+ id: "insta360-insv-lrv",
933
+ version: "1.0.0",
934
+ priority: 100,
935
+ capabilities: [
936
+ "sidecar-binding",
937
+ "stitch-export",
938
+ "stream-info"
939
+ ],
940
+ supports(files) {
941
+ return files.some((file) => parseInsta360FileName(file));
942
+ },
943
+ async inspect(files, context) {
944
+ const parsedByPath = new Map(files.map((file) => [file.path, parseInsta360FileName(file)]));
945
+ const bundleKey = chooseBundleKey(files, parsedByPath);
946
+ const bundleFiles = files.filter((file) => {
947
+ const parsed = parsedByPath.get(file.path);
948
+ return Boolean(parsed && (!bundleKey || parsed.bundleKey === bundleKey));
949
+ });
950
+ const ignoredFiles = files.filter((file) => !bundleFiles.includes(file));
951
+ const primary = choosePrimary(bundleFiles, parsedByPath);
952
+ const warnings = [];
953
+ if (ignoredFiles.length > 0) warnings.push(`ignored ${ignoredFiles.length} file(s) outside Insta360 bundle ${bundleKey ?? "unknown"}: ${ignoredFiles.map(displayName).join(", ")}`);
954
+ let metadata = {
955
+ mimeType: primary.mimeType,
956
+ private: { "happyvertical.video.insta360": {
957
+ primary: parsedByPath.get(primary.path) ?? null,
958
+ supportFiles: bundleFiles.filter((file) => file !== primary).map((file) => parsedByPath.get(file.path) ?? null)
959
+ } }
960
+ };
961
+ const nonPrimaryBundleFiles = bundleFiles.filter((file) => file !== primary);
962
+ const supportFiles = await Promise.all(nonPrimaryBundleFiles.map(async (file) => {
963
+ const parsed = parsedByPath.get(file.path);
964
+ let supportMetadata;
965
+ if (context.probe !== false) try {
966
+ supportMetadata = await probeEmbeddedMetadata(file, context.tools?.exiftoolPath);
967
+ } catch (error) {
968
+ warnings.push(`exiftool failed for support file ${displayName(file)}: ${formatError(error)}`);
969
+ }
970
+ return {
971
+ file: {
972
+ ...file,
973
+ role: "support"
974
+ },
975
+ role: "support",
976
+ relationship: relationshipForInsta360SupportFile(file, parsed),
977
+ visibility: context.defaultSupportFileVisibility ?? "hidden-retained",
978
+ metadata: supportMetadata
979
+ };
980
+ }));
981
+ if (context.probe === false) warnings.push("probe disabled; returning file-level Insta360 bundle inspection");
982
+ else {
983
+ try {
984
+ metadata = mergeMetadata(await probeVideoMetadata(primary, context.tools?.ffprobePath), metadata);
985
+ } catch (error) {
986
+ warnings.push(`ffprobe failed for primary ${displayName(primary)}: ${formatError(error)}`);
987
+ }
988
+ try {
989
+ metadata = mergeMetadata(await probeEmbeddedMetadata(primary, context.tools?.exiftoolPath), metadata);
990
+ } catch (error) {
991
+ warnings.push(`exiftool failed for primary ${displayName(primary)}: ${formatError(error)}`);
992
+ }
993
+ }
994
+ if (!metadata.gpsTrack || metadata.gpsTrack.length === 0) {
995
+ const supportGps = supportFiles.map((support) => support.metadata).find((candidate) => candidate?.gpsTrack && candidate.gpsTrack.length > 0);
996
+ if (supportGps) metadata = {
997
+ ...metadata,
998
+ gpsTrack: supportGps.gpsTrack
999
+ };
1000
+ }
1001
+ const capabilities = new Set(insta360BundleHandler.capabilities);
1002
+ if (metadata.gpsTrack && metadata.gpsTrack.length > 0) capabilities.add("gps-track");
1003
+ return {
1004
+ handlerId: insta360BundleHandler.id,
1005
+ handlerVersion: insta360BundleHandler.version,
1006
+ formatFamily: "insta360",
1007
+ primary: {
1008
+ ...primary,
1009
+ role: "primary"
1010
+ },
1011
+ supportFiles,
1012
+ metadata,
1013
+ capabilities: [...capabilities],
1014
+ warnings,
1015
+ errors: [],
1016
+ raw: { insta360: {
1017
+ bundleKey,
1018
+ files: Object.fromEntries(bundleFiles.map((file) => [file.path, parsedByPath.get(file.path)])),
1019
+ ignoredFiles: ignoredFiles.map((file) => ({
1020
+ file,
1021
+ identity: parsedByPath.get(file.path) ?? null
1022
+ }))
1023
+ } }
1024
+ };
1025
+ }
1081
1026
  };
1082
1027
  function parseInsta360FileName(file) {
1083
- const match = INSTA360_RE.exec(displayName(file));
1084
- if (!match) return null;
1085
- const prefix = match[1].toUpperCase();
1086
- const date = match[2];
1087
- const time = match[3];
1088
- const streamIndex = match[4];
1089
- const sequence = match[5];
1090
- const extension = match[6].toLowerCase();
1091
- return {
1092
- prefix,
1093
- date,
1094
- time,
1095
- streamIndex,
1096
- sequence,
1097
- extension,
1098
- bundleKey: `${date}_${time}_${sequence}`
1099
- };
1028
+ const match = INSTA360_RE.exec(displayName(file));
1029
+ if (!match) return null;
1030
+ const prefix = match[1].toUpperCase();
1031
+ const date = match[2];
1032
+ const time = match[3];
1033
+ const streamIndex = match[4];
1034
+ const sequence = match[5];
1035
+ return {
1036
+ prefix,
1037
+ date,
1038
+ time,
1039
+ streamIndex,
1040
+ sequence,
1041
+ extension: match[6].toLowerCase(),
1042
+ bundleKey: `${date}_${time}_${sequence}`
1043
+ };
1100
1044
  }
1101
1045
  function chooseBundleKey(files, parsedByPath) {
1102
- const candidate = files.map((file) => parsedByPath.get(file.path)).find((parsed) => parsed?.prefix === "VID" && parsed.streamIndex === "00");
1103
- if (candidate) return candidate.bundleKey;
1104
- return files.map((file) => parsedByPath.get(file.path)).find(Boolean)?.bundleKey ?? null;
1046
+ const candidate = files.map((file) => parsedByPath.get(file.path)).find((parsed) => parsed?.prefix === "VID" && parsed.streamIndex === "00");
1047
+ if (candidate) return candidate.bundleKey;
1048
+ return files.map((file) => parsedByPath.get(file.path)).find(Boolean)?.bundleKey ?? null;
1105
1049
  }
1106
1050
  function choosePrimary(files, parsedByPath) {
1107
- return files.find((file) => {
1108
- const parsed = parsedByPath.get(file.path);
1109
- return parsed?.prefix === "VID" && parsed.streamIndex === "00";
1110
- }) ?? files.find((file) => {
1111
- const parsed = parsedByPath.get(file.path);
1112
- return parsed?.prefix === "VID" && parsed.extension === "insv";
1113
- }) ?? files.find((file) => fileExtension(file) === ".insv") ?? files[0];
1051
+ return files.find((file) => {
1052
+ const parsed = parsedByPath.get(file.path);
1053
+ return parsed?.prefix === "VID" && parsed.streamIndex === "00";
1054
+ }) ?? files.find((file) => {
1055
+ const parsed = parsedByPath.get(file.path);
1056
+ return parsed?.prefix === "VID" && parsed.extension === "insv";
1057
+ }) ?? files.find((file) => fileExtension(file) === ".insv") ?? files[0];
1114
1058
  }
1115
1059
  function relationshipForInsta360SupportFile(file, parsed) {
1116
- if (parsed?.prefix === "LRV" || fileExtension(file) === ".lrv")
1117
- return "proxy-video";
1118
- if (parsed?.prefix === "VID" && parsed.streamIndex !== "00")
1119
- return "paired-video-stream";
1120
- return "support-file";
1060
+ if (parsed?.prefix === "LRV" || fileExtension(file) === ".lrv") return "proxy-video";
1061
+ if (parsed?.prefix === "VID" && parsed.streamIndex !== "00") return "paired-video-stream";
1062
+ return "support-file";
1121
1063
  }
1122
- const defaultMediaBundleHandlers = [
1123
- insta360BundleHandler,
1124
- genericVideoBundleHandler,
1125
- genericImageBundleHandler
1064
+ //#endregion
1065
+ //#region src/media-bundles/index.ts
1066
+ var defaultMediaBundleHandlers = [
1067
+ insta360BundleHandler,
1068
+ genericVideoBundleHandler,
1069
+ genericImageBundleHandler
1126
1070
  ];
1127
1071
  async function inspectMediaBundle(files, options = {}) {
1128
- if (files.length === 0) {
1129
- throw new Error("inspectMediaBundle requires at least one file");
1130
- }
1131
- const context = {
1132
- ...options,
1133
- defaultSupportFileVisibility: options.defaultSupportFileVisibility ?? "hidden-retained"
1134
- };
1135
- const handlers = options.handlers ?? defaultMediaBundleHandlers;
1136
- const orderedHandlers = handlers.map((handler, index) => ({ handler, index })).sort(
1137
- (left, right) => right.handler.priority - left.handler.priority || left.index - right.index
1138
- );
1139
- for (const { handler } of orderedHandlers) {
1140
- if (!await handler.supports(files, context)) continue;
1141
- const inspection = await handler.inspect(files, context);
1142
- const validationWarnings = handler.validate ? await handler.validate(inspection, context) : [];
1143
- if (validationWarnings.length > 0) {
1144
- inspection.warnings.push(...validationWarnings);
1145
- }
1146
- return inspection;
1147
- }
1148
- return {
1149
- handlerId: "unknown",
1150
- handlerVersion: "1.0.0",
1151
- formatFamily: "unknown",
1152
- primary: { ...files[0], role: "primary" },
1153
- supportFiles: files.slice(1).map((file) => ({
1154
- file: { ...file, role: file.role ?? "support" },
1155
- role: "support",
1156
- relationship: "co-located-file",
1157
- visibility: context.defaultSupportFileVisibility
1158
- })),
1159
- metadata: {
1160
- mimeType: files[0].mimeType
1161
- },
1162
- capabilities: [],
1163
- warnings: ["no media bundle handler matched; returned unknown inspection"],
1164
- errors: []
1165
- };
1072
+ if (files.length === 0) throw new Error("inspectMediaBundle requires at least one file");
1073
+ const context = {
1074
+ ...options,
1075
+ defaultSupportFileVisibility: options.defaultSupportFileVisibility ?? "hidden-retained"
1076
+ };
1077
+ const orderedHandlers = (options.handlers ?? defaultMediaBundleHandlers).map((handler, index) => ({
1078
+ handler,
1079
+ index
1080
+ })).sort((left, right) => right.handler.priority - left.handler.priority || left.index - right.index);
1081
+ for (const { handler } of orderedHandlers) {
1082
+ if (!await handler.supports(files, context)) continue;
1083
+ const inspection = await handler.inspect(files, context);
1084
+ const validationWarnings = handler.validate ? await handler.validate(inspection, context) : [];
1085
+ if (validationWarnings.length > 0) inspection.warnings.push(...validationWarnings);
1086
+ return inspection;
1087
+ }
1088
+ return {
1089
+ handlerId: "unknown",
1090
+ handlerVersion: "1.0.0",
1091
+ formatFamily: "unknown",
1092
+ primary: {
1093
+ ...files[0],
1094
+ role: "primary"
1095
+ },
1096
+ supportFiles: files.slice(1).map((file) => ({
1097
+ file: {
1098
+ ...file,
1099
+ role: file.role ?? "support"
1100
+ },
1101
+ role: "support",
1102
+ relationship: "co-located-file",
1103
+ visibility: context.defaultSupportFileVisibility
1104
+ })),
1105
+ metadata: { mimeType: files[0].mimeType },
1106
+ capabilities: [],
1107
+ warnings: ["no media bundle handler matched; returned unknown inspection"],
1108
+ errors: []
1109
+ };
1166
1110
  }
1167
- export {
1168
- FFmpegProcessor,
1169
- defaultMediaBundleHandlers,
1170
- genericImageBundleHandler,
1171
- genericVideoBundleHandler,
1172
- inspectMediaBundle,
1173
- insta360BundleHandler,
1174
- parseInsta360FileName
1175
- };
1176
- //# sourceMappingURL=index.js.map
1111
+ //#endregion
1112
+ export { FFmpegProcessor, defaultMediaBundleHandlers, genericImageBundleHandler, genericVideoBundleHandler, inspectMediaBundle, insta360BundleHandler, parseInsta360FileName };
1113
+
1114
+ //# sourceMappingURL=index.js.map