-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.js
More file actions
executable file
·1594 lines (1422 loc) · 50.1 KB
/
Copy pathweb.js
File metadata and controls
executable file
·1594 lines (1422 loc) · 50.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const path = require('path');
const { spawn, spawnSync } = require('child_process');
const REPO_ROOT = __dirname;
const WEB_ROOT = path.join(REPO_ROOT, 'web');
const UPLOAD_ROOT = path.join(REPO_ROOT, '.web-uploads');
const HOST = process.env.MM_WEB_HOST || '127.0.0.1';
const PORT = Number(process.env.MM_WEB_PORT || process.env.PORT || 3001);
const MAX_BODY_BYTES = 1024 * 1024;
const MAX_UPLOAD_BYTES = Number(process.env.MM_WEB_MAX_UPLOAD_BYTES || 500 * 1024 * 1024);
const SOURCE_INFO_TIMEOUT_MS = Number(process.env.MM_WEB_SOURCE_INFO_TIMEOUT_MS || 15000);
const LOCAL_VIDEO_INPUT_EXTS = ['gif', 'mov', 'mp4', 'webm'];
const LOCAL_VIDEO_INPUT_EXTS_WITH_DOTS = LOCAL_VIDEO_INPUT_EXTS.map(ext => `.${ext}`);
const PREVIEW_PROCESS_TIMEOUT_MS = Number(process.env.MM_WEB_PREVIEW_TIMEOUT_MS || 45000);
const MAX_REMOTE_PREVIEW_CACHE_ENTRIES = Number(process.env.MM_WEB_PREVIEW_CACHE_ENTRIES || 24);
const jobs = new Map();
const publicPaths = new Set();
const remotePreviewCache = new Map();
let defaultFontCache = null;
const MIME = {
'.css': 'text/css; charset=utf-8',
'.gif': 'image/gif',
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.mov': 'video/quicktime',
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4',
'.otf': 'font/otf',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ttc': 'font/collection',
'.ttf': 'font/ttf',
'.webm': 'video/webm'
};
function clean(value) {
return typeof value === 'string' ? value.trim() : '';
}
function basenameNoExt(value) {
return path.basename(clean(value)).replace(/\.[^.]+$/, '');
}
function required(fields, name, label = name) {
const value = clean(fields[name]);
if (!value) {
throw new Error(`${label} is required.`);
}
return value;
}
function optional(fields, name) {
return clean(fields[name]);
}
function optionalInteger(fields, name, label = name, fallback = '') {
const value = optional(fields, name) || fallback;
if (value && !/^[0-9]+$/.test(value)) {
throw new Error(`${label} must be a non-negative integer.`);
}
return value;
}
function optionalPositiveNumber(fields, name, label = name, fallback = '') {
const value = optional(fields, name) || fallback;
if (value && !/^[0-9]+(?:\.[0-9]+)?$/.test(value)) {
throw new Error(`${label} must be a positive number.`);
}
if (value && Number(value) <= 0) {
throw new Error(`${label} must be greater than zero.`);
}
return value;
}
function parseFrameBoundary(value, metadata, { allowBlank = true, label = 'Output boundary' } = {}) {
const raw = clean(value);
if (!raw) {
if (allowBlank) return null;
throw new Error(`${label} is required.`);
}
const frameMatch = raw.match(/^(?:#|frame\s*:?\s*)?([0-9]+)\s*(?:f|frames?)$/i)
|| raw.match(/^frame\s+([0-9]+)$/i);
if (frameMatch) {
const frame = Number(frameMatch[1]);
if (!Number.isInteger(frame) || frame < 0) {
throw new Error(`${label} frame must be a non-negative whole number.`);
}
const fps = Number(metadata && metadata.fps) || 0;
if (fps <= 0) {
throw new Error(`${label} uses a frame value, but source FPS is not available.`);
}
return { kind: 'frame', raw, frame, seconds: frame / fps };
}
return {
kind: 'time',
raw,
frame: null,
seconds: parseTimeValue(raw, { label })
};
}
function parseTimeValue(value, { allowBlank = false, allowInf = false, label = 'Time' } = {}) {
const raw = clean(value);
if (!raw) {
if (allowBlank) return null;
throw new Error(`${label} is required.`);
}
if (allowInf && raw.toLowerCase() === 'inf') return Infinity;
if (!/^[0-9]+(?::[0-9]+){0,2}(?:\.[0-9]+)?$/.test(raw)) {
throw new Error(`${label} must be seconds, MM:SS, HH:MM:SS, or ${allowInf ? 'inf' : 'a valid time'}.`);
}
const parts = raw.split(':');
const seconds = Number(parts[parts.length - 1]);
if (!Number.isFinite(seconds) || seconds < 0) {
throw new Error(`${label} must be a valid time.`);
}
if (parts.length > 1 && seconds >= 60) {
throw new Error(`${label} seconds must be less than 60 when using colon format.`);
}
let total = seconds;
if (parts.length >= 2) {
const minutes = Number(parts[parts.length - 2]);
if (!Number.isInteger(minutes) || minutes < 0 || minutes >= 60) {
throw new Error(`${label} minutes must be a whole number less than 60 when using colon format.`);
}
total += minutes * 60;
}
if (parts.length === 3) {
const hours = Number(parts[0]);
if (!Number.isInteger(hours) || hours < 0) {
throw new Error(`${label} hours must be a non-negative whole number.`);
}
total += hours * 3600;
}
return total;
}
function validateTimeRange(fields, { requireStart = true, allowBlankEnd = true } = {}) {
const start = requireStart ? required(fields, 'start', 'Start time') : optional(fields, 'start');
const end = optional(fields, 'end');
const startSeconds = parseTimeValue(start, { allowBlank: !requireStart, label: 'Start time' });
const endSeconds = parseTimeValue(end, { allowBlank: allowBlankEnd, allowInf: true, label: 'End time' });
if (startSeconds !== null && endSeconds !== null && endSeconds !== Infinity && startSeconds >= endSeconds) {
throw new Error('Start time must be before end time.');
}
return { start: start || '0:00', end };
}
function detectDefaultFont() {
if (defaultFontCache) return defaultFontCache;
const fallback = { name: 'system font', path: '' };
const candidates = [
'/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
'/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf',
'/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf',
'/usr/share/fonts/TTF/DejaVuSans-Bold.ttf',
'/usr/share/fonts/noto/NotoSans-Bold.ttf',
'/usr/share/fonts/TTF/LiberationSans-Bold.ttf',
'/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
'/System/Library/Fonts/SFNS.ttf',
'/System/Library/Fonts/HelveticaNeue.ttc',
'/System/Library/Fonts/Helvetica.ttc',
'/Library/Fonts/Arial Unicode.ttf',
'/System/Library/Fonts/Supplemental/Arial Bold.ttf'
];
const found = candidates.find(candidate => fs.existsSync(candidate));
if (found) {
defaultFontCache = { name: basenameNoExt(found), path: found };
return defaultFontCache;
}
const fc = spawnSync('fc-match', ['-f', '%{family}\n%{file}\n', 'sans-serif:weight=bold'], {
encoding: 'utf8',
timeout: 3000
});
if (!fc.error && fc.status === 0) {
const lines = fc.stdout.split('\n').map(line => clean(line)).filter(Boolean);
if (lines.length > 0) {
const name = lines[0].split(',')[0] || lines[0];
defaultFontCache = { name, path: lines[1] || '' };
return defaultFontCache;
}
}
defaultFontCache = fallback;
return defaultFontCache;
}
function safeStem(value, fallback = 'clip') {
const stem = clean(value).replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^_+|_+$/g, '');
return stem || fallback;
}
function safeSegment(value, fallback = 'file') {
return safeStem(value, fallback).replace(/^\.+/, '') || fallback;
}
function outputStem(value, fallback) {
return safeStem(path.basename(clean(value)).replace(/\.[^.]+$/, '') || fallback, fallback);
}
function repoPath(...parts) {
return path.join(REPO_ROOT, ...parts);
}
function spawnCommand(cmd, args) {
if (process.platform === 'win32' && path.extname(cmd).toLowerCase() === '.sh') {
return { cmd: 'bash', args: [cmd, ...args] };
}
return { cmd, args };
}
function repoRelativePath(outputPath) {
if (!outputPath) return null;
const resolved = path.resolve(REPO_ROOT, outputPath);
const rel = path.relative(REPO_ROOT, resolved);
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
return null;
}
return rel.split(path.sep).join('/');
}
function publicUrl(prefix, outputPath) {
const rel = repoRelativePath(outputPath);
if (!rel) return null;
publicPaths.add(rel);
return `${prefix}/${rel.split('/').map(encodeURIComponent).join('/')}`;
}
function publicFileUrl(outputPath) {
return publicUrl('/files', outputPath);
}
function publicDownloadUrl(outputPath) {
return publicUrl('/download', outputPath);
}
function extractYouTubeId(value) {
const raw = clean(value);
if (!raw) return '';
if (/^[A-Za-z0-9_-]{11}$/.test(raw)) return raw;
try {
const url = new URL(raw);
const host = url.hostname.replace(/^www\./, '');
let id = '';
if (host === 'youtu.be') {
id = url.pathname.split('/').filter(Boolean)[0] || '';
} else if (host === 'youtube.com' || host.endsWith('.youtube.com')) {
id = url.searchParams.get('v') || '';
if (!id) {
const parts = url.pathname.split('/').filter(Boolean);
const marker = parts.findIndex(part => ['shorts', 'embed', 'v'].includes(part));
if (marker >= 0) id = parts[marker + 1] || '';
}
}
id = clean(id).split(/[?&#/]/)[0];
return /^[A-Za-z0-9_-]{11}$/.test(id) ? id : '';
} catch {
return '';
}
}
function looksLikeUrl(value) {
return /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(clean(value));
}
function sourceFallbackStem(value, fallback = 'media') {
const raw = clean(value);
const ytId = extractYouTubeId(raw);
if (ytId) return safeStem(ytId, fallback);
if (looksLikeUrl(raw)) {
try {
const url = new URL(raw);
const pathStem = safeStem(path.posix.basename(url.pathname).replace(/\.[^.]+$/, ''), '');
return pathStem || safeStem(url.hostname.replace(/^www\./, ''), fallback);
} catch {
return safeStem(raw, fallback);
}
}
return safeStem(path.basename(raw).replace(/\.[^.]+$/, ''), fallback);
}
function ytDlpSource(value) {
const raw = clean(value);
const ytId = extractYouTubeId(raw);
if (ytId) return ytId;
if (looksLikeUrl(raw)) return raw;
throw new Error('Source must be a local file, a YouTube ID, or a supported media URL.');
}
function ytDlpProbeSource(value) {
const raw = clean(value);
const ytId = extractYouTubeId(raw);
if (ytId) return `https://www.youtube.com/watch?v=${ytId}`;
if (looksLikeUrl(raw)) return raw;
throw new Error('Source must be a local file, a YouTube ID, or a supported media URL.');
}
function isFalseEnv(value) {
return /^(?:0|false|no|off)$/i.test(clean(value));
}
function ytDlpNetworkArgs() {
const args = [];
if (!isFalseEnv(process.env.MM_YTDLP_FORCE_IPV4 || '1')) {
args.push('--force-ipv4');
}
const socketTimeout = clean(process.env.MM_YTDLP_SOCKET_TIMEOUT || '15');
if (socketTimeout && socketTimeout !== '0') {
args.push('--socket-timeout', socketTimeout);
}
return args;
}
function resolveJobSource(value, label = 'Source') {
const raw = clean(value);
if (!raw) {
throw new Error(`${label} is required.`);
}
const resolved = path.resolve(REPO_ROOT, raw);
if (fs.existsSync(resolved)) {
return resolved;
}
return ytDlpSource(raw);
}
function isLocalSource(value) {
const raw = clean(value);
return Boolean(raw && fs.existsSync(path.resolve(REPO_ROOT, raw)));
}
function defaultDirForExt(ext) {
switch (ext) {
case 'gif': return 'gifs';
case 'mp3': return 'Audio';
case 'png': return 'frames';
case 'mp4':
case 'webm':
default:
return 'videos';
}
}
function normalizeOutputPath(value, { defaultExt, allowedExts, fallbackStem, defaultDir }) {
const raw = clean(value).replaceAll('\\', '/');
const allowed = allowedExts || [defaultExt];
const fallback = safeStem(fallbackStem, 'output');
const baseDir = defaultDir || defaultDirForExt(defaultExt);
if (!raw) {
return `${baseDir}/${fallback}.${defaultExt}`;
}
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(raw) || raw.startsWith('/')) {
throw new Error('Output paths must be relative to this project.');
}
const parts = raw.split('/').filter(Boolean);
if (parts.some(part => part === '.' || part === '..')) {
throw new Error('Output paths cannot contain . or .. segments.');
}
let filename = parts.pop() || fallback;
const parsed = path.posix.parse(filename);
const ext = parsed.ext ? parsed.ext.slice(1).toLowerCase() : '';
const finalExt = allowed.includes(ext) ? ext : defaultExt;
const rawName = ext ? parsed.name : filename;
filename = `${safeSegment(rawName, fallback)}.${finalExt}`;
const dirs = parts.map((part, index) => safeSegment(part, `folder${index + 1}`));
if (dirs.length === 0) {
dirs.push(defaultDir || defaultDirForExt(finalExt));
}
return path.posix.join(...dirs, filename);
}
function normalizeVideoOutput(out, fallbackStem = 'clip', fallbackFormat = 'mp4') {
return normalizeOutputPath(out, {
defaultExt: fallbackFormat,
allowedExts: ['mp4', 'webm'],
fallbackStem,
defaultDir: 'videos'
});
}
function normalizeMediaOutput(out, format, fallbackStem = 'media') {
validateFormat(format, ['gif', 'mp3', 'mp4', 'webm']);
return normalizeOutputPath(out, {
defaultExt: format,
allowedExts: [format],
fallbackStem,
defaultDir: defaultDirForExt(format)
});
}
function outputExt(outputPath) {
return path.posix.extname(outputPath).slice(1).toLowerCase();
}
function uploadName(originalName) {
const parsed = path.parse(clean(originalName) || 'upload');
const base = safeSegment(parsed.name, 'upload');
const ext = parsed.ext ? parsed.ext.toLowerCase().replace(/[^.A-Za-z0-9]/g, '') : '';
return `${Date.now()}-${crypto.randomUUID()}-${base}${ext}`;
}
function resolveInputPath(value, label = 'Input') {
const raw = clean(value);
if (!raw) {
throw new Error(`${label} is required.`);
}
const resolved = path.resolve(REPO_ROOT, raw);
if (!fs.existsSync(resolved)) {
throw new Error(`${label} not found: ${raw}`);
}
return resolved;
}
function validateMediaInputExtension(value, allowed, label = 'Input media') {
const ext = path.extname(clean(value)).slice(1).toLowerCase();
if (!allowed.includes(ext)) {
throw new Error(`${label} must be one of: ${allowed.map(item => item.toUpperCase()).join(', ')}.`);
}
}
function localFrameMetadata(inputPath) {
const probe = spawnSync('ffprobe', [
'-v', 'error',
'-show_entries', 'format=duration:stream=codec_type,width,height,avg_frame_rate,r_frame_rate,nb_frames',
'-of', 'json',
inputPath
], {
encoding: 'utf8',
timeout: 5000
});
if (probe.error || probe.status !== 0) {
return {};
}
try {
const info = JSON.parse(probe.stdout || '{}');
const duration = Number(info.format && info.format.duration);
return mediaFrameInfo(Array.isArray(info.streams) ? info.streams : [], duration);
} catch {
return {};
}
}
function parseCropFields(fields, metadata = {}) {
const rawX = optional(fields, 'cropX');
const rawY = optional(fields, 'cropY');
const rawWidth = optional(fields, 'cropWidth');
const rawHeight = optional(fields, 'cropHeight');
if (!rawX && !rawY && !rawWidth && !rawHeight) return null;
const x = Number(optionalInteger(fields, 'cropX', 'Crop x', '0'));
const y = Number(optionalInteger(fields, 'cropY', 'Crop y', '0'));
const width = Number(optionalInteger(fields, 'cropWidth', 'Crop width', '0'));
const height = Number(optionalInteger(fields, 'cropHeight', 'Crop height', '0'));
if (width === 0 && height === 0) return null;
if (width <= 0 || height <= 0) {
throw new Error('Crop width and height must be greater than zero.');
}
const sourceWidth = Number(metadata.width) || 0;
const sourceHeight = Number(metadata.height) || 0;
if (sourceWidth > 0 && sourceHeight > 0) {
if (x >= sourceWidth || y >= sourceHeight || x + width > sourceWidth || y + height > sourceHeight) {
throw new Error('Crop area must stay inside the input media.');
}
if (x === 0 && y === 0 && width === sourceWidth && height === sourceHeight) {
return null;
}
}
return { x, y, width, height };
}
function addCaptionOptions(args, fields) {
const options = [
['topY', '--top-y'],
['bottomY', '--bottom-y'],
['fontSize', '--font-size'],
['width', '--width']
];
for (const [field, flag] of options) {
const value = optional(fields, field);
if (value) {
if (!/^[0-9]+$/.test(value)) {
throw new Error(`${flag} must be a non-negative integer.`);
}
args.push(flag, value);
}
}
}
function addFontOptions(args, fields) {
const family = optional(fields, 'fontFamily');
const style = optional(fields, 'fontStyle');
if (family) args.push('--font-family', family);
if (style === 'bold' || style === 'bold-italic') args.push('--bold');
if (style === 'italic' || style === 'bold-italic') args.push('--italic');
}
function addPerLineFontOptions(args, fields) {
const topFamily = optional(fields, 'topFontFamily');
const topSize = optionalInteger(fields, 'topFontSize', 'Top font size');
const topStyle = optional(fields, 'topFontStyle');
const bottomFamily = optional(fields, 'bottomFontFamily');
const bottomSize = optionalInteger(fields, 'bottomFontSize', 'Bottom font size');
const bottomStyle = optional(fields, 'bottomFontStyle');
if (topFamily) args.push('--top-font-family', topFamily);
if (topSize) args.push('--top-font-size', topSize);
if (topStyle === 'bold' || topStyle === 'bold-italic') args.push('--top-bold');
if (topStyle === 'italic' || topStyle === 'bold-italic') args.push('--top-italic');
if (bottomFamily) args.push('--bottom-font-family', bottomFamily);
if (bottomSize) args.push('--bottom-font-size', bottomSize);
if (bottomStyle === 'bold' || bottomStyle === 'bold-italic') args.push('--bottom-bold');
if (bottomStyle === 'italic' || bottomStyle === 'bold-italic') args.push('--bottom-italic');
}
function validateFormat(format, allowed) {
if (!allowed.includes(format)) {
throw new Error(`Format must be one of: ${allowed.join(', ')}.`);
}
}
function runProcess(cmd, args, options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, {
cwd: options.cwd || REPO_ROOT,
env: process.env,
stdio: ['ignore', 'ignore', 'pipe'],
detached: canSignalProcessGroup() && options.detached !== false
});
let stderr = '';
let settled = false;
let timeout = null;
let killTimeout = null;
function clearTimers() {
if (timeout) clearTimeout(timeout);
if (killTimeout) clearTimeout(killTimeout);
timeout = null;
killTimeout = null;
}
const timeoutMs = Number(options.timeoutMs || 0);
if (timeoutMs > 0) {
timeout = setTimeout(() => {
if (settled) return;
settled = true;
signalChildTree(child, 'SIGTERM');
killTimeout = setTimeout(() => signalChildTree(child, 'SIGKILL'), 2000);
if (typeof killTimeout.unref === 'function') killTimeout.unref();
reject(new Error(`${path.basename(cmd)} timed out after ${timeoutMs}ms.`));
}, timeoutMs);
if (typeof timeout.unref === 'function') timeout.unref();
}
child.stderr.on('data', chunk => {
stderr += chunk.toString();
if (stderr.length > 20000) stderr = stderr.slice(-20000);
});
child.on('error', err => {
clearTimers();
if (settled) return;
settled = true;
reject(err);
});
child.on('close', code => {
clearTimers();
if (settled) return;
settled = true;
if (code === 0) {
resolve();
} else {
reject(new Error(stderr.trim() || `${path.basename(cmd)} exited with ${code}`));
}
});
});
}
function canSignalProcessGroup() {
return process.platform !== 'win32';
}
function signalChildTree(child, signal = 'SIGTERM') {
if (!child || !child.pid) return false;
try {
if (canSignalProcessGroup()) {
process.kill(-child.pid, signal);
} else {
child.kill(signal);
}
return true;
} catch (err) {
if (err && err.code === 'ESRCH') return false;
throw err;
}
}
function runCapture(cmd, args, options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, {
cwd: options.cwd || REPO_ROOT,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe']
});
let stdout = '';
let stderr = '';
let settled = false;
const timeoutMs = options.timeoutMs || SOURCE_INFO_TIMEOUT_MS;
const timeout = setTimeout(() => {
if (settled) return;
settled = true;
child.kill('SIGTERM');
reject(new Error(`${path.basename(cmd)} timed out after ${timeoutMs}ms.`));
}, timeoutMs);
child.stdout.on('data', chunk => {
stdout += chunk.toString();
if (stdout.length > 2 * 1024 * 1024) stdout = stdout.slice(-2 * 1024 * 1024);
});
child.stderr.on('data', chunk => {
stderr += chunk.toString();
if (stderr.length > 20000) stderr = stderr.slice(-20000);
});
child.on('error', err => {
if (settled) return;
settled = true;
clearTimeout(timeout);
reject(err);
});
child.on('close', code => {
if (settled) return;
settled = true;
clearTimeout(timeout);
if (code === 0) {
resolve({ stdout, stderr });
} else {
reject(new Error(stderr.trim() || `${path.basename(cmd)} exited with ${code}`));
}
});
});
}
function durationLabel(seconds) {
if (seconds === null || seconds === undefined || seconds === '') return '';
const value = Number(seconds);
if (!Number.isFinite(value) || value < 0) return '';
const total = Math.round(value);
const hrs = Math.floor(total / 3600);
const mins = Math.floor((total % 3600) / 60);
const secs = total % 60;
if (hrs > 0) {
return `${hrs}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
}
return `${mins}:${String(secs).padStart(2, '0')}`;
}
function safeDecodeURIComponent(value) {
try {
return decodeURIComponent(value);
} catch {
return null;
}
}
function parseFrameRate(value) {
const raw = clean(value);
if (!raw || raw === '0/0') return null;
if (raw.includes('/')) {
const [numerator, denominator] = raw.split('/').map(Number);
if (Number.isFinite(numerator) && Number.isFinite(denominator) && denominator > 0) {
const rate = numerator / denominator;
return rate > 0 ? rate : null;
}
return null;
}
const rate = Number(raw);
return Number.isFinite(rate) && rate > 0 ? rate : null;
}
function positiveNumber(...values) {
for (const value of values) {
const number = Number(value);
if (Number.isFinite(number) && number > 0) return number;
}
return null;
}
function mediaFrameInfo(streams, duration) {
const video = (Array.isArray(streams) ? streams : []).find(stream => stream.codec_type === 'video') || {};
const fps = parseFrameRate(video.avg_frame_rate) || parseFrameRate(video.r_frame_rate);
const exactFrames = Number(video.nb_frames);
const estimatedFrames = Number.isFinite(duration) && fps ? Math.round(duration * fps) : null;
const frameCount = Number.isFinite(exactFrames) && exactFrames > 0 ? exactFrames : estimatedFrames;
return {
width: Number(video.width) || null,
height: Number(video.height) || null,
fps,
frameCount: Number.isFinite(frameCount) && frameCount > 0 ? frameCount : null
};
}
function remoteMediaInfo(info, raw, remote) {
const formats = Array.isArray(info.formats) ? info.formats : [];
const bestVideo = formats
.filter(format => positiveNumber(format.width) && positiveNumber(format.height))
.sort((a, b) => {
const aArea = positiveNumber(a.width) * positiveNumber(a.height);
const bArea = positiveNumber(b.width) * positiveNumber(b.height);
return bArea - aArea;
})[0] || {};
const duration = positiveNumber(info.duration);
const fps = positiveNumber(info.fps, bestVideo.fps);
const width = positiveNumber(info.width, bestVideo.width);
const height = positiveNumber(info.height, bestVideo.height);
const frameCount = duration && fps ? Math.round(duration * fps) : null;
const defaultStem = safeStem(info.id || info.display_id || info.title || sourceFallbackStem(raw), sourceFallbackStem(raw));
return {
ok: true,
supported: true,
kind: 'remote',
source: remote,
title: info.title || '',
id: info.id || info.display_id || extractYouTubeId(raw) || '',
extractor: info.extractor_key || info.extractor || '',
webpageUrl: info.webpage_url || remote,
defaultStem,
duration,
durationLabel: durationLabel(duration),
width,
height,
fps,
frameCount: Number.isFinite(frameCount) && frameCount > 0 ? frameCount : null
};
}
function remoteFrameMetadata(value) {
const remote = ytDlpProbeSource(value);
const probe = spawnSync('yt-dlp', [
...ytDlpNetworkArgs(),
'--dump-single-json',
'--skip-download',
'--no-warnings',
'--no-playlist',
remote
], {
encoding: 'utf8',
timeout: SOURCE_INFO_TIMEOUT_MS
});
if (probe.error || probe.status !== 0) {
return {};
}
try {
const info = remoteMediaInfo(JSON.parse(probe.stdout || '{}'), value, remote);
return {
width: info.width,
height: info.height,
fps: info.fps,
frameCount: info.frameCount
};
} catch {
return {};
}
}
async function sourceInfo(value) {
const raw = required({ value }, 'value', 'Source');
const resolved = path.resolve(REPO_ROOT, raw);
if (fs.existsSync(resolved)) {
const { stdout } = await runCapture('ffprobe', [
'-v', 'error',
'-show_entries', 'format=duration,format_name:stream=codec_type,codec_name,width,height,avg_frame_rate,r_frame_rate,nb_frames',
'-of', 'json',
resolved
]);
const info = JSON.parse(stdout || '{}');
const duration = Number(info.format && info.format.duration);
const streams = Array.isArray(info.streams) ? info.streams : [];
const frameInfo = mediaFrameInfo(streams, duration);
return {
ok: true,
supported: true,
kind: 'local',
source: raw,
title: path.basename(resolved),
defaultStem: sourceFallbackStem(raw),
duration: Number.isFinite(duration) ? duration : null,
durationLabel: durationLabel(duration),
width: frameInfo.width,
height: frameInfo.height,
fps: frameInfo.fps,
frameCount: frameInfo.frameCount,
format: info.format && info.format.format_name || '',
streams
};
}
const remote = ytDlpProbeSource(raw);
const { stdout } = await runCapture('yt-dlp', [
...ytDlpNetworkArgs(),
'--dump-single-json',
'--skip-download',
'--no-warnings',
'--no-playlist',
remote
]);
const info = JSON.parse(stdout || '{}');
return remoteMediaInfo(info, raw, remote);
}
async function downloadRemotePreviewClip(input, seconds) {
const dir = path.join(UPLOAD_ROOT, 'previews');
fs.mkdirSync(dir, { recursive: true });
const target = path.join(dir, `${Date.now()}-${crypto.randomUUID()}-remote.mp4`);
const remote = ytDlpProbeSource(input);
const requestedSeconds = Math.max(0, Number(seconds) || 0);
const start = Math.floor(requestedSeconds);
const end = start + 1;
const cacheKey = `${remote}\n${start}`;
const cached = remotePreviewCache.get(cacheKey);
if (cached && fs.existsSync(cached.path)) {
const stat = fs.statSync(cached.path);
if (stat.isFile() && stat.size > 0) {
cached.lastUsed = Date.now();
return {
path: cached.path,
seekSeconds: Math.max(0, requestedSeconds - start)
};
}
remotePreviewCache.delete(cacheKey);
}
const args = [
...ytDlpNetworkArgs(),
'-f', 'bv*[ext=mp4]+ba/b[ext=mp4]/bv*+ba/best',
'--merge-output-format', 'mp4',
'--force-overwrites',
'--no-playlist',
'-o', target,
'--download-sections', `*${start}-${end}`,
'--force-keyframes-at-cuts',
remote
];
await runProcess('yt-dlp', args, { timeoutMs: PREVIEW_PROCESS_TIMEOUT_MS });
let mediaPath = target;
if (!fs.existsSync(target) && fs.existsSync(`${target}.mp4`)) {
mediaPath = `${target}.mp4`;
}
const stat = fs.existsSync(mediaPath) ? fs.statSync(mediaPath) : null;
if (!stat || !stat.isFile() || stat.size === 0) {
throw new Error('yt-dlp produced no preview media for this source.');
}
remotePreviewCache.set(cacheKey, {
path: mediaPath,
createdAt: Date.now(),
lastUsed: Date.now()
});
pruneRemotePreviewCache();
return {
path: mediaPath,
seekSeconds: Math.max(0, requestedSeconds - start)
};
}
async function createPreviewFrame(input, time = '0') {
const seconds = parseTimeValue(time, { allowBlank: true, label: 'Preview time' }) || 0;
const local = isLocalSource(input);
let source;
let cleanupSource = '';
let seekSeconds = seconds;
if (local) {
source = resolveInputPath(input, 'Preview input');
const ext = path.extname(source).toLowerCase();
if (!LOCAL_VIDEO_INPUT_EXTS_WITH_DOTS.includes(ext)) {
throw new Error('Preview input must be a supported URL or a GIF, MOV, MP4, or WebM file.');
}
} else {
const previewClip = await downloadRemotePreviewClip(input, seconds);
source = previewClip.path;
seekSeconds = previewClip.seekSeconds;
}
const dir = path.join(UPLOAD_ROOT, 'previews');
fs.mkdirSync(dir, { recursive: true });
const target = path.join(dir, `${Date.now()}-${crypto.randomUUID()}.png`);
const args = ['-y'];
if (seekSeconds > 0) args.push('-ss', String(seekSeconds));
args.push('-i', source, '-frames:v', '1', '-update', '1', target);
try {
await runProcess('ffmpeg', args, { timeoutMs: PREVIEW_PROCESS_TIMEOUT_MS });
} finally {
if (cleanupSource) fs.rm(cleanupSource, { force: true }, () => {});
}
const rel = path.relative(REPO_ROOT, target).split(path.sep).join('/');
return {
path: rel,
fileUrl: publicFileUrl(rel)
};
}
function pruneRemotePreviewCache() {
const maxEntries = Math.max(0, Number(MAX_REMOTE_PREVIEW_CACHE_ENTRIES) || 0);
if (maxEntries === 0) {
for (const entry of remotePreviewCache.values()) {
fs.rm(entry.path, { force: true }, () => {});
}
remotePreviewCache.clear();
return;
}
for (const [key, entry] of remotePreviewCache) {
if (!fs.existsSync(entry.path)) remotePreviewCache.delete(key);
}
const entries = [...remotePreviewCache.entries()]
.sort((a, b) => (a[1].lastUsed || 0) - (b[1].lastUsed || 0));
while (entries.length > maxEntries) {
const [key, entry] = entries.shift();
remotePreviewCache.delete(key);
fs.rm(entry.path, { force: true }, () => {});
}
}
function buildJob(action, fields) {
const data = fields && typeof fields === 'object' ? fields : {};
switch (action) {
case 'download-convert': {
const sourceRaw = required(data, 'source', 'Source');
const source = resolveJobSource(sourceRaw);
const { start, end } = validateTimeRange(data);
const format = optional(data, 'format') || 'mp4';
validateFormat(format, ['gif', 'mp3', 'mp4', 'webm']);
const output = normalizeMediaOutput(optional(data, 'output'), format, sourceFallbackStem(sourceRaw));
return {
cmd: repoPath('convert.sh'),
args: [source, start, end, format, output],
outputPath: output
};
}
case 'text-to-media': {
const sourceRaw = required(data, 'source', 'Source');
const source = resolveJobSource(sourceRaw);
const sourceIsLocal = isLocalSource(sourceRaw);
const { start, end } = validateTimeRange(data);
const format = optional(data, 'format') || 'gif';
validateFormat(format, ['gif', 'mp4', 'webm']);
const fallbackStem = `${sourceFallbackStem(sourceRaw)}-captioned`;
const output = normalizeMediaOutput(optional(data, 'outputName') || optional(data, 'output'), format, fallbackStem);
const top = typeof data.topText === 'string' ? data.topText : '';
const bottom = typeof data.bottomText === 'string' ? data.bottomText : '';
const font = optional(data, 'fontPath');
const args = [];
addCaptionOptions(args, data);
addFontOptions(args, data);
addPerLineFontOptions(args, data);
if (sourceIsLocal) {
args.unshift('--caption-local');
args.push('--start', start);
if (end) args.push('--end', end);
args.push(source, output, top, bottom);