@torrent-tv/proxy 2.81.2 → 2.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/package.json +1 -1
- package/server.js +38 -19
- package/services/encode/Encoder.js +27 -0
- package/services/encode/QsvEncoder.js +6 -0
- package/services/encode/SoftwareEncoder.js +5 -0
- package/services/encode/VaapiEncoder.js +8 -0
- package/services/encode/run-costs.js +37 -2
- package/services/encode/start-stop-cost.js +174 -0
- package/services/hls-session-manager.js +6 -0
- package/services/hwaccel.js +1850 -1843
- package/services/orchestrators/EncodeOrchestrator.js +11 -0
- package/test/startup-readings.test.js +119 -0
package/services/hwaccel.js
CHANGED
|
@@ -1,1843 +1,1850 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file Hardware-accelerated H.264 encoder auto-detection.
|
|
3
|
-
*
|
|
4
|
-
* Probes the ffmpeg build and the host for a usable hardware H.264 encoder
|
|
5
|
-
* (NVENC / QSV / VAAPI / V4L2 M2M), verifying each candidate with a real
|
|
6
|
-
* test-encode before selecting it. Falls back to software libx264 when no
|
|
7
|
-
* hardware encoder is present or working.
|
|
8
|
-
*
|
|
9
|
-
* Deployment-agnostic: relies only on ffmpeg, the filesystem and
|
|
10
|
-
* `process.platform`; makes no assumptions about Home Assistant or any
|
|
11
|
-
* specific host. A garbled or unsupported hardware path simply fails its
|
|
12
|
-
* test-encode and is skipped, so the worst case is software encoding.
|
|
13
|
-
*
|
|
14
|
-
* A descriptor exposes:
|
|
15
|
-
* - `name` human-readable encoder id (e.g. "h264_vaapi")
|
|
16
|
-
* - `kind` "software" | "vaapi" | "qsv" | "nvenc" | "v4l2m2m"
|
|
17
|
-
* - `device` device node path or null
|
|
18
|
-
* - `inputArgs` ffmpeg args inserted before `-i` (decode/hwaccel setup)
|
|
19
|
-
* - `buildVideoArgs({ targetWidth, targetHeight, segmentDurationSec })`
|
|
20
|
-
* ffmpeg video filter + encoder args inserted after `-map`s
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
import { spawn } from "node:child_process";
|
|
24
|
-
import { mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
25
|
-
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
26
|
-
import os from "node:os";
|
|
27
|
-
import path from "node:path";
|
|
28
|
-
import { fitDecodeCost } from "./decode-cost-fit.js";
|
|
29
|
-
import { penaltiesFrom } from "./encode/contention.js";
|
|
30
|
-
import { fileURLToPath } from "node:url";
|
|
31
|
-
import {
|
|
32
|
-
parseFfmpegBitrateKbps,
|
|
33
|
-
parseFfmpegDurationSeconds,
|
|
34
|
-
parseFfmpegVideoDimensions,
|
|
35
|
-
parseFfmpegVideoFps
|
|
36
|
-
} from "./ffmpeg-banner.js";
|
|
37
|
-
|
|
38
|
-
import { keyFrameArgs,
|
|
39
|
-
// The five kinds, one class each. Detection and benchmarking stay in this file;
|
|
40
|
-
// how a kind is driven belongs to the kind.
|
|
41
|
-
import {
|
|
42
|
-
NvencEncoder,
|
|
43
|
-
QsvEncoder,
|
|
44
|
-
SoftwareEncoder,
|
|
45
|
-
V4l2m2mEncoder,
|
|
46
|
-
VaapiEncoder
|
|
47
|
-
} from "./encode/index.js";
|
|
48
|
-
// Re-exported so every caller goes on importing these figures from here:
|
|
49
|
-
// the same calculation, moved to sit beside the encoder kinds built from it.
|
|
50
|
-
export {
|
|
51
|
-
chooseOutputFps,
|
|
52
|
-
maxrateKbpsFor,
|
|
53
|
-
nominalKbpsForHeight,
|
|
54
|
-
nominalKbpsForMaxrate,
|
|
55
|
-
TRANSCODE_FPS
|
|
56
|
-
} from "./encode/args.js";
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
*/
|
|
71
|
-
const
|
|
72
|
-
/**
|
|
73
|
-
const
|
|
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
|
-
* @property {string}
|
|
145
|
-
* @property {
|
|
146
|
-
* @property {string|null}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
* @param {
|
|
155
|
-
* @
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
let
|
|
162
|
-
let
|
|
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
|
-
return
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
return
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
*
|
|
235
|
-
*
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
*
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
* @param {
|
|
242
|
-
* @
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
const
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
/** @type {string[]} */
|
|
252
|
-
let
|
|
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
|
-
const
|
|
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
|
-
const
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
//
|
|
423
|
-
//
|
|
424
|
-
//
|
|
425
|
-
//
|
|
426
|
-
//
|
|
427
|
-
//
|
|
428
|
-
//
|
|
429
|
-
//
|
|
430
|
-
//
|
|
431
|
-
// the
|
|
432
|
-
//
|
|
433
|
-
//
|
|
434
|
-
//
|
|
435
|
-
//
|
|
436
|
-
//
|
|
437
|
-
//
|
|
438
|
-
//
|
|
439
|
-
//
|
|
440
|
-
//
|
|
441
|
-
//
|
|
442
|
-
//
|
|
443
|
-
//
|
|
444
|
-
//
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
"cal-h264-
|
|
450
|
-
"cal-h264-
|
|
451
|
-
"cal-h264-
|
|
452
|
-
"cal-h264-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
"cal-hevc-
|
|
458
|
-
"cal-hevc-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
"cal-hevc10-
|
|
464
|
-
"cal-hevc10-
|
|
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
|
-
const
|
|
500
|
-
const
|
|
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
|
-
/** @type {
|
|
579
|
-
const
|
|
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
|
-
const
|
|
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
|
-
const
|
|
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
|
-
* outputs
|
|
779
|
-
*
|
|
780
|
-
*
|
|
781
|
-
*
|
|
782
|
-
*
|
|
783
|
-
*
|
|
784
|
-
*
|
|
785
|
-
*
|
|
786
|
-
*
|
|
787
|
-
*
|
|
788
|
-
* @param {string}
|
|
789
|
-
* @
|
|
790
|
-
*
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
//
|
|
797
|
-
//
|
|
798
|
-
//
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
const
|
|
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
|
-
const
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
*
|
|
885
|
-
*
|
|
886
|
-
*
|
|
887
|
-
* @param {
|
|
888
|
-
* @
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
let
|
|
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
|
-
* starting
|
|
933
|
-
*
|
|
934
|
-
*
|
|
935
|
-
*
|
|
936
|
-
*
|
|
937
|
-
*
|
|
938
|
-
*
|
|
939
|
-
* and
|
|
940
|
-
*
|
|
941
|
-
*
|
|
942
|
-
*
|
|
943
|
-
*
|
|
944
|
-
*
|
|
945
|
-
* the
|
|
946
|
-
*
|
|
947
|
-
*
|
|
948
|
-
*
|
|
949
|
-
*
|
|
950
|
-
*
|
|
951
|
-
*
|
|
952
|
-
*
|
|
953
|
-
*
|
|
954
|
-
*
|
|
955
|
-
*
|
|
956
|
-
*
|
|
957
|
-
*
|
|
958
|
-
*
|
|
959
|
-
*
|
|
960
|
-
*
|
|
961
|
-
*
|
|
962
|
-
* @param {string}
|
|
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
|
-
|
|
1001
|
-
|
|
1002
|
-
let
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
//
|
|
1007
|
-
//
|
|
1008
|
-
//
|
|
1009
|
-
//
|
|
1010
|
-
//
|
|
1011
|
-
//
|
|
1012
|
-
//
|
|
1013
|
-
//
|
|
1014
|
-
//
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
//
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
//
|
|
1051
|
-
//
|
|
1052
|
-
//
|
|
1053
|
-
//
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
const
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
//
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
//
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
child.stdin.on("
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
*
|
|
1148
|
-
*
|
|
1149
|
-
*
|
|
1150
|
-
*
|
|
1151
|
-
* @
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
*
|
|
1173
|
-
*
|
|
1174
|
-
*
|
|
1175
|
-
*
|
|
1176
|
-
*
|
|
1177
|
-
*
|
|
1178
|
-
*
|
|
1179
|
-
*
|
|
1180
|
-
*
|
|
1181
|
-
*
|
|
1182
|
-
*
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
//
|
|
1201
|
-
//
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
*
|
|
1215
|
-
*
|
|
1216
|
-
*
|
|
1217
|
-
*
|
|
1218
|
-
*
|
|
1219
|
-
*
|
|
1220
|
-
*
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
//
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
//
|
|
1255
|
-
//
|
|
1256
|
-
//
|
|
1257
|
-
//
|
|
1258
|
-
//
|
|
1259
|
-
//
|
|
1260
|
-
//
|
|
1261
|
-
//
|
|
1262
|
-
//
|
|
1263
|
-
//
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
*
|
|
1277
|
-
*
|
|
1278
|
-
*
|
|
1279
|
-
*
|
|
1280
|
-
* swarm
|
|
1281
|
-
*
|
|
1282
|
-
*
|
|
1283
|
-
*
|
|
1284
|
-
*
|
|
1285
|
-
*
|
|
1286
|
-
*
|
|
1287
|
-
*
|
|
1288
|
-
*
|
|
1289
|
-
*
|
|
1290
|
-
*
|
|
1291
|
-
*
|
|
1292
|
-
* @
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
*
|
|
1302
|
-
*
|
|
1303
|
-
*
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
*
|
|
1314
|
-
*
|
|
1315
|
-
*
|
|
1316
|
-
*
|
|
1317
|
-
*
|
|
1318
|
-
*
|
|
1319
|
-
*
|
|
1320
|
-
*
|
|
1321
|
-
*
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
//
|
|
1329
|
-
//
|
|
1330
|
-
//
|
|
1331
|
-
//
|
|
1332
|
-
//
|
|
1333
|
-
// and
|
|
1334
|
-
//
|
|
1335
|
-
//
|
|
1336
|
-
//
|
|
1337
|
-
//
|
|
1338
|
-
//
|
|
1339
|
-
//
|
|
1340
|
-
// it
|
|
1341
|
-
//
|
|
1342
|
-
//
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
//
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
}
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
*
|
|
1387
|
-
*
|
|
1388
|
-
*
|
|
1389
|
-
*
|
|
1390
|
-
*
|
|
1391
|
-
*
|
|
1392
|
-
*
|
|
1393
|
-
*
|
|
1394
|
-
*
|
|
1395
|
-
*
|
|
1396
|
-
*
|
|
1397
|
-
*
|
|
1398
|
-
* @
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
* Video seconds
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
*
|
|
1405
|
-
*
|
|
1406
|
-
*
|
|
1407
|
-
*
|
|
1408
|
-
*
|
|
1409
|
-
*
|
|
1410
|
-
*
|
|
1411
|
-
*
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
"-
|
|
1437
|
-
"-
|
|
1438
|
-
"-
|
|
1439
|
-
"-
|
|
1440
|
-
"-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
}
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
}
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
}
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
}
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
*
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
*
|
|
1574
|
-
*
|
|
1575
|
-
*
|
|
1576
|
-
*
|
|
1577
|
-
*
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
*
|
|
1581
|
-
*
|
|
1582
|
-
*
|
|
1583
|
-
*
|
|
1584
|
-
*
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
}
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
*
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
}
|
|
1670
|
-
const
|
|
1671
|
-
|
|
1672
|
-
if (
|
|
1673
|
-
|
|
1674
|
-
}
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
*
|
|
1689
|
-
*
|
|
1690
|
-
*
|
|
1691
|
-
*
|
|
1692
|
-
*
|
|
1693
|
-
*
|
|
1694
|
-
*
|
|
1695
|
-
*
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
*
|
|
1735
|
-
*
|
|
1736
|
-
*
|
|
1737
|
-
*
|
|
1738
|
-
*
|
|
1739
|
-
*
|
|
1740
|
-
*
|
|
1741
|
-
*
|
|
1742
|
-
*
|
|
1743
|
-
*
|
|
1744
|
-
*
|
|
1745
|
-
*
|
|
1746
|
-
*
|
|
1747
|
-
*
|
|
1748
|
-
*
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
)
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
//
|
|
1788
|
-
//
|
|
1789
|
-
|
|
1790
|
-
//
|
|
1791
|
-
//
|
|
1792
|
-
"-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
}
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
}
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @file Hardware-accelerated H.264 encoder auto-detection.
|
|
3
|
+
*
|
|
4
|
+
* Probes the ffmpeg build and the host for a usable hardware H.264 encoder
|
|
5
|
+
* (NVENC / QSV / VAAPI / V4L2 M2M), verifying each candidate with a real
|
|
6
|
+
* test-encode before selecting it. Falls back to software libx264 when no
|
|
7
|
+
* hardware encoder is present or working.
|
|
8
|
+
*
|
|
9
|
+
* Deployment-agnostic: relies only on ffmpeg, the filesystem and
|
|
10
|
+
* `process.platform`; makes no assumptions about Home Assistant or any
|
|
11
|
+
* specific host. A garbled or unsupported hardware path simply fails its
|
|
12
|
+
* test-encode and is skipped, so the worst case is software encoding.
|
|
13
|
+
*
|
|
14
|
+
* A descriptor exposes:
|
|
15
|
+
* - `name` human-readable encoder id (e.g. "h264_vaapi")
|
|
16
|
+
* - `kind` "software" | "vaapi" | "qsv" | "nvenc" | "v4l2m2m"
|
|
17
|
+
* - `device` device node path or null
|
|
18
|
+
* - `inputArgs` ffmpeg args inserted before `-i` (decode/hwaccel setup)
|
|
19
|
+
* - `buildVideoArgs({ targetWidth, targetHeight, segmentDurationSec })`
|
|
20
|
+
* ffmpeg video filter + encoder args inserted after `-map`s
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { spawn } from "node:child_process";
|
|
24
|
+
import { mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
25
|
+
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
26
|
+
import os from "node:os";
|
|
27
|
+
import path from "node:path";
|
|
28
|
+
import { fitDecodeCost } from "./decode-cost-fit.js";
|
|
29
|
+
import { penaltiesFrom } from "./encode/contention.js";
|
|
30
|
+
import { fileURLToPath } from "node:url";
|
|
31
|
+
import {
|
|
32
|
+
parseFfmpegBitrateKbps,
|
|
33
|
+
parseFfmpegDurationSeconds,
|
|
34
|
+
parseFfmpegVideoDimensions,
|
|
35
|
+
parseFfmpegVideoFps
|
|
36
|
+
} from "./ffmpeg-banner.js";
|
|
37
|
+
|
|
38
|
+
import { keyFrameArgs, TRANSCODE_FPS } from "./encode/args.js";
|
|
39
|
+
// The five kinds, one class each. Detection and benchmarking stay in this file;
|
|
40
|
+
// how a kind is driven belongs to the kind.
|
|
41
|
+
import {
|
|
42
|
+
NvencEncoder,
|
|
43
|
+
QsvEncoder,
|
|
44
|
+
SoftwareEncoder,
|
|
45
|
+
V4l2m2mEncoder,
|
|
46
|
+
VaapiEncoder
|
|
47
|
+
} from "./encode/index.js";
|
|
48
|
+
// Re-exported so every caller goes on importing these figures from here:
|
|
49
|
+
// the same calculation, moved to sit beside the encoder kinds built from it.
|
|
50
|
+
export {
|
|
51
|
+
chooseOutputFps,
|
|
52
|
+
maxrateKbpsFor,
|
|
53
|
+
nominalKbpsForHeight,
|
|
54
|
+
nominalKbpsForMaxrate,
|
|
55
|
+
TRANSCODE_FPS
|
|
56
|
+
} from "./encode/args.js";
|
|
57
|
+
|
|
58
|
+
const BENCHMARK_REF_W = 640;
|
|
59
|
+
const BENCHMARK_REF_H = 360;
|
|
60
|
+
const BENCHMARK_DURATION_SEC = 3;
|
|
61
|
+
/**
|
|
62
|
+
* The narrowest window a slope may be taken over. Measured 2026-08-15: at a
|
|
63
|
+
* fifth of a second the readings were noisy enough to put `faster` and
|
|
64
|
+
* `veryfast` BELOW `fast`, which libx264 cannot do — and `pickSoftwarePreset`
|
|
65
|
+
* walks the list assuming it ascends. Half a second was still noisy enough for that
|
|
66
|
+
* (measured again: veryfast below faster, twice), so a full second it is —
|
|
67
|
+
* about six seconds of startup for a ladder the whole budget then rests on.
|
|
68
|
+
*/
|
|
69
|
+
const ENCODE_BENCHMARK_WINDOW_SEC = 1;
|
|
70
|
+
/** The narrowest window that may be used when a run ends early. */
|
|
71
|
+
const ENCODE_BENCHMARK_MIN_WINDOW_SEC = 0.2;
|
|
72
|
+
/** Above this a reading is a fault, not a fast machine. */
|
|
73
|
+
const ENCODE_BENCHMARK_MAX_PLAUSIBLE_SPEED = 1000;
|
|
74
|
+
/**
|
|
75
|
+
* A preset that has not reported twice in this long is hung, not slow: reports
|
|
76
|
+
* arrive twice a second whatever the encoding speed.
|
|
77
|
+
*/
|
|
78
|
+
const ENCODE_BENCHMARK_TIMEOUT_MS = 10_000;
|
|
79
|
+
/**
|
|
80
|
+
* How many times the calibration clip is joined to itself to measure copying.
|
|
81
|
+
*
|
|
82
|
+
* Not a figure about the machine: it is how much film the reading needs to have
|
|
83
|
+
* in front of it. A copy runs at hundreds of times realtime, and the slope is
|
|
84
|
+
* taken over a window of one second, so the input has to hold more film than the
|
|
85
|
+
* fastest plausible host gets through in that second. Forty laps of a five-second
|
|
86
|
+
* clip is 200 s of film, which covers the ceiling `slopeOf` will accept.
|
|
87
|
+
*/
|
|
88
|
+
/** Progress reports arrive line by line. */
|
|
89
|
+
const NEWLINE = String.fromCharCode(10);
|
|
90
|
+
// Producing one second of video per second of clock. Not a margin and not a
|
|
91
|
+
// choice — the definition of keeping up, and the bar when nothing better is
|
|
92
|
+
// known about the supply this step will meet.
|
|
93
|
+
const REALTIME = 1;
|
|
94
|
+
// The bar where decoding CANNOT be priced — no calibration fit, or a source the
|
|
95
|
+
// probe said too little about. This one is not measured and cannot be: the
|
|
96
|
+
// prediction it guards counts encoding only, which on the field host was
|
|
97
|
+
// several times optimistic, and there is no reading on such a host to correct
|
|
98
|
+
// it with. It is left at the figure it has had since before decoding was
|
|
99
|
+
// priced, because lowering it to realtime would make the least-measured hosts
|
|
100
|
+
// the most permissive. Where decoding IS priced, nothing chosen remains.
|
|
101
|
+
const UNPRICED_DECODE_BAR = 1.8;
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
// The five kinds live in `encode/`, one class each, and these keep the names
|
|
105
|
+
// every caller already uses. A kind states its own arguments and its own
|
|
106
|
+
// ladder of speed settings; detection and benchmarking stay here.
|
|
107
|
+
/** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
|
|
108
|
+
export function softwareDescriptor() {
|
|
109
|
+
return new SoftwareEncoder();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {string} device
|
|
114
|
+
* @returns {import("./hwaccel.js").VideoEncoderDescriptor}
|
|
115
|
+
*/
|
|
116
|
+
function vaapiDescriptor(device) {
|
|
117
|
+
return new VaapiEncoder(device);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* @param {string} device
|
|
122
|
+
* @returns {import("./hwaccel.js").VideoEncoderDescriptor}
|
|
123
|
+
*/
|
|
124
|
+
function qsvDescriptor(device) {
|
|
125
|
+
return new QsvEncoder(device);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
|
|
129
|
+
function nvencDescriptor() {
|
|
130
|
+
return new NvencEncoder();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
|
|
134
|
+
function v4l2m2mDescriptor() {
|
|
135
|
+
return new V4l2m2mEncoder();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @typedef {Object} VideoEncoderDescriptor
|
|
142
|
+
* @property {string} name
|
|
143
|
+
* @property {"software"|"vaapi"|"qsv"|"nvenc"|"v4l2m2m"} kind
|
|
144
|
+
* @property {string|null} device
|
|
145
|
+
* @property {string[]} inputArgs
|
|
146
|
+
* @property {(opts: { targetWidth: number, targetHeight: number, segmentDurationSec: number, preset?: string, fps?: number, tonemap?: boolean, forcedKeyframeTimes?: number[] | null, nominalKbps?: number | null }) => string[]} buildVideoArgs
|
|
147
|
+
*/
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Run ffmpeg and resolve with its exit code and captured output.
|
|
151
|
+
*
|
|
152
|
+
* @param {string} ffmpegBin
|
|
153
|
+
* @param {string[]} args
|
|
154
|
+
* @param {number} [timeoutMs=12000]
|
|
155
|
+
* @returns {Promise<{ code: number, stdout: string, stderr: string }>}
|
|
156
|
+
*/
|
|
157
|
+
function runFfmpeg(ffmpegBin, args, timeoutMs = 12000) {
|
|
158
|
+
return new Promise((resolve) => {
|
|
159
|
+
let stdout = "";
|
|
160
|
+
let stderr = "";
|
|
161
|
+
let settled = false;
|
|
162
|
+
let child;
|
|
163
|
+
const finish = (code) => {
|
|
164
|
+
if (settled) {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
settled = true;
|
|
168
|
+
resolve({ code, stdout, stderr });
|
|
169
|
+
};
|
|
170
|
+
try {
|
|
171
|
+
child = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
172
|
+
} catch {
|
|
173
|
+
finish(-1);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const timer = setTimeout(() => {
|
|
177
|
+
try {
|
|
178
|
+
child.kill("SIGKILL");
|
|
179
|
+
} catch {
|
|
180
|
+
// already gone
|
|
181
|
+
}
|
|
182
|
+
finish(-1);
|
|
183
|
+
}, timeoutMs);
|
|
184
|
+
child.stdout.on("data", (chunk) => {
|
|
185
|
+
stdout += String(chunk);
|
|
186
|
+
});
|
|
187
|
+
child.stderr.on("data", (d) => {
|
|
188
|
+
stderr += String(d);
|
|
189
|
+
});
|
|
190
|
+
child.on("error", () => {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
finish(-1);
|
|
193
|
+
});
|
|
194
|
+
child.on("exit", (code) => {
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
finish(code ?? -1);
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** @returns {string[]} /dev/dri/renderD* nodes (VAAPI/QSV). */
|
|
202
|
+
function listRenderNodes() {
|
|
203
|
+
try {
|
|
204
|
+
return readdirSync("/dev/dri")
|
|
205
|
+
.filter((n) => n.startsWith("renderD"))
|
|
206
|
+
.map((n) => `/dev/dri/${n}`)
|
|
207
|
+
.sort();
|
|
208
|
+
} catch {
|
|
209
|
+
return [];
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** @returns {boolean} Whether any /dev/nvidia* node exists (NVENC). */
|
|
214
|
+
function hasNvidiaDevice() {
|
|
215
|
+
try {
|
|
216
|
+
return readdirSync("/dev").some((n) => /^nvidia(\d+)?$/.test(n));
|
|
217
|
+
} catch {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** @returns {boolean} Whether any /dev/video* node exists (V4L2 M2M). */
|
|
223
|
+
function hasV4l2Device() {
|
|
224
|
+
try {
|
|
225
|
+
return readdirSync("/dev").some((n) => /^video\d+$/.test(n));
|
|
226
|
+
} catch {
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Build a full ffmpeg command that encodes a short, *moving* synthetic clip
|
|
233
|
+
* (testsrc2 — far more representative than a static black frame) through the
|
|
234
|
+
* candidate encoder into real HLS segments in `outDir`, with keyframes forced
|
|
235
|
+
* on segment boundaries. Verifying the resulting segments (see
|
|
236
|
+
* {@link verifySegmentsDecodeCleanly}) catches encoders that silently produce
|
|
237
|
+
* a corrupted or non-IDR-aligned stream (e.g. some V4L2 M2M builds).
|
|
238
|
+
*
|
|
239
|
+
* @param {VideoEncoderDescriptor} descriptor
|
|
240
|
+
* @param {number} segmentDurationSec
|
|
241
|
+
* @param {string} outDir
|
|
242
|
+
* @returns {string[]}
|
|
243
|
+
*/
|
|
244
|
+
function buildEncoderTestArgs(descriptor, segmentDurationSec, outDir) {
|
|
245
|
+
const durationSec = Math.max(8, segmentDurationSec * 3);
|
|
246
|
+
const source = ["-f", "lavfi", "-i", `testsrc2=s=640x360:r=${TRANSCODE_FPS}:d=${durationSec}`];
|
|
247
|
+
const kf = keyFrameArgs(segmentDurationSec);
|
|
248
|
+
|
|
249
|
+
/** @type {string[]} */
|
|
250
|
+
let pre = ["-hide_banner", "-loglevel", "error"];
|
|
251
|
+
/** @type {string[]} */
|
|
252
|
+
let encode;
|
|
253
|
+
switch (descriptor.kind) {
|
|
254
|
+
case "vaapi":
|
|
255
|
+
pre = [...pre, "-vaapi_device", String(descriptor.device)];
|
|
256
|
+
encode = ["-vf", "format=nv12,hwupload", "-c:v", "h264_vaapi", "-qp", "24", ...kf];
|
|
257
|
+
break;
|
|
258
|
+
case "qsv":
|
|
259
|
+
pre = [...pre, "-qsv_device", String(descriptor.device)];
|
|
260
|
+
encode = ["-vf", "hwupload=extra_hw_frames=16,format=qsv", "-c:v", "h264_qsv", "-global_quality", "24", ...kf];
|
|
261
|
+
break;
|
|
262
|
+
case "nvenc":
|
|
263
|
+
encode = ["-c:v", "h264_nvenc", "-preset", "p4", "-cq", "24", "-pix_fmt", "yuv420p", ...kf];
|
|
264
|
+
break;
|
|
265
|
+
case "v4l2m2m":
|
|
266
|
+
encode = ["-pix_fmt", "yuv420p", "-c:v", "h264_v4l2m2m", "-num_capture_buffers", "32", "-b:v", "3M", "-g", String(TRANSCODE_FPS * segmentDurationSec), ...kf];
|
|
267
|
+
break;
|
|
268
|
+
default:
|
|
269
|
+
encode = ["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", ...kf];
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const hlsOut = [
|
|
274
|
+
"-f", "hls",
|
|
275
|
+
"-hls_time", String(segmentDurationSec),
|
|
276
|
+
"-hls_list_size", "0",
|
|
277
|
+
"-hls_flags", "independent_segments",
|
|
278
|
+
// fMP4 (CMAF) — matches the runtime pipeline (hls-session-manager).
|
|
279
|
+
"-hls_segment_type", "fmp4",
|
|
280
|
+
"-hls_fmp4_init_filename", "init.mp4",
|
|
281
|
+
"-hls_segment_filename", path.join(outDir, "seg-%03d.m4s"),
|
|
282
|
+
path.join(outDir, "index.m3u8")
|
|
283
|
+
];
|
|
284
|
+
return [...pre, ...source, ...encode, ...hlsOut];
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Verify the HLS segments produced by the test encode are valid: at least two
|
|
289
|
+
* segments exist, and each decodes standalone without errors. A segment that
|
|
290
|
+
* does not begin with a keyframe (broken/corrupted output) emits decode errors
|
|
291
|
+
* when read on its own, which fails this check.
|
|
292
|
+
*
|
|
293
|
+
* @param {string} ffmpegBin
|
|
294
|
+
* @param {string} outDir
|
|
295
|
+
* @returns {Promise<boolean>}
|
|
296
|
+
*/
|
|
297
|
+
async function verifySegmentsDecodeCleanly(ffmpegBin, outDir) {
|
|
298
|
+
let files;
|
|
299
|
+
try {
|
|
300
|
+
files = readdirSync(outDir).filter((n) => /^seg-\d+\.m4s$/.test(n));
|
|
301
|
+
} catch {
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
304
|
+
if (files.length < 2) {
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
// fMP4: parameter sets (SPS/PPS) live in init.mp4, not in each segment.
|
|
308
|
+
// Decode the whole playlist (ffmpeg's own, which references init.mp4 via
|
|
309
|
+
// #EXT-X-MAP), so every segment is exercised together with the init. Any
|
|
310
|
+
// corrupt / non-conformant segment (e.g. some V4L2 M2M builds emit a stray
|
|
311
|
+
// no-picture access unit) surfaces as a decode error here.
|
|
312
|
+
const result = await runFfmpeg(
|
|
313
|
+
ffmpegBin,
|
|
314
|
+
["-hide_banner", "-loglevel", "error", "-i", path.join(outDir, "index.m3u8"), "-f", "null", "-"],
|
|
315
|
+
12000
|
|
316
|
+
);
|
|
317
|
+
return result.code === 0 && result.stderr.trim().length === 0;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Detect the best usable H.264 encoder. Always resolves (falls back to
|
|
322
|
+
* software libx264). Each hardware candidate is verified with a real
|
|
323
|
+
* test-encode before being selected.
|
|
324
|
+
*
|
|
325
|
+
* @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, segmentDurationSec?: number }} options
|
|
326
|
+
* @returns {Promise<VideoEncoderDescriptor>}
|
|
327
|
+
*/
|
|
328
|
+
export async function detectVideoEncoder({ ffmpegBin, logger, segmentDurationSec = 4 }) {
|
|
329
|
+
const log = logger ?? { info: () => {}, warn: () => {} };
|
|
330
|
+
const software = softwareDescriptor();
|
|
331
|
+
|
|
332
|
+
const { code, stdout } = await runFfmpeg(ffmpegBin, ["-hide_banner", "-encoders"], 10000);
|
|
333
|
+
if (code !== 0) {
|
|
334
|
+
log.warn("hwaccel: could not list ffmpeg encoders; using software libx264");
|
|
335
|
+
return software;
|
|
336
|
+
}
|
|
337
|
+
const has = (name) => stdout.includes(name);
|
|
338
|
+
|
|
339
|
+
/** @type {VideoEncoderDescriptor[]} */
|
|
340
|
+
const candidates = [];
|
|
341
|
+
const renderNodes = listRenderNodes();
|
|
342
|
+
if (has("h264_nvenc") && hasNvidiaDevice()) {
|
|
343
|
+
candidates.push(nvencDescriptor());
|
|
344
|
+
}
|
|
345
|
+
if (has("h264_qsv") && renderNodes.length > 0) {
|
|
346
|
+
candidates.push(qsvDescriptor(renderNodes[0]));
|
|
347
|
+
}
|
|
348
|
+
if (has("h264_vaapi") && renderNodes.length > 0) {
|
|
349
|
+
candidates.push(vaapiDescriptor(renderNodes[0]));
|
|
350
|
+
}
|
|
351
|
+
// h264_v4l2m2m (ARM SoC / Raspberry Pi / HA Yellow). It is gated behind the
|
|
352
|
+
// strict keyframe-alignment test below, because some V4L2 M2M builds silently
|
|
353
|
+
// emit a corrupted / non-IDR-aligned stream; the test rejects those and the
|
|
354
|
+
// host falls back to software libx264.
|
|
355
|
+
if (has("h264_v4l2m2m") && hasV4l2Device()) {
|
|
356
|
+
candidates.push(v4l2m2mDescriptor());
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
for (const candidate of candidates) {
|
|
360
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), "tt-hwtest-"));
|
|
361
|
+
let ok = false;
|
|
362
|
+
try {
|
|
363
|
+
const encoded = await runFfmpeg(
|
|
364
|
+
ffmpegBin,
|
|
365
|
+
buildEncoderTestArgs(candidate, segmentDurationSec, dir),
|
|
366
|
+
25000
|
|
367
|
+
);
|
|
368
|
+
if (encoded.code === 0) {
|
|
369
|
+
ok = await verifySegmentsDecodeCleanly(ffmpegBin, dir);
|
|
370
|
+
}
|
|
371
|
+
} finally {
|
|
372
|
+
try {
|
|
373
|
+
rmSync(dir, { recursive: true, force: true });
|
|
374
|
+
} catch {
|
|
375
|
+
// best effort
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (ok) {
|
|
379
|
+
log.info(
|
|
380
|
+
`hwaccel: using hardware encoder ${candidate.name}` +
|
|
381
|
+
`${candidate.device ? ` (${candidate.device})` : ""}`
|
|
382
|
+
);
|
|
383
|
+
return candidate;
|
|
384
|
+
}
|
|
385
|
+
log.warn(`hwaccel: ${candidate.name} failed the HLS keyframe-alignment test; skipping`);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
log.info("hwaccel: no working hardware encoder; using software libx264");
|
|
389
|
+
return software;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Detect whether this ffmpeg build has the filters needed for the HDR→SDR
|
|
394
|
+
* tone-map chain (`zscale`, from libzimg, and `tonemap`). Both are required;
|
|
395
|
+
* when either is missing, HDR sources are re-encoded without tone mapping
|
|
396
|
+
* (washed-out but playable). Always resolves.
|
|
397
|
+
*
|
|
398
|
+
* @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void } }} options
|
|
399
|
+
* @returns {Promise<boolean>}
|
|
400
|
+
*/
|
|
401
|
+
export async function detectTonemapSupport({ ffmpegBin, logger }) {
|
|
402
|
+
const log = logger ?? { info: () => {}, warn: () => {} };
|
|
403
|
+
const { code, stdout } = await runFfmpeg(ffmpegBin, ["-hide_banner", "-filters"], 10000);
|
|
404
|
+
if (code !== 0) {
|
|
405
|
+
log.warn("hwaccel: could not list ffmpeg filters; HDR tone mapping disabled");
|
|
406
|
+
return false;
|
|
407
|
+
}
|
|
408
|
+
// `-filters` prints one filter per line: "... zscale ...", "... tonemap ...".
|
|
409
|
+
const hasZscale = /\bzscale\b/.test(stdout);
|
|
410
|
+
const hasTonemap = /\btonemap\b/.test(stdout);
|
|
411
|
+
const supported = hasZscale && hasTonemap;
|
|
412
|
+
log.info(
|
|
413
|
+
`hwaccel: HDR tone mapping ${supported ? "available" : "unavailable"} ` +
|
|
414
|
+
`(zscale=${hasZscale} tonemap=${hasTonemap})`
|
|
415
|
+
);
|
|
416
|
+
return supported;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
// The clips the decode cost is fitted from. They ship with the package
|
|
421
|
+
// (`assets/calibration/`), cut from Netflix Open Content "Meridian" (CC-BY 4.0)
|
|
422
|
+
// — real, grainy live action, because a generated `testsrc2` clip decodes 158 %
|
|
423
|
+
// away from a real film where these are 11 % away (measured 2026-08-14).
|
|
424
|
+
//
|
|
425
|
+
// Three sizes at two bitrates each, with the axes varied INDEPENDENTLY. The set
|
|
426
|
+
// this replaced was three clips for three unknowns, two of them at the same
|
|
427
|
+
// size: an exact system, which cannot fail visibly. On 2026-08-17 it returned
|
|
428
|
+
// `0.007542 × Mpx/s + 0.000000 × Mbit/s + 0.0000 s/s` — the bitrate term and
|
|
429
|
+
// the constant exactly zero — and the prediction on top of it was 1.8-2.2x
|
|
430
|
+
// optimistic. Six points leave three spare, so the fit has a residual, and a
|
|
431
|
+
// term the data does not determine can be refused instead of published as a
|
|
432
|
+
// zero that looks measured. See `assets/calibration/NOTICE.md`.
|
|
433
|
+
//
|
|
434
|
+
// One set PER CODEC FAMILY, because a family is what the model describes. The
|
|
435
|
+
// fit used to be H.264 only, while a video that has to be RE-ENCODED is by
|
|
436
|
+
// definition one the browser could not play — which is to say HEVC, 10-bit or
|
|
437
|
+
// AV1 — and those decode dearer per pixel on the same box. Pricing them with
|
|
438
|
+
// H.264 constants is the one case the model is always asked about and was never
|
|
439
|
+
// measured on.
|
|
440
|
+
//
|
|
441
|
+
// A family that has no set of its own is priced with H.264's, which is what
|
|
442
|
+
// happened to every family before this; the line says so rather than implying
|
|
443
|
+
// it. AV1 has no set yet: the survey of 2026-07-10 found it rare where HEVC was
|
|
444
|
+
// 18 % of releases, so it waits for the same treatment.
|
|
445
|
+
const CALIBRATION_SETS = {
|
|
446
|
+
h264: [
|
|
447
|
+
"cal-h264-1080-hi.mp4",
|
|
448
|
+
"cal-h264-1080-lo.mp4",
|
|
449
|
+
"cal-h264-720-hi.mp4",
|
|
450
|
+
"cal-h264-720-lo.mp4",
|
|
451
|
+
"cal-h264-480-hi.mp4",
|
|
452
|
+
"cal-h264-480-lo.mp4"
|
|
453
|
+
],
|
|
454
|
+
hevc: [
|
|
455
|
+
"cal-hevc-1080-hi.mp4",
|
|
456
|
+
"cal-hevc-1080-lo.mp4",
|
|
457
|
+
"cal-hevc-480-hi.mp4",
|
|
458
|
+
"cal-hevc-480-lo.mp4"
|
|
459
|
+
],
|
|
460
|
+
hevc10: [
|
|
461
|
+
"cal-hevc10-1080-hi.mp4",
|
|
462
|
+
"cal-hevc10-1080-lo.mp4",
|
|
463
|
+
"cal-hevc10-480-hi.mp4",
|
|
464
|
+
"cal-hevc10-480-lo.mp4"
|
|
465
|
+
]
|
|
466
|
+
};
|
|
467
|
+
const CALIBRATION_CLIPS = CALIBRATION_SETS.h264;
|
|
468
|
+
const CALIBRATION_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "calibration");
|
|
469
|
+
// How wide the measured window must be before the slope is trusted, and how
|
|
470
|
+
// long to wait for it at most.
|
|
471
|
+
//
|
|
472
|
+
// Half a second, and it is the TIMING noise that sets it rather than the amount
|
|
473
|
+
// of video: the slope is output time against wall time, both read from the same
|
|
474
|
+
// two progress lines, and the jitter in stamping one is milliseconds — so half
|
|
475
|
+
// a second of window is a fraction of a percent of error on any host. What used
|
|
476
|
+
// to make a longer window necessary was the clip restarting inside it, and that
|
|
477
|
+
// is gone: the stream is continuous now. Measured 2026-08-22 against the
|
|
478
|
+
// continuous-pass truth on a desktop: -3.0 % and +0.6 % at half a second, with
|
|
479
|
+
// the readings spread 2-6 %, against -25 % and -33 % for the loop it replaces.
|
|
480
|
+
// Half a second also costs the startup about 0.6 s per clip less, which matters
|
|
481
|
+
// because every clip of every codec family is paid for before any viewer
|
|
482
|
+
// exists.
|
|
483
|
+
const DECODE_WINDOW_MIN_SEC = 0.5;
|
|
484
|
+
const DECODE_WINDOW_MAX_MS = 8000;
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* Read what a calibration clip IS from the decode run's own output: the
|
|
488
|
+
* dimensions, the frame rate and the bitrate ffmpeg reports for it. Read rather
|
|
489
|
+
* than declared, so replacing a clip cannot silently invalidate the fit.
|
|
490
|
+
*
|
|
491
|
+
* @param {string} stderr
|
|
492
|
+
* @returns {{ megapixelsPerSecond: number, megabitsPerSecond: number, durationSeconds: number } | null}
|
|
493
|
+
*/
|
|
494
|
+
function parseClipCharacteristics(stderr) {
|
|
495
|
+
// The same readers the session manager uses on the same banner — one parser
|
|
496
|
+
// per fact, so a second copy cannot drift from the first.
|
|
497
|
+
const { width, height } = parseFfmpegVideoDimensions(stderr);
|
|
498
|
+
const rate = parseFfmpegVideoFps(stderr);
|
|
499
|
+
const seconds = parseFfmpegDurationSeconds(stderr);
|
|
500
|
+
const kbps = parseFfmpegBitrateKbps(stderr);
|
|
501
|
+
if (!(width > 0) || !(height > 0) || !(rate > 0) || !(seconds > 0) || !(kbps > 0)) {
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
return {
|
|
505
|
+
megapixelsPerSecond: (width * height * rate) / 1e6,
|
|
506
|
+
megabitsPerSecond: kbps / 1000,
|
|
507
|
+
durationSeconds: seconds
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Measure what DECODING costs on this host, as seconds of work per second of
|
|
513
|
+
* video, and solve it into three host constants:
|
|
514
|
+
*
|
|
515
|
+
* decodeCost = a × Mpixel/s + b × Mbit/s + c
|
|
516
|
+
*
|
|
517
|
+
* Why it exists: the preset benchmark below measures ENCODING only, and a
|
|
518
|
+
* re-encode pays for both halves. Measured 2026-08-14 on the addon host, that
|
|
519
|
+
* omission made the budget offer a 240p rung it then ran at 0.39-0.95× — the
|
|
520
|
+
* benchmark said the host cleared the bar 2.5× over. With the decode term the
|
|
521
|
+
* same file predicts within 4.8 %; without it the error on that rung was 209 %.
|
|
522
|
+
*
|
|
523
|
+
* The constants are properties of the HOST, so this runs once at startup (about
|
|
524
|
+
* 5 s on a CM4) and any source is then priced from figures the probe already
|
|
525
|
+
* has — nothing is added to a session's cold start.
|
|
526
|
+
*
|
|
527
|
+
* They are also properties of the CODEC, and the clips are H.264: HEVC, AV1 and
|
|
528
|
+
* 10-bit decode dearer per pixel on the same machine, and a source that has to
|
|
529
|
+
* be re-encoded is by definition one this browser could not play, which is
|
|
530
|
+
* usually not H.264. So the fit is optimistic exactly there. Closing that needs
|
|
531
|
+
* clips in those codecs, and is its own roadmap item.
|
|
532
|
+
*
|
|
533
|
+
* @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, clipsDir?: string }} options
|
|
534
|
+
* @returns {Promise<{ pixelTerm: number, bitrateTerm: number, constantTerm: number } | null>}
|
|
535
|
+
*/
|
|
536
|
+
/**
|
|
537
|
+
* What a second job costs on this host, measured rather than assumed.
|
|
538
|
+
*
|
|
539
|
+
* The budget adds seconds of work per second of content — this encode, plus
|
|
540
|
+
* that decode, plus what is already committed — and the addon host contradicted
|
|
541
|
+
* that directly on 2026-08-18: decoding ran at 2.10-2.25x alone, 0.79-0.90x
|
|
542
|
+
* with one encoder beside it and 0.56-0.64x with two. The same work costs 2.6×
|
|
543
|
+
* more for having company. Heat is not the cause (the hot idle machine was the
|
|
544
|
+
* fastest reading of all); four cores sharing one path to memory is.
|
|
545
|
+
*
|
|
546
|
+
* So it is measured the way everything else here is: the same clip decoded
|
|
547
|
+
* alone, then decoded again while an encoder of the same clip runs beside it.
|
|
548
|
+
* The ratio is the penalty. The encoder is stopped as soon as the reading is
|
|
549
|
+
* taken, and the whole thing costs one decode plus one short encode.
|
|
550
|
+
*
|
|
551
|
+
* @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, clipsDir?: string, upTo?: number }} options
|
|
552
|
+
* @returns {Promise<Map<number, number> | null>} Penalties by how many other
|
|
553
|
+
* jobs were running, or null when the readings could not be taken.
|
|
554
|
+
*/
|
|
555
|
+
export async function benchmarkContention({ ffmpegBin, logger, clipsDir = CALIBRATION_DIR, upTo = 2 }) {
|
|
556
|
+
const log = logger ?? { info: () => {}, warn: () => {} };
|
|
557
|
+
// The cheapest clip in the set: this measures the MACHINE's behaviour under
|
|
558
|
+
// company, not the clip's own cost, so the smallest one says it soonest.
|
|
559
|
+
const clip = path.join(clipsDir, "cal-h264-480-lo.mp4");
|
|
560
|
+
const startedAt = Date.now();
|
|
561
|
+
// Lifted once and decoded three times from the same bytes. Going through
|
|
562
|
+
// `measureDecodeSlope` lifted it again for every reading — three process
|
|
563
|
+
// starts on a path that is awaited before the proxy's tunnel opens, for a
|
|
564
|
+
// remux whose result had not changed.
|
|
565
|
+
const streams = await extractFamilyStreams(ffmpegBin, [clip], "h264");
|
|
566
|
+
const stream = streams?.[0];
|
|
567
|
+
if (!stream) {
|
|
568
|
+
log.warn("hwaccel: contention could not be measured; costs will be added as though jobs were independent");
|
|
569
|
+
return null;
|
|
570
|
+
}
|
|
571
|
+
const alone = await decodePipedStream(ffmpegBin, stream, log);
|
|
572
|
+
if (!alone?.speed) {
|
|
573
|
+
log.warn("hwaccel: contention could not be measured; costs will be added as though jobs were independent");
|
|
574
|
+
return null;
|
|
575
|
+
}
|
|
576
|
+
/** @type {Array<{ others: number, speed: number }>} */
|
|
577
|
+
const beside = [];
|
|
578
|
+
/** @type {import("node:child_process").ChildProcess[]} */
|
|
579
|
+
const load = [];
|
|
580
|
+
try {
|
|
581
|
+
for (let others = 1; others <= Math.max(1, upTo); others += 1) {
|
|
582
|
+
load.push(
|
|
583
|
+
spawn(
|
|
584
|
+
ffmpegBin,
|
|
585
|
+
[
|
|
586
|
+
"-hide_banner", "-loglevel", "error", "-nostats",
|
|
587
|
+
"-stream_loop", "-1", "-i", clip,
|
|
588
|
+
"-an", "-c:v", "libx264", "-preset", "fast", "-f", "null", "-"
|
|
589
|
+
],
|
|
590
|
+
{ stdio: ["ignore", "ignore", "ignore"], windowsHide: true }
|
|
591
|
+
)
|
|
592
|
+
);
|
|
593
|
+
// Let the encoder reach its own speed before reading anything: an encode
|
|
594
|
+
// measured in its first moments is measuring the process starting.
|
|
595
|
+
await new Promise((resolve) => {
|
|
596
|
+
setTimeout(resolve, 2_000);
|
|
597
|
+
});
|
|
598
|
+
const withCompany = await decodePipedStream(ffmpegBin, stream, log);
|
|
599
|
+
if (withCompany?.speed) {
|
|
600
|
+
beside.push({ others, speed: withCompany.speed });
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
} finally {
|
|
604
|
+
for (const child of load) {
|
|
605
|
+
try {
|
|
606
|
+
child.kill("SIGKILL");
|
|
607
|
+
} catch {
|
|
608
|
+
// Already gone: the reading is what mattered, and nothing else uses it.
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const penalties = penaltiesFrom(alone.speed, beside);
|
|
613
|
+
if (!penalties) {
|
|
614
|
+
log.warn("hwaccel: contention readings said nothing; costs will be added as though jobs were independent");
|
|
615
|
+
return null;
|
|
616
|
+
}
|
|
617
|
+
log.info(
|
|
618
|
+
`hwaccel: a second job costs ${[...penalties.entries()]
|
|
619
|
+
.map(([others, penalty]) => `${penalty.toFixed(2)}x beside ${others}`)
|
|
620
|
+
.join(", ")} ` +
|
|
621
|
+
`(decode alone ${alone.speed.toFixed(2)}x, ` +
|
|
622
|
+
`${beside.map((reading) => `${reading.speed.toFixed(2)}x beside ${reading.others}`).join(", ")}, ` +
|
|
623
|
+
`measured in ${((Date.now() - startedAt) / 1000).toFixed(1)}s)`
|
|
624
|
+
);
|
|
625
|
+
return penalties;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
export async function benchmarkDecodeCost({ ffmpegBin, logger, clipsDir = CALIBRATION_DIR }) {
|
|
629
|
+
const log = logger ?? { info: () => {}, warn: () => {} };
|
|
630
|
+
const startedAllAt = Date.now();
|
|
631
|
+
/** @type {Record<string, { pixelTerm: number, bitrateTerm: number, constantTerm: number }>} */
|
|
632
|
+
const families = {};
|
|
633
|
+
for (const [family, clips] of Object.entries(CALIBRATION_SETS)) {
|
|
634
|
+
const fitted = await fitOneFamily({ ffmpegBin, log, clipsDir, family, clips });
|
|
635
|
+
if (fitted) {
|
|
636
|
+
families[family] = fitted;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
if (!families.h264) {
|
|
640
|
+
// H.264 is the family every other one falls back to, so without it there is
|
|
641
|
+
// no model at all rather than a partial one. Which families DID fit is said
|
|
642
|
+
// anyway: on a fast host the H.264 clips decode at 20-80x and the readings
|
|
643
|
+
// stop being ordered — measured 2026-08-20 on a desktop, 1080p at 9.35
|
|
644
|
+
// Mbit/s costing 0.0307 s/s against 720p at 9.94 costing 0.0472, which is
|
|
645
|
+
// not a thing a decoder does — so a failure here is a measurement problem
|
|
646
|
+
// and not a missing file, and the line has to let those be told apart.
|
|
647
|
+
log.warn(
|
|
648
|
+
"hwaccel: decode cost unknown — the H.264 clips did not fit" +
|
|
649
|
+
(Object.keys(families).length > 0
|
|
650
|
+
? `, though ${Object.keys(families).join(" and ")} did`
|
|
651
|
+
: "")
|
|
652
|
+
);
|
|
653
|
+
return null;
|
|
654
|
+
}
|
|
655
|
+
const missing = Object.keys(CALIBRATION_SETS).filter((family) => !families[family]);
|
|
656
|
+
log.info(
|
|
657
|
+
`hwaccel: decode cost measured for ${Object.keys(families).join(", ")}` +
|
|
658
|
+
(missing.length > 0 ? `; ${missing.join(" and ")} priced as H.264` : "") +
|
|
659
|
+
` (in ${((Date.now() - startedAllAt) / 1000).toFixed(1)}s)`
|
|
660
|
+
);
|
|
661
|
+
return { families, ...families.h264 };
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* Fit one codec family's decode cost from its own clips.
|
|
666
|
+
*
|
|
667
|
+
* @param {{ ffmpegBin: string, log: { info: Function, warn: Function }, clipsDir: string, family: string, clips: string[] }} params
|
|
668
|
+
* @returns {Promise<{ pixelTerm: number, bitrateTerm: number, constantTerm: number } | null>}
|
|
669
|
+
*/
|
|
670
|
+
async function fitOneFamily({ ffmpegBin, log, clipsDir, family, clips }) {
|
|
671
|
+
const startedAllAt = Date.now();
|
|
672
|
+
/** @type {Array<{ megapixelsPerSecond: number, megabitsPerSecond: number, costSecondsPerSecond: number }>} */
|
|
673
|
+
const samples = [];
|
|
674
|
+
// Every clip of the family is lifted out of its container FIRST, in one
|
|
675
|
+
// ffmpeg run. See `extractFamilyStreams` for why one run rather than one per
|
|
676
|
+
// clip, and why before the measurements rather than beside them.
|
|
677
|
+
const streams = await extractFamilyStreams(
|
|
678
|
+
ffmpegBin,
|
|
679
|
+
clips.map((clip) => path.join(clipsDir, clip)),
|
|
680
|
+
family
|
|
681
|
+
);
|
|
682
|
+
if (!streams) {
|
|
683
|
+
log.warn(
|
|
684
|
+
`hwaccel: ${family} cannot be lifted out of its container — no Annex-B filter is mapped for it, ` +
|
|
685
|
+
`so its clips were never measured`
|
|
686
|
+
);
|
|
687
|
+
return null;
|
|
688
|
+
}
|
|
689
|
+
for (const [index, clip] of clips.entries()) {
|
|
690
|
+
const stream = streams[index];
|
|
691
|
+
const measured = stream ? await decodePipedStream(ffmpegBin, stream, log) : null;
|
|
692
|
+
if (!measured?.speed) {
|
|
693
|
+
log.warn(
|
|
694
|
+
`hwaccel: decode benchmark "${clip}" said nothing; ${family} not measured` +
|
|
695
|
+
(measured?.error ? ` — ${measured.error}` : " — the clip could not be lifted out of its container")
|
|
696
|
+
);
|
|
697
|
+
return null;
|
|
698
|
+
}
|
|
699
|
+
const cost = 1 / measured.speed;
|
|
700
|
+
samples.push({
|
|
701
|
+
megapixelsPerSecond: measured.megapixelsPerSecond,
|
|
702
|
+
megabitsPerSecond: measured.megabitsPerSecond,
|
|
703
|
+
costSecondsPerSecond: cost
|
|
704
|
+
});
|
|
705
|
+
log.info(
|
|
706
|
+
`hwaccel: decode "${clip}" ${measured.megapixelsPerSecond.toFixed(1)} Mpx/s ` +
|
|
707
|
+
`${measured.megabitsPerSecond.toFixed(2)} Mbit/s -> ${measured.speed.toFixed(1)}x ` +
|
|
708
|
+
`(cost ${cost.toFixed(4)} s/s, over ${measured.windowSec.toFixed(1)}s of decoding)`
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
const fitted = fitDecodeCost(samples);
|
|
712
|
+
if (!fitted) {
|
|
713
|
+
log.warn(`hwaccel: ${family} decode cost could not be fitted to these measurements`);
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
log.info(
|
|
717
|
+
`hwaccel: ${family} decode cost = ${fitted.pixelTerm.toFixed(6)} × Mpx/s + ${fitted.bitrateTerm.toFixed(6)} × Mbit/s ` +
|
|
718
|
+
`+ ${fitted.constantTerm.toFixed(4)} s/s (${fitted.shape} from ${fitted.samples} clips, ` +
|
|
719
|
+
`typical disagreement ${fitted.residualRms.toFixed(4)} s/s` +
|
|
720
|
+
// Named rather than implied: a zero in the line above means "not
|
|
721
|
+
// measured" for a dropped term and "measured to be nothing" otherwise,
|
|
722
|
+
// and those are different claims.
|
|
723
|
+
(fitted.dropped.length > 0 ? `, ${fitted.dropped.join(" and ")} not determined by these clips` : "") +
|
|
724
|
+
`, measured in ${((Date.now() - startedAllAt) / 1000).toFixed(1)}s)`
|
|
725
|
+
);
|
|
726
|
+
return { pixelTerm: fitted.pixelTerm, bitrateTerm: fitted.bitrateTerm, constantTerm: fitted.constantTerm };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* The bitstream filter and demuxer that turn a clip's video track into a
|
|
731
|
+
* continuous elementary stream, by codec family.
|
|
732
|
+
*
|
|
733
|
+
* H.264 and HEVC in MP4 keep their parameter sets in the container's `avcC` /
|
|
734
|
+
* `hvcC` and their access units length-prefixed; Annex-B carries them inline,
|
|
735
|
+
* with start codes, which is what makes plain byte concatenation a valid
|
|
736
|
+
* stream. That is the property this whole measurement rests on.
|
|
737
|
+
*/
|
|
738
|
+
const ANNEX_B_BY_FAMILY = {
|
|
739
|
+
h264: { filter: "h264_mp4toannexb", demuxer: "h264" },
|
|
740
|
+
hevc: { filter: "hevc_mp4toannexb", demuxer: "hevc" },
|
|
741
|
+
hevc10: { filter: "hevc_mp4toannexb", demuxer: "hevc" }
|
|
742
|
+
};
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* The last complaint in an ffmpeg stderr, for a line that has to say why.
|
|
746
|
+
*
|
|
747
|
+
* @param {string} stderr
|
|
748
|
+
* @returns {string}
|
|
749
|
+
*/
|
|
750
|
+
function lastErrorLine(stderr) {
|
|
751
|
+
const lines = String(stderr ?? "")
|
|
752
|
+
.split(/\r?\n/)
|
|
753
|
+
.map((line) => line.trim())
|
|
754
|
+
.filter((line) => line.length > 0);
|
|
755
|
+
return lines[lines.length - 1] ?? "";
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* How long the lift may take before it is abandoned. It is a remux of a few
|
|
760
|
+
* megabytes, so this is not a budget — it is the difference between a startup
|
|
761
|
+
* that reports a failure and one that never finishes. Every other ffmpeg run in
|
|
762
|
+
* this file has such a bound; this one did not, and it is awaited before the
|
|
763
|
+
* proxy's tunnel opens.
|
|
764
|
+
*/
|
|
765
|
+
const EXTRACT_TIMEOUT_MS = 20_000;
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* Lift a whole family's clips out of their containers, as Annex-B elementary
|
|
769
|
+
* streams, in ONE ffmpeg run.
|
|
770
|
+
*
|
|
771
|
+
* No re-encoding — the frames are copied — so the work itself is trivial and
|
|
772
|
+
* the cost is almost entirely the process. Doing one process per clip added
|
|
773
|
+
* 11 s to the startup here (fourteen clips at about 0.83 s each), and running
|
|
774
|
+
* them concurrently did not help: six at once took 4.75 s against 0.89 s for
|
|
775
|
+
* one, so the machine serialises them. One run with many inputs and many
|
|
776
|
+
* outputs costs one process.
|
|
777
|
+
*
|
|
778
|
+
* The outputs go to temporary files because several outputs cannot share one
|
|
779
|
+
* pipe; they are read into memory and deleted immediately, and nothing about
|
|
780
|
+
* this measurement is kept between runs.
|
|
781
|
+
*
|
|
782
|
+
* Before the measurements, never beside them: a remux running next to a decode
|
|
783
|
+
* is a second job on the machine, and this benchmark exists to find out what
|
|
784
|
+
* ONE job costs here.
|
|
785
|
+
*
|
|
786
|
+
* @param {string} ffmpegBin
|
|
787
|
+
* @param {string[]} clipPaths
|
|
788
|
+
* @param {string} family
|
|
789
|
+
* @returns {Promise<Array<{ bytes: Buffer, demuxer: string, megapixelsPerSecond: number, megabitsPerSecond: number, fps: number } | null> | null>}
|
|
790
|
+
* One entry per clip, in order; null when the family cannot be lifted at all.
|
|
791
|
+
*/
|
|
792
|
+
async function extractFamilyStreams(ffmpegBin, clipPaths, family) {
|
|
793
|
+
const shape = ANNEX_B_BY_FAMILY[family];
|
|
794
|
+
// A family with no mapping is a hard failure, not a silent fallback to
|
|
795
|
+
// H.264's filter. AV1 has no Annex-B form at all (its packaging is OBU), and
|
|
796
|
+
// MPEG-2 and VC-1 have no `*_mp4toannexb` filter — so the three families the
|
|
797
|
+
// roadmap plans next cannot come through here, and finding that out as
|
|
798
|
+
// "the clip failed" would send the reader after the clip.
|
|
799
|
+
if (!shape) {
|
|
800
|
+
return null;
|
|
801
|
+
}
|
|
802
|
+
const workDir = await mkdtemp(path.join(os.tmpdir(), "ttv-calibration-"));
|
|
803
|
+
const outputs = clipPaths.map((_, index) => path.join(workDir, `stream-${index}.${shape.demuxer}`));
|
|
804
|
+
/** @type {string[]} */
|
|
805
|
+
const args = ["-hide_banner", "-loglevel", "info", "-nostats", "-y"];
|
|
806
|
+
for (const clipPath of clipPaths) {
|
|
807
|
+
args.push("-i", clipPath);
|
|
808
|
+
}
|
|
809
|
+
for (const [index, output] of outputs.entries()) {
|
|
810
|
+
args.push("-map", `${index}:v:0`, "-c:v", "copy", "-bsf:v", shape.filter, "-f", shape.demuxer, output);
|
|
811
|
+
}
|
|
812
|
+
const stderr = await runCapturingStderr(ffmpegBin, args, EXTRACT_TIMEOUT_MS);
|
|
813
|
+
try {
|
|
814
|
+
if (stderr === null) {
|
|
815
|
+
return null;
|
|
816
|
+
}
|
|
817
|
+
// One banner block per input, in the order they were given. Read rather
|
|
818
|
+
// than declared, so replacing a clip cannot silently invalidate the fit
|
|
819
|
+
// that rests on it.
|
|
820
|
+
const blocks = splitInputBlocks(stderr, clipPaths.length);
|
|
821
|
+
return await Promise.all(clipPaths.map(async (_, index) => {
|
|
822
|
+
const block = blocks[index];
|
|
823
|
+
if (!block) {
|
|
824
|
+
return null;
|
|
825
|
+
}
|
|
826
|
+
const clipInfo = parseClipCharacteristics(block);
|
|
827
|
+
const fps = parseFfmpegVideoFps(block);
|
|
828
|
+
if (!clipInfo || !(fps > 0)) {
|
|
829
|
+
return null;
|
|
830
|
+
}
|
|
831
|
+
let bytes;
|
|
832
|
+
try {
|
|
833
|
+
bytes = await readFile(outputs[index]);
|
|
834
|
+
} catch {
|
|
835
|
+
return null;
|
|
836
|
+
}
|
|
837
|
+
if (bytes.length === 0) {
|
|
838
|
+
return null;
|
|
839
|
+
}
|
|
840
|
+
return {
|
|
841
|
+
bytes,
|
|
842
|
+
demuxer: shape.demuxer,
|
|
843
|
+
megapixelsPerSecond: clipInfo.megapixelsPerSecond,
|
|
844
|
+
megabitsPerSecond: clipInfo.megabitsPerSecond,
|
|
845
|
+
fps
|
|
846
|
+
};
|
|
847
|
+
}));
|
|
848
|
+
} finally {
|
|
849
|
+
await rm(workDir, { recursive: true, force: true }).catch(() => {});
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* The part of an ffmpeg banner describing each input, in order.
|
|
855
|
+
*
|
|
856
|
+
* ffmpeg prints one `Input #N, …` block per input and then the stream mapping;
|
|
857
|
+
* the parsers here read a single input's facts, so they are given a single
|
|
858
|
+
* input's text rather than the whole banner.
|
|
859
|
+
*
|
|
860
|
+
* @param {string} stderr
|
|
861
|
+
* @param {number} count
|
|
862
|
+
* @returns {string[]}
|
|
863
|
+
*/
|
|
864
|
+
function splitInputBlocks(stderr, count) {
|
|
865
|
+
/** @type {string[]} */
|
|
866
|
+
const blocks = [];
|
|
867
|
+
for (let index = 0; index < count; index += 1) {
|
|
868
|
+
const from = stderr.indexOf(`Input #${index},`);
|
|
869
|
+
if (from < 0) {
|
|
870
|
+
blocks.push("");
|
|
871
|
+
continue;
|
|
872
|
+
}
|
|
873
|
+
const nextInput = stderr.indexOf(`Input #${index + 1},`, from);
|
|
874
|
+
const mapping = stderr.indexOf("Stream mapping:", from);
|
|
875
|
+
const ends = [nextInput, mapping].filter((at) => at > from);
|
|
876
|
+
blocks.push(stderr.slice(from, ends.length > 0 ? Math.min(...ends) : stderr.length));
|
|
877
|
+
}
|
|
878
|
+
return blocks;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* Run ffmpeg to completion and return its stderr, or null when it failed or
|
|
883
|
+
* outlasted its bound.
|
|
884
|
+
*
|
|
885
|
+
* @param {string} ffmpegBin
|
|
886
|
+
* @param {string[]} args
|
|
887
|
+
* @param {number} timeoutMs
|
|
888
|
+
* @returns {Promise<string | null>}
|
|
889
|
+
*/
|
|
890
|
+
function runCapturingStderr(ffmpegBin, args, timeoutMs) {
|
|
891
|
+
return new Promise((resolve) => {
|
|
892
|
+
let stderr = "";
|
|
893
|
+
let settled = false;
|
|
894
|
+
let child;
|
|
895
|
+
const settle = (value) => {
|
|
896
|
+
if (settled) {
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
settled = true;
|
|
900
|
+
clearTimeout(timer);
|
|
901
|
+
try {
|
|
902
|
+
child?.kill("SIGKILL");
|
|
903
|
+
} catch {
|
|
904
|
+
// already gone
|
|
905
|
+
}
|
|
906
|
+
resolve(value);
|
|
907
|
+
};
|
|
908
|
+
const timer = setTimeout(() => settle(null), timeoutMs);
|
|
909
|
+
try {
|
|
910
|
+
child = spawn(ffmpegBin, args, { stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
|
|
911
|
+
} catch {
|
|
912
|
+
settle(null);
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
child.stderr.on("data", (chunk) => {
|
|
916
|
+
stderr += String(chunk);
|
|
917
|
+
});
|
|
918
|
+
child.on("error", () => settle(null));
|
|
919
|
+
child.on("close", (code) => settle(code === 0 ? stderr : null));
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/**
|
|
924
|
+
* Measure how fast this host DECODES a clip, from ffmpeg's own report of how
|
|
925
|
+
* much video it has processed.
|
|
926
|
+
*
|
|
927
|
+
* Two things are deliberately outside the measurement.
|
|
928
|
+
*
|
|
929
|
+
* **The process starting.** Wall-clock around the process cannot answer this:
|
|
930
|
+
* starting ffmpeg costs about a second, and on a quick machine a five-second
|
|
931
|
+
* clip decodes in a tenth of that, so the measurement would be of the program
|
|
932
|
+
* starting. Progress lines arrive AFTER it has started, and the slope between
|
|
933
|
+
* two of them — video processed against time taken — contains no part of the
|
|
934
|
+
* startup by construction.
|
|
935
|
+
*
|
|
936
|
+
* **The clip restarting.** This used to loop the clip with `-stream_loop -1`,
|
|
937
|
+
* and a loop is not free: measured 2026-08-22 on a desktop, a restart costs
|
|
938
|
+
* 0.03 s on the 480p clip and 0.12 s on the 1080p one — the decoder tearing
|
|
939
|
+
* down and re-allocating its frame buffers, which is why the price rises with
|
|
940
|
+
* the picture. A five-second clip decoded at 55x restarts eleven times a
|
|
941
|
+
* second, so that cost DOMINATED the reading: the same clips measured 53.7x
|
|
942
|
+
* looped against 80.3x in one continuous pass, and 11.8x against 15.8x. Worse,
|
|
943
|
+
* the bias is not shared — it depends on the clip's own resolution and on how
|
|
944
|
+
* fast the host is — so it does not cancel out of the fit, it tilts it. That is
|
|
945
|
+
* the fast-host failure recorded on 2026-08-20, where 1080p read cheaper than
|
|
946
|
+
* 720p, which is not a thing a decoder does.
|
|
947
|
+
*
|
|
948
|
+
* So the clip is fed to the decoder as ONE stream instead. An Annex-B
|
|
949
|
+
* elementary stream carries its parameter sets inline, so writing the same
|
|
950
|
+
* bytes again is simply more stream — the decoder never re-initialises, and
|
|
951
|
+
* there is no restart inside the window to measure. Verified against the
|
|
952
|
+
* continuous-pass truth on the same host: -0.2 % and -5.5 %, against -25 % and
|
|
953
|
+
* -33 % for the loop. Nothing is written to disk and the process is killed as
|
|
954
|
+
* soon as the window is wide enough.
|
|
955
|
+
*
|
|
956
|
+
* Exported because the property that broke here is checkable and was not being
|
|
957
|
+
* checked: a bigger picture must cost more than a smaller one of the same
|
|
958
|
+
* bitrate, and under the loop it did not.
|
|
959
|
+
*
|
|
960
|
+
* @param {string} ffmpegBin
|
|
961
|
+
* @param {string} clipPath
|
|
962
|
+
* @param {string} [family="h264"]
|
|
963
|
+
* @returns {Promise<{ speed: number, windowSec: number, megapixelsPerSecond: number, megabitsPerSecond: number } | null>}
|
|
964
|
+
*/
|
|
965
|
+
export async function measureDecodeSlope(ffmpegBin, clipPath, family = "h264") {
|
|
966
|
+
const streams = await extractFamilyStreams(ffmpegBin, [clipPath], family);
|
|
967
|
+
const stream = streams?.[0];
|
|
968
|
+
if (!stream) {
|
|
969
|
+
return null;
|
|
970
|
+
}
|
|
971
|
+
const measured = await decodePipedStream(ffmpegBin, stream);
|
|
972
|
+
return measured?.speed ? measured : null;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* Decode an elementary stream fed from memory, and report the slope.
|
|
977
|
+
*
|
|
978
|
+
* @param {string} ffmpegBin
|
|
979
|
+
* @param {{ bytes: Buffer, demuxer: string, megapixelsPerSecond: number, megabitsPerSecond: number, fps: number }} stream
|
|
980
|
+
* @returns {Promise<{ speed: number, windowSec: number, megapixelsPerSecond: number, megabitsPerSecond: number } | null>}
|
|
981
|
+
*/
|
|
982
|
+
function decodePipedStream(ffmpegBin, stream, log = { info: () => {}, warn: () => {} }) {
|
|
983
|
+
return new Promise((resolve) => {
|
|
984
|
+
const args = [
|
|
985
|
+
"-hide_banner", "-loglevel", "error", "-nostats",
|
|
986
|
+
// A raw stream states no frame rate, so the one the container declared is
|
|
987
|
+
// given back to it. It decides how output time advances, and therefore
|
|
988
|
+
// what "seconds of video per second of clock" means.
|
|
989
|
+
"-f", stream.demuxer, "-framerate", String(stream.fps), "-i", "pipe:0",
|
|
990
|
+
"-an", "-f", "null", "-",
|
|
991
|
+
"-progress", "pipe:1"
|
|
992
|
+
];
|
|
993
|
+
/** @type {Array<{ wallSec: number, outSec: number }>} */
|
|
994
|
+
const samples = [];
|
|
995
|
+
let stdout = "";
|
|
996
|
+
// Kept because this path depends on three things the old one did not: the
|
|
997
|
+
// raw demuxer accepting the frame rate, the bitstream filter having
|
|
998
|
+
// produced something parsable, and the fed concatenation being decodable.
|
|
999
|
+
// Without it the only trace of any of those failing is "said nothing".
|
|
1000
|
+
let stderr = "";
|
|
1001
|
+
let settled = false;
|
|
1002
|
+
let child;
|
|
1003
|
+
const startedAt = Date.now();
|
|
1004
|
+
// Whether the FEED, not the decoder, could be what this reading measures
|
|
1005
|
+
// (item 4(d2)). `child.stdin.write()` returning false was tried as the
|
|
1006
|
+
// signal — never once true would mean this process was never ahead of the
|
|
1007
|
+
// pipe — and measured false on every reading taken while writing this,
|
|
1008
|
+
// including clips this same host decodes at 15-80x with room to spare, so
|
|
1009
|
+
// it does not discriminate: `write()`'s return value tracks Node's own
|
|
1010
|
+
// internal watermark against the size of what was just handed to it, not
|
|
1011
|
+
// real drain state, and answered "no slack" identically whether the pipe
|
|
1012
|
+
// or the decoder was the true limit. Rather than publish a verdict that
|
|
1013
|
+
// reads the same in both cases, only the byte count is kept, for the
|
|
1014
|
+
// MB/s figure below — a number to read, not a boolean to trust.
|
|
1015
|
+
let bytesWritten = 0;
|
|
1016
|
+
const finish = () => {
|
|
1017
|
+
if (settled) {
|
|
1018
|
+
return;
|
|
1019
|
+
}
|
|
1020
|
+
settled = true;
|
|
1021
|
+
clearTimeout(timer);
|
|
1022
|
+
try {
|
|
1023
|
+
child?.stdin?.destroy();
|
|
1024
|
+
} catch {
|
|
1025
|
+
// already gone
|
|
1026
|
+
}
|
|
1027
|
+
try {
|
|
1028
|
+
child?.kill("SIGKILL");
|
|
1029
|
+
} catch {
|
|
1030
|
+
// already gone
|
|
1031
|
+
}
|
|
1032
|
+
// The first sample still carries the startup — it reports whatever was
|
|
1033
|
+
// processed while the process was coming up. Everything is measured from
|
|
1034
|
+
// the second onwards.
|
|
1035
|
+
const first = samples[1];
|
|
1036
|
+
const last = samples[samples.length - 1];
|
|
1037
|
+
if (!first || !last) {
|
|
1038
|
+
resolve({ error: lastErrorLine(stderr) || "the decoder reported no progress" });
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
const windowSec = last.wallSec - first.wallSec;
|
|
1042
|
+
const producedSec = last.outSec - first.outSec;
|
|
1043
|
+
if (!(windowSec >= DECODE_WINDOW_MIN_SEC) || !(producedSec > 0)) {
|
|
1044
|
+
resolve({ error: lastErrorLine(stderr) || `the window was ${windowSec.toFixed(2)}s of ${producedSec.toFixed(2)}s produced` });
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
const speed = producedSec / windowSec;
|
|
1048
|
+
// Diagnostic only — logged, not acted on. Both figures are taken over the
|
|
1049
|
+
// SAME window the speed itself is: bytesWritten is snapshotted alongside
|
|
1050
|
+
// every progress sample, so this compares like against like rather than
|
|
1051
|
+
// the achieved rate over the whole run (which starts before the first
|
|
1052
|
+
// kept sample and reads systematically low against the window's own
|
|
1053
|
+
// rate for no reason but that mismatch — measured while building this).
|
|
1054
|
+
const windowBytes = last.bytesWritten - first.bytesWritten;
|
|
1055
|
+
const achievedMBps = windowSec > 0 ? windowBytes / windowSec / 1e6 : 0;
|
|
1056
|
+
const requiredMBps = ((stream.megabitsPerSecond * 1e6) / 8) * speed / 1e6;
|
|
1057
|
+
// "Far apart" is stated, not left to the reader to eyeball: outside a
|
|
1058
|
+
// factor of 1.5 either way is bigger than the write-timing slop this
|
|
1059
|
+
// comparison carries on a healthy reading.
|
|
1060
|
+
const farApart = requiredMBps > 0 && (achievedMBps / requiredMBps < 1 / 1.5 || achievedMBps / requiredMBps > 1.5);
|
|
1061
|
+
log.info(
|
|
1062
|
+
`hwaccel: decode pipe fed ${achievedMBps.toFixed(1)} MB/s, ${requiredMBps.toFixed(1)} MB/s ` +
|
|
1063
|
+
`needed for ${speed.toFixed(2)}x` +
|
|
1064
|
+
(farApart ? " — far enough apart to be worth a second look" : "")
|
|
1065
|
+
);
|
|
1066
|
+
resolve({
|
|
1067
|
+
speed,
|
|
1068
|
+
windowSec,
|
|
1069
|
+
megapixelsPerSecond: stream.megapixelsPerSecond,
|
|
1070
|
+
megabitsPerSecond: stream.megabitsPerSecond,
|
|
1071
|
+
pipeThroughputMBps: achievedMBps
|
|
1072
|
+
});
|
|
1073
|
+
};
|
|
1074
|
+
const timer = setTimeout(finish, DECODE_WINDOW_MAX_MS);
|
|
1075
|
+
try {
|
|
1076
|
+
child = spawn(ffmpegBin, args, { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
|
|
1077
|
+
} catch (error) {
|
|
1078
|
+
clearTimeout(timer);
|
|
1079
|
+
settled = true;
|
|
1080
|
+
resolve({ error: error instanceof Error ? error.message : String(error) });
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
child.stderr.on("data", (chunk) => {
|
|
1084
|
+
stderr += String(chunk);
|
|
1085
|
+
});
|
|
1086
|
+
// Keep the decoder fed. `write` returning false means the pipe is full, and
|
|
1087
|
+
// the next copy goes on the `drain` — so the decoder is never starved and
|
|
1088
|
+
// this process never buffers more than the pipe holds.
|
|
1089
|
+
const writeOnce = () => {
|
|
1090
|
+
const accepted = child.stdin.write(stream.bytes);
|
|
1091
|
+
bytesWritten += stream.bytes.length;
|
|
1092
|
+
return accepted;
|
|
1093
|
+
};
|
|
1094
|
+
const feed = () => {
|
|
1095
|
+
while (!settled && child.stdin.writable && writeOnce()) {
|
|
1096
|
+
// Written straight through; go round again.
|
|
1097
|
+
}
|
|
1098
|
+
};
|
|
1099
|
+
child.stdin.on("drain", feed);
|
|
1100
|
+
// The kill closes the pipe under the writer; that is the intended end.
|
|
1101
|
+
child.stdin.on("error", () => {});
|
|
1102
|
+
child.stdout.on("data", (chunk) => {
|
|
1103
|
+
stdout += String(chunk);
|
|
1104
|
+
let newline = stdout.indexOf("\n");
|
|
1105
|
+
while (newline >= 0) {
|
|
1106
|
+
const line = stdout.slice(0, newline).trim();
|
|
1107
|
+
stdout = stdout.slice(newline + 1);
|
|
1108
|
+
if (line.startsWith("out_time_ms=")) {
|
|
1109
|
+
const microseconds = Number(line.slice("out_time_ms=".length));
|
|
1110
|
+
if (Number.isFinite(microseconds)) {
|
|
1111
|
+
samples.push({ wallSec: (Date.now() - startedAt) / 1000, outSec: microseconds / 1e6, bytesWritten });
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
newline = stdout.indexOf("\n");
|
|
1115
|
+
}
|
|
1116
|
+
if (samples.length >= 2 && samples[samples.length - 1].wallSec - samples[1].wallSec >= DECODE_WINDOW_MIN_SEC) {
|
|
1117
|
+
finish();
|
|
1118
|
+
}
|
|
1119
|
+
});
|
|
1120
|
+
child.on("error", (error) => {
|
|
1121
|
+
if (settled) {
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
clearTimeout(timer);
|
|
1125
|
+
settled = true;
|
|
1126
|
+
try {
|
|
1127
|
+
child?.stdin?.destroy();
|
|
1128
|
+
} catch {
|
|
1129
|
+
// already gone
|
|
1130
|
+
}
|
|
1131
|
+
try {
|
|
1132
|
+
child?.kill("SIGKILL");
|
|
1133
|
+
} catch {
|
|
1134
|
+
// already gone
|
|
1135
|
+
}
|
|
1136
|
+
resolve({ error: error instanceof Error ? error.message : String(error) });
|
|
1137
|
+
});
|
|
1138
|
+
child.on("close", finish);
|
|
1139
|
+
feed();
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
|
|
1144
|
+
/**
|
|
1145
|
+
* How many times realtime this host can DECODE a source of these
|
|
1146
|
+
* characteristics, from the startup fit. `null` when the fit is unavailable or
|
|
1147
|
+
* the source figures are not known.
|
|
1148
|
+
*
|
|
1149
|
+
* @param {{ pixelTerm: number, bitrateTerm: number, constantTerm: number } | null} model
|
|
1150
|
+
* @param {{ megapixelsPerSecond: number, megabitsPerSecond: number }} source
|
|
1151
|
+
* @returns {number | null}
|
|
1152
|
+
*/
|
|
1153
|
+
export function decodeSpeedFor(model, source) {
|
|
1154
|
+
if (!model) {
|
|
1155
|
+
return null;
|
|
1156
|
+
}
|
|
1157
|
+
const pixels = Number(source?.megapixelsPerSecond);
|
|
1158
|
+
const bits = Number(source?.megabitsPerSecond);
|
|
1159
|
+
if (!Number.isFinite(pixels) || pixels <= 0 || !Number.isFinite(bits) || bits < 0) {
|
|
1160
|
+
return null;
|
|
1161
|
+
}
|
|
1162
|
+
const cost = model.pixelTerm * pixels + model.bitrateTerm * bits + model.constantTerm;
|
|
1163
|
+
if (!(cost > 0)) {
|
|
1164
|
+
return null;
|
|
1165
|
+
}
|
|
1166
|
+
return 1 / cost;
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
/**
|
|
1170
|
+
* How many times realtime a re-encode of this source at this output pixel rate
|
|
1171
|
+
* would run: decoding and encoding share the machine, so their costs add and
|
|
1172
|
+
* their speeds combine as
|
|
1173
|
+
*
|
|
1174
|
+
* 1 / (1/decodeSpeed + 1/encodeSpeed)
|
|
1175
|
+
*
|
|
1176
|
+
* Checked 2026-08-14 on the rung that broke playback: 1/(1/2.31 + 1/5.99) =
|
|
1177
|
+
* 1.67× against 1.48× measured. With no decode fit this falls back to the
|
|
1178
|
+
* encode speed alone — which is what the budget did before, and which
|
|
1179
|
+
* overestimated that rung five to eleven times.
|
|
1180
|
+
*
|
|
1181
|
+
* @param {{ decodeModel: { pixelTerm: number, bitrateTerm: number, constantTerm: number } | null, encodePixelsPerSec: number, outputPixelsPerSec: number, source: { megapixelsPerSecond: number, megabitsPerSecond: number } | null }} params
|
|
1182
|
+
* @returns {number | null}
|
|
1183
|
+
*/
|
|
1184
|
+
export function predictedRealtimeSpeed({
|
|
1185
|
+
decodeModel,
|
|
1186
|
+
encodePixelsPerSec,
|
|
1187
|
+
outputPixelsPerSec,
|
|
1188
|
+
source,
|
|
1189
|
+
observedDecodeCostSec = null
|
|
1190
|
+
}) {
|
|
1191
|
+
if (!Number.isFinite(encodePixelsPerSec) || encodePixelsPerSec <= 0) {
|
|
1192
|
+
return null;
|
|
1193
|
+
}
|
|
1194
|
+
if (!Number.isFinite(outputPixelsPerSec) || outputPixelsPerSec <= 0) {
|
|
1195
|
+
return null;
|
|
1196
|
+
}
|
|
1197
|
+
const encodeSpeed = encodePixelsPerSec / outputPixelsPerSec;
|
|
1198
|
+
// What this very file has been seen to cost, when it has been: the clips are
|
|
1199
|
+
// H.264 and a source that has to be re-encoded usually is not, so a figure
|
|
1200
|
+
// taken from the encoder actually running on THIS source beats any model of
|
|
1201
|
+
// a stand-in. It arrives seconds into playback and replaces the estimate.
|
|
1202
|
+
const decodeSpeed = Number.isFinite(observedDecodeCostSec) && observedDecodeCostSec > 0
|
|
1203
|
+
? 1 / observedDecodeCostSec
|
|
1204
|
+
: (source ? decodeSpeedFor(decodeModel, source) : null);
|
|
1205
|
+
if (decodeSpeed === null) {
|
|
1206
|
+
return encodeSpeed;
|
|
1207
|
+
}
|
|
1208
|
+
return 1 / (1 / decodeSpeed + 1 / encodeSpeed);
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
/**
|
|
1212
|
+
* Whether this host can hold realtime, with the margin, while re-encoding this
|
|
1213
|
+
* source to this output pixel rate — and the predicted speed either way, so a
|
|
1214
|
+
* refusal can say what it refused on.
|
|
1215
|
+
*
|
|
1216
|
+
* The encoder figure is the FASTEST benchmarked preset: it is the best this
|
|
1217
|
+
* host can do, so a rung it cannot hold cannot be held at any quality setting.
|
|
1218
|
+
*
|
|
1219
|
+
* @param {{ benchmark: Array<{ preset: string, pixelsPerSec: number }>, decodeModel?: object | null, source?: { megapixelsPerSecond: number, megabitsPerSecond: number } | null, outputPixelsPerSec: number, requiredSpeed?: number | null }} params
|
|
1220
|
+
* @returns {{ speed: number | null, sustainable: boolean }}
|
|
1221
|
+
*/
|
|
1222
|
+
export function canSustainOutput({
|
|
1223
|
+
benchmark,
|
|
1224
|
+
decodeModel = null,
|
|
1225
|
+
source = null,
|
|
1226
|
+
outputPixelsPerSec,
|
|
1227
|
+
observedDecodeCostSec = null,
|
|
1228
|
+
concurrentCostSec = 0,
|
|
1229
|
+
requiredSpeed = null
|
|
1230
|
+
}) {
|
|
1231
|
+
if (!Array.isArray(benchmark) || benchmark.length === 0) {
|
|
1232
|
+
// Nothing measured on this host: the budget cannot refuse what it cannot
|
|
1233
|
+
// price, and refusing everything would leave a viewer with no rung at all.
|
|
1234
|
+
return { speed: null, sustainable: true };
|
|
1235
|
+
}
|
|
1236
|
+
const observed = Number.isFinite(observedDecodeCostSec) && observedDecodeCostSec > 0
|
|
1237
|
+
? observedDecodeCostSec
|
|
1238
|
+
: null;
|
|
1239
|
+
if (observed === null && !isDecodePriced({ decodeModel, source })) {
|
|
1240
|
+
// An encoder-only figure was several times too optimistic on the rung this
|
|
1241
|
+
// check exists for, so it is not fit to refuse anything. Without the decode
|
|
1242
|
+
// term the ladder is offered whole, exactly as it was before.
|
|
1243
|
+
return { speed: null, sustainable: true };
|
|
1244
|
+
}
|
|
1245
|
+
const alone = predictedRealtimeSpeed({
|
|
1246
|
+
decodeModel,
|
|
1247
|
+
encodePixelsPerSec: cheapestPresetPixelsPerSec(benchmark),
|
|
1248
|
+
outputPixelsPerSec,
|
|
1249
|
+
source,
|
|
1250
|
+
observedDecodeCostSec: observed
|
|
1251
|
+
});
|
|
1252
|
+
// What ELSE will be running while this rung is. A rung is never the only
|
|
1253
|
+
// thing on the machine: the picture it accompanies is being copied or
|
|
1254
|
+
// encoded, an audio track may have its own encoder, and a warm-up is two
|
|
1255
|
+
// encoders by design. Measured on the addon host, a copy alone takes about an
|
|
1256
|
+
// eighth of the machine per second of video, and the field case of
|
|
1257
|
+
// 2026-08-15 adds up exactly: 0.125 for the copy plus ~1.05 for the rung is
|
|
1258
|
+
// more than the one second per second the machine has, which is what was
|
|
1259
|
+
// observed.
|
|
1260
|
+
//
|
|
1261
|
+
// Zero when nothing else is known to be running, or when nothing has been
|
|
1262
|
+
// measured yet — then this is a LOWER bound on the cost and the check is as
|
|
1263
|
+
// permissive as it was before.
|
|
1264
|
+
const speed = alone === null || !(concurrentCostSec > 0)
|
|
1265
|
+
? alone
|
|
1266
|
+
: 1 / (1 / alone + concurrentCostSec);
|
|
1267
|
+
if (speed === null) {
|
|
1268
|
+
return { speed: null, sustainable: true };
|
|
1269
|
+
}
|
|
1270
|
+
return { speed, sustainable: speed >= speedBar(requiredSpeed) };
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/**
|
|
1274
|
+
* The speed a step has to reach to be worth offering.
|
|
1275
|
+
*
|
|
1276
|
+
* Realtime is not enough on its own: a step that produces exactly one second
|
|
1277
|
+
* per second never recovers the seconds lost while its reader waits for the
|
|
1278
|
+
* swarm, so it survives its own supply only if what it gains between
|
|
1279
|
+
* interruptions covers what one interruption costs. That is measured per file
|
|
1280
|
+
* and per swarm by the reader — `1 + worst wait / median interval`, in
|
|
1281
|
+
* `supply-margin.js` — and on the field torrent of 2026-08-17 it came to 1.67
|
|
1282
|
+
* against the 1.5 that used to stand here, and to 4.04-8.14 on a torrent whose
|
|
1283
|
+
* swarm no encoder could have kept up with.
|
|
1284
|
+
*
|
|
1285
|
+
* Where that figure does not exist yet — fewer than two interruptions measured
|
|
1286
|
+
* — the bar is realtime. It is the one thing that can be said without
|
|
1287
|
+
* measuring the swarm, and the offer is restated as soon as the reader has
|
|
1288
|
+
* something to say.
|
|
1289
|
+
*
|
|
1290
|
+
* @param {number | null | undefined} requiredSpeed - What this file's own
|
|
1291
|
+
* interruptions demand, when they have been measured.
|
|
1292
|
+
* @returns {number}
|
|
1293
|
+
*/
|
|
1294
|
+
export function speedBar(requiredSpeed) {
|
|
1295
|
+
return Number.isFinite(requiredSpeed) && requiredSpeed > REALTIME ? requiredSpeed : REALTIME;
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
/**
|
|
1299
|
+
* The bar for a cost description — the supply's demand where decoding is
|
|
1300
|
+
* priced, and never below the unpriced-decode bar where it is not.
|
|
1301
|
+
*
|
|
1302
|
+
* @param {{ decodeModel?: object | null, source?: object | null, observedDecodeCostSec?: number | null, requiredSpeed?: number | null }} cost
|
|
1303
|
+
* @returns {number}
|
|
1304
|
+
*/
|
|
1305
|
+
function barFor(cost) {
|
|
1306
|
+
const measured = speedBar(cost?.requiredSpeed);
|
|
1307
|
+
return isDecodePriced(cost) ? measured : Math.max(UNPRICED_DECODE_BAR, measured);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
/**
|
|
1311
|
+
* Benchmark software libx264 presets on this host. Encodes a short synthetic
|
|
1312
|
+
* clip at a fixed reference resolution with each preset and measures encoder
|
|
1313
|
+
* throughput in pixels/second. The session manager uses this to pick, per
|
|
1314
|
+
* stream, the highest-quality preset that still encodes the actual
|
|
1315
|
+
* (source-capped) resolution faster than realtime.
|
|
1316
|
+
*
|
|
1317
|
+
* Runs once at startup; bounded by a per-encode timeout. Presets that fail are
|
|
1318
|
+
* omitted from the result.
|
|
1319
|
+
*
|
|
1320
|
+
* @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void } }} options
|
|
1321
|
+
* @returns {Promise<Array<{ preset: string, pixelsPerSec: number }>>} Ordered slowest→fastest.
|
|
1322
|
+
*/
|
|
1323
|
+
export async function benchmarkSoftwarePresets({ ffmpegBin, logger, encoder = null }) {
|
|
1324
|
+
const log = logger ?? { info: () => {}, warn: () => {} };
|
|
1325
|
+
|
|
1326
|
+
// REAL footage, decoded ONCE into raw frames, and the presets are then timed
|
|
1327
|
+
// on those frames.
|
|
1328
|
+
//
|
|
1329
|
+
// Two reasons, both measured. The pattern this replaced (`testsrc2`) has flat
|
|
1330
|
+
// areas and no grain and encodes 1.23x cheaper than film on the same machine
|
|
1331
|
+
// and preset — an error that always points at offering a rung the host cannot
|
|
1332
|
+
// hold. And feeding a compressed clip to each preset instead would put
|
|
1333
|
+
// decoding and scaling inside the measurement: subtracting them afterwards
|
|
1334
|
+
// compares a wall clock that includes process startup against a decode figure
|
|
1335
|
+
// measured to exclude it, while inside one ffmpeg the two halves overlap. On
|
|
1336
|
+
// the fastest preset — the one every ladder decision reads as the ceiling —
|
|
1337
|
+
// that subtraction is most of the number being measured, so a small error in
|
|
1338
|
+
// it becomes a large error in the answer.
|
|
1339
|
+
//
|
|
1340
|
+
// Raw frames remove all of it: no decoder, no scaler, nothing to subtract,
|
|
1341
|
+
// and no dependence on the decode model. The cost is 25 MB of memory in a
|
|
1342
|
+
// pipe for a few seconds.
|
|
1343
|
+
const rawFramesPath = await decodeToRawFrames(ffmpegBin, log);
|
|
1344
|
+
if (rawFramesPath === null) {
|
|
1345
|
+
// Said once more, in the words that matter to whoever reads the log next:
|
|
1346
|
+
// with no benchmark, `#sustainableHeights` filters nothing and every rung
|
|
1347
|
+
// is offered, which is the failure of 2026-08-14 in full.
|
|
1348
|
+
log.warn("hwaccel: the quality ladder is UNFILTERED on this host — nothing measured the encoder");
|
|
1349
|
+
return [];
|
|
1350
|
+
}
|
|
1351
|
+
/** @type {Array<{ preset: string, pixelsPerSec: number }>} */
|
|
1352
|
+
const results = [];
|
|
1353
|
+
try {
|
|
1354
|
+
// THE CHOSEN ENCODER'S OWN LADDER, whatever kind it is. NVENC walks p1…p7,
|
|
1355
|
+
// QSV veryfast…veryslow, VAAPI its quality levels. A kind with no ladder is
|
|
1356
|
+
// measured once, which is still a reading where there was none at all.
|
|
1357
|
+
const ladder = encoder?.speedLadder;
|
|
1358
|
+
const rungs = Array.isArray(ladder?.values) && ladder.values.length > 0 ? ladder.values : [null];
|
|
1359
|
+
for (const rung of rungs) {
|
|
1360
|
+
const speed = await measureEncodeSlope(ffmpegBin, encoder, rung, rawFramesPath);
|
|
1361
|
+
if (speed === null) {
|
|
1362
|
+
log.warn(`hwaccel: the benchmark of "${rung ?? encoder?.name}" produced no usable reading; skipping`);
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
const pixelsPerSec = BENCHMARK_REF_W * BENCHMARK_REF_H * TRANSCODE_FPS * speed;
|
|
1366
|
+
results.push({ preset: rung ?? encoder?.name, pixelsPerSec });
|
|
1367
|
+
log.info(
|
|
1368
|
+
`hwaccel: ${encoder?.name} "${rung ?? "as it comes"}" ~= ${(pixelsPerSec / 1e6).toFixed(1)} Mpx/s ` +
|
|
1369
|
+
`(${speed.toFixed(2)}x @ ${BENCHMARK_REF_W}x${BENCHMARK_REF_H}, real footage)`
|
|
1370
|
+
);
|
|
1371
|
+
}
|
|
1372
|
+
} finally {
|
|
1373
|
+
// The encoder was killed a moment ago and on Windows the handle outlives
|
|
1374
|
+
// the signal, so removal is retried and its failure is not worth a session:
|
|
1375
|
+
// this is a temp directory the operating system will clear anyway.
|
|
1376
|
+
try {
|
|
1377
|
+
rmSync(path.dirname(rawFramesPath), { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
|
|
1378
|
+
} catch (error) {
|
|
1379
|
+
log.warn(`hwaccel: could not remove the benchmark's raw frames: ${error instanceof Error ? error.message : String(error)}`);
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
return results;
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
/**
|
|
1386
|
+
* How fast one preset encodes, from ffmpeg's own reports of how much video it
|
|
1387
|
+
* has written — not from the clock around the process.
|
|
1388
|
+
*
|
|
1389
|
+
* Timing whole runs measures the run STARTING. Measured 2026-08-15 on a desktop
|
|
1390
|
+
* that spawns ffmpeg in ~0.4 s: three seconds of raw frames encoded that way
|
|
1391
|
+
* put `fast` and `ultrafast` within 1.24x of each other, when libx264's own
|
|
1392
|
+
* presets differ by several times — the constant had swallowed the difference.
|
|
1393
|
+
* The slope between two progress reports contains no part of the startup.
|
|
1394
|
+
*
|
|
1395
|
+
* The frames are written repeatedly so there is runway to measure over,
|
|
1396
|
+
* whatever the preset's speed.
|
|
1397
|
+
*
|
|
1398
|
+
* @param {string} ffmpegBin
|
|
1399
|
+
* @param {string} preset
|
|
1400
|
+
* @param {string} rawFramesPath
|
|
1401
|
+
* @returns {Promise<number | null>} Video seconds encoded per second of clock.
|
|
1402
|
+
*/
|
|
1403
|
+
/**
|
|
1404
|
+
* Video seconds produced per second of clock, from ffmpeg's own reports.
|
|
1405
|
+
*
|
|
1406
|
+
* Startup is excluded by taking a DIFFERENCE: it lands in the wall clock of
|
|
1407
|
+
* every report equally, so it cancels between two of them. (The decode
|
|
1408
|
+
* benchmark drops its first report instead, because there the first one is
|
|
1409
|
+
* emitted at out_time zero; here reports with no time yet are discarded before
|
|
1410
|
+
* they arrive, so the first kept one is already running.)
|
|
1411
|
+
*
|
|
1412
|
+
* @param {Array<{ wallSec: number, outSec: number }>} samples
|
|
1413
|
+
* @param {number} [minimumWindowSec=ENCODE_BENCHMARK_WINDOW_SEC]
|
|
1414
|
+
* @returns {number | null}
|
|
1415
|
+
*/
|
|
1416
|
+
export function slopeOf(samples, minimumWindowSec = ENCODE_BENCHMARK_WINDOW_SEC) {
|
|
1417
|
+
const first = samples[0];
|
|
1418
|
+
const last = samples[samples.length - 1];
|
|
1419
|
+
if (!first || !last || first === last) {
|
|
1420
|
+
return null;
|
|
1421
|
+
}
|
|
1422
|
+
const took = last.wallSec - first.wallSec;
|
|
1423
|
+
const produced = last.outSec - first.outSec;
|
|
1424
|
+
if (!(took >= minimumWindowSec) || !(produced > 0)) {
|
|
1425
|
+
return null;
|
|
1426
|
+
}
|
|
1427
|
+
const slope = produced / took;
|
|
1428
|
+
// Nothing encodes a thousand times realtime. A figure above that is a
|
|
1429
|
+
// measurement fault, and letting it through opens the whole ladder.
|
|
1430
|
+
return slope <= ENCODE_BENCHMARK_MAX_PLAUSIBLE_SPEED ? slope : null;
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
function measureEncodeSlope(ffmpegBin, encoder, rung, rawFramesPath) {
|
|
1434
|
+
return new Promise((resolve) => {
|
|
1435
|
+
const args = [
|
|
1436
|
+
"-hide_banner", "-loglevel", "error", "-nostats",
|
|
1437
|
+
"-stream_loop", "-1",
|
|
1438
|
+
"-f", "rawvideo", "-pix_fmt", "yuv420p",
|
|
1439
|
+
"-s", `${BENCHMARK_REF_W}x${BENCHMARK_REF_H}`, "-r", String(TRANSCODE_FPS),
|
|
1440
|
+
"-i", rawFramesPath,
|
|
1441
|
+
// THE ENCODER SAYS HOW TO MEASURE ITSELF. It was libx264 written here, so
|
|
1442
|
+
// a host with NVENC, QSV, VAAPI or V4L2M2M measured its encoder not at all
|
|
1443
|
+
// and the quality offer, which is arithmetic over pixels per second, had
|
|
1444
|
+
// no pixels per second to work with.
|
|
1445
|
+
...encoder.benchmarkArgs(rung),
|
|
1446
|
+
"-f", "null", "-",
|
|
1447
|
+
"-progress", "pipe:1"
|
|
1448
|
+
];
|
|
1449
|
+
/** @type {Array<{ wallSec: number, outSec: number }>} */
|
|
1450
|
+
const samples = [];
|
|
1451
|
+
let settled = false;
|
|
1452
|
+
let buffered = "";
|
|
1453
|
+
let child;
|
|
1454
|
+
const startedAt = Date.now();
|
|
1455
|
+
const finish = (value) => {
|
|
1456
|
+
if (settled) {
|
|
1457
|
+
return;
|
|
1458
|
+
}
|
|
1459
|
+
settled = true;
|
|
1460
|
+
clearTimeout(timer);
|
|
1461
|
+
try {
|
|
1462
|
+
child?.kill("SIGKILL");
|
|
1463
|
+
} catch {
|
|
1464
|
+
// already gone
|
|
1465
|
+
}
|
|
1466
|
+
resolve(value);
|
|
1467
|
+
};
|
|
1468
|
+
const timer = setTimeout(() => finish(null), ENCODE_BENCHMARK_TIMEOUT_MS);
|
|
1469
|
+
try {
|
|
1470
|
+
child = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
|
|
1471
|
+
} catch {
|
|
1472
|
+
finish(null);
|
|
1473
|
+
return;
|
|
1474
|
+
}
|
|
1475
|
+
// The frames come from a FILE, read on repeat by ffmpeg itself. Fed through
|
|
1476
|
+
// a pipe instead, the fastest presets measured the pipe: `ultrafast` on a
|
|
1477
|
+
// desktop wants raw frames at hundreds of megabytes a second, which no
|
|
1478
|
+
// writer here can supply, and the reading then describes the feeding rather
|
|
1479
|
+
// than the encoder.
|
|
1480
|
+
child.stdout.on("data", (chunk) => {
|
|
1481
|
+
buffered += String(chunk);
|
|
1482
|
+
let newline = buffered.indexOf(NEWLINE);
|
|
1483
|
+
while (newline >= 0) {
|
|
1484
|
+
const line = buffered.slice(0, newline).trim();
|
|
1485
|
+
buffered = buffered.slice(newline + 1);
|
|
1486
|
+
if (line.startsWith("out_time_ms=")) {
|
|
1487
|
+
const outSec = Number(line.slice("out_time_ms=".length)) / 1e6;
|
|
1488
|
+
// `N/A` is not the only way ffmpeg says "no position yet": some builds
|
|
1489
|
+
// print the smallest signed 64-bit integer, which IS finite and would
|
|
1490
|
+
// be taken for a position nine trillion seconds before the start.
|
|
1491
|
+
if (Number.isFinite(outSec) && outSec >= 0) {
|
|
1492
|
+
samples.push({ wallSec: (Date.now() - startedAt) / 1000, outSec });
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
newline = buffered.indexOf(NEWLINE);
|
|
1496
|
+
}
|
|
1497
|
+
const slope = slopeOf(samples);
|
|
1498
|
+
if (slope !== null) {
|
|
1499
|
+
finish(slope);
|
|
1500
|
+
}
|
|
1501
|
+
});
|
|
1502
|
+
child.on("error", () => finish(null));
|
|
1503
|
+
// A preset that finished before the window was wide enough is measured from
|
|
1504
|
+
// whatever it did report, provided two reports exist at all.
|
|
1505
|
+
// A preset that finished before the wide window was covered is still
|
|
1506
|
+
// measured — but never over a window of nothing. Two reports a millisecond
|
|
1507
|
+
// apart would divide a frame of video by that millisecond and call the host
|
|
1508
|
+
// twenty times faster than it is, and one such reading becomes the figure
|
|
1509
|
+
// every ladder decision is taken from.
|
|
1510
|
+
child.on("exit", () => finish(slopeOf(samples, ENCODE_BENCHMARK_MIN_WINDOW_SEC)));
|
|
1511
|
+
});
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
/**
|
|
1515
|
+
* The benchmark's footage as raw frames: the calibration clip, looped to the
|
|
1516
|
+
* benchmark's length and scaled to its size, decoded once.
|
|
1517
|
+
*
|
|
1518
|
+
* @param {string} ffmpegBin
|
|
1519
|
+
* @param {{ info: (m: string) => void, warn: (m: string) => void }} log
|
|
1520
|
+
* @returns {Promise<string | null>} Path to the raw frames, or null.
|
|
1521
|
+
*/
|
|
1522
|
+
async function decodeToRawFrames(ffmpegBin, log) {
|
|
1523
|
+
// A benchmark may leave a host unmeasured; it may never stop it from
|
|
1524
|
+
// starting. Before this the temp directory was made outside any guard, so a
|
|
1525
|
+
// read-only or missing TMPDIR rejected the promise that starts the proxy.
|
|
1526
|
+
let directory;
|
|
1527
|
+
try {
|
|
1528
|
+
directory = mkdtempSync(path.join(os.tmpdir(), "torrent-tv-bench-"));
|
|
1529
|
+
} catch (error) {
|
|
1530
|
+
log.warn(
|
|
1531
|
+
`hwaccel: no writable temp directory for the preset benchmark (${error instanceof Error ? error.message : String(error)}); ` +
|
|
1532
|
+
"presets unmeasured, so no quality rung will be refused on this host"
|
|
1533
|
+
);
|
|
1534
|
+
return null;
|
|
1535
|
+
}
|
|
1536
|
+
const rawPath = path.join(directory, "frames.yuv");
|
|
1537
|
+
const args = [
|
|
1538
|
+
"-hide_banner", "-loglevel", "error",
|
|
1539
|
+
"-stream_loop", "-1",
|
|
1540
|
+
"-i", path.join(CALIBRATION_DIR, CALIBRATION_CLIPS[0]),
|
|
1541
|
+
"-t", String(BENCHMARK_DURATION_SEC),
|
|
1542
|
+
"-vf", `scale=${BENCHMARK_REF_W}:${BENCHMARK_REF_H},fps=${TRANSCODE_FPS}`,
|
|
1543
|
+
"-an", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-y", rawPath
|
|
1544
|
+
];
|
|
1545
|
+
const { code } = await runFfmpeg(ffmpegBin, args, 30000);
|
|
1546
|
+
const expectedBytes = BENCHMARK_REF_W * BENCHMARK_REF_H * 1.5 * TRANSCODE_FPS * BENCHMARK_DURATION_SEC;
|
|
1547
|
+
let written = 0;
|
|
1548
|
+
try {
|
|
1549
|
+
written = statSync(rawPath).size;
|
|
1550
|
+
} catch {
|
|
1551
|
+
written = 0;
|
|
1552
|
+
}
|
|
1553
|
+
if (code !== 0 || written < expectedBytes * 0.9) {
|
|
1554
|
+
log.warn(
|
|
1555
|
+
"hwaccel: could not decode the calibration clip for the preset benchmark " +
|
|
1556
|
+
`(${written} of ~${Math.round(expectedBytes)} bytes); presets unmeasured, ` +
|
|
1557
|
+
"so no quality rung will be refused on this host"
|
|
1558
|
+
);
|
|
1559
|
+
try {
|
|
1560
|
+
rmSync(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
|
|
1561
|
+
} catch {
|
|
1562
|
+
// A temp directory the operating system will clear; not worth a start-up.
|
|
1563
|
+
}
|
|
1564
|
+
return null;
|
|
1565
|
+
}
|
|
1566
|
+
return rawPath;
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
/**
|
|
1570
|
+
* Pick the highest-quality (slowest) benchmarked preset that can encode
|
|
1571
|
+
* `pixelsPerSecNeeded` with the speed margin. Falls back to the fastest
|
|
1572
|
+
* benchmarked preset, or `"ultrafast"` when no benchmark is available.
|
|
1573
|
+
*
|
|
1574
|
+
* @param {Array<{ preset: string, pixelsPerSec: number }>} benchmark - slowest→fastest
|
|
1575
|
+
* @param {number} pixelsPerSecNeeded
|
|
1576
|
+
* @param {{ decodeModel?: object | null, source?: { megapixelsPerSecond: number, megabitsPerSecond: number } | null, requiredSpeed?: number | null }} [cost]
|
|
1577
|
+
* @returns {string}
|
|
1578
|
+
*/
|
|
1579
|
+
/**
|
|
1580
|
+
* What this host can do at its CHEAPEST preset — the ceiling of the ladder.
|
|
1581
|
+
*
|
|
1582
|
+
* Deliberately not the largest reading in the array. The list is in quality
|
|
1583
|
+
* order, so its last measured entry is the cheapest preset; taking the maximum
|
|
1584
|
+
* instead would let one noisy reading of an expensive preset raise the bar that
|
|
1585
|
+
* decides which rungs are offered, and a rung offered on noise is a rung the
|
|
1586
|
+
* host cannot hold. For choosing a preset the direction of that error is
|
|
1587
|
+
* harmless; for deciding what to offer it is not, so the two use different
|
|
1588
|
+
* statistics on purpose.
|
|
1589
|
+
*
|
|
1590
|
+
* @param {Array<{ preset: string, pixelsPerSec: number }>} benchmark
|
|
1591
|
+
* @returns {number}
|
|
1592
|
+
*/
|
|
1593
|
+
function cheapestPresetPixelsPerSec(benchmark) {
|
|
1594
|
+
return benchmark[benchmark.length - 1]?.pixelsPerSec ?? 0;
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
export function pickSoftwarePreset(benchmark, pixelsPerSecNeeded, cost = {}) {
|
|
1598
|
+
if (!Array.isArray(benchmark) || benchmark.length === 0) {
|
|
1599
|
+
return "ultrafast";
|
|
1600
|
+
}
|
|
1601
|
+
const observed = Number.isFinite(cost?.observedDecodeCostSec) && cost.observedDecodeCostSec > 0
|
|
1602
|
+
? cost.observedDecodeCostSec
|
|
1603
|
+
: null;
|
|
1604
|
+
const bar = barFor(cost);
|
|
1605
|
+
// The FIRST entry that clears the bar wins — the list is in quality order, so
|
|
1606
|
+
// that is the best picture this host can hold. Every entry is examined rather
|
|
1607
|
+
// than the walk stopping at the first miss, because the measurements do not
|
|
1608
|
+
// always ascend with the list: on a busy machine on 2026-08-15 `faster` read
|
|
1609
|
+
// below `fast` twice.
|
|
1610
|
+
for (const entry of benchmark) {
|
|
1611
|
+
const speed = predictedRealtimeSpeed({
|
|
1612
|
+
decodeModel: cost.decodeModel ?? null,
|
|
1613
|
+
encodePixelsPerSec: entry.pixelsPerSec,
|
|
1614
|
+
outputPixelsPerSec: pixelsPerSecNeeded,
|
|
1615
|
+
source: cost.source ?? null,
|
|
1616
|
+
observedDecodeCostSec: observed
|
|
1617
|
+
});
|
|
1618
|
+
if (speed !== null && speed >= bar) {
|
|
1619
|
+
return entry.preset;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
// Nothing clears the bar: the cheapest preset, which is the last in quality
|
|
1623
|
+
// order. Returning whichever preset measured fastest would hand an expensive
|
|
1624
|
+
// one to a host that has just been shown to hold no rung at all.
|
|
1625
|
+
return benchmark[benchmark.length - 1].preset;
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
/**
|
|
1629
|
+
* Whether a cost description can actually price decoding — a fit AND a source
|
|
1630
|
+
* to apply it to. Without both, every prediction is encoder-only.
|
|
1631
|
+
*
|
|
1632
|
+
* @param {{ decodeModel?: object | null, source?: object | null }} cost
|
|
1633
|
+
* @returns {boolean}
|
|
1634
|
+
*/
|
|
1635
|
+
function isDecodePriced(cost) {
|
|
1636
|
+
if (Number.isFinite(cost?.observedDecodeCostSec) && cost.observedDecodeCostSec > 0) {
|
|
1637
|
+
return true; // measured on the source itself, which needs no fit to stand on
|
|
1638
|
+
}
|
|
1639
|
+
return Boolean(cost?.decodeModel) && Boolean(cost?.source);
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// Resolution-ladder heights (output height rungs), high→low. The ladder is
|
|
1643
|
+
// derived per-stream from the ceiling (the client-requested, source-capped
|
|
1644
|
+
// output box): only rungs at or below the ceiling height are used, so the
|
|
1645
|
+
// budget never upscales past what the client asked for. Standard heights keep
|
|
1646
|
+
// the downscaled output at familiar resolutions.
|
|
1647
|
+
const RESOLUTION_LADDER_HEIGHTS = [2160, 1440, 1080, 720, 540, 480, 360, 240];
|
|
1648
|
+
|
|
1649
|
+
/**
|
|
1650
|
+
* Build the resolution ladder for a ceiling box. Returns candidate output
|
|
1651
|
+
* dimensions from the ceiling downward, preserving the ceiling's aspect ratio,
|
|
1652
|
+
* each even-sized. The ceiling itself is always the top rung; ladder heights
|
|
1653
|
+
* at or above it are skipped (never upscale). Deduped by height.
|
|
1654
|
+
*
|
|
1655
|
+
* @param {number} ceilingWidth
|
|
1656
|
+
* @param {number} ceilingHeight
|
|
1657
|
+
* @returns {Array<{ width: number, height: number }>} high→low
|
|
1658
|
+
*/
|
|
1659
|
+
export function buildResolutionLadder(ceilingWidth, ceilingHeight) {
|
|
1660
|
+
const cw = Number.isInteger(ceilingWidth) && ceilingWidth > 0 ? ceilingWidth : 0;
|
|
1661
|
+
const ch = Number.isInteger(ceilingHeight) && ceilingHeight > 0 ? ceilingHeight : 0;
|
|
1662
|
+
if (!cw || !ch) {
|
|
1663
|
+
return [];
|
|
1664
|
+
}
|
|
1665
|
+
const even = (v) => {
|
|
1666
|
+
const r = Math.round(v);
|
|
1667
|
+
return Math.max(2, r - (r % 2));
|
|
1668
|
+
};
|
|
1669
|
+
/** @type {Array<{ width: number, height: number }>} */
|
|
1670
|
+
const rungs = [{ width: cw, height: ch }];
|
|
1671
|
+
for (const h of RESOLUTION_LADDER_HEIGHTS) {
|
|
1672
|
+
if (h >= ch) {
|
|
1673
|
+
continue; // at/above the ceiling — the ceiling rung already covers it
|
|
1674
|
+
}
|
|
1675
|
+
rungs.push({ width: even(cw * (h / ch)), height: h });
|
|
1676
|
+
}
|
|
1677
|
+
const seen = new Set();
|
|
1678
|
+
return rungs.filter((rung) => {
|
|
1679
|
+
if (seen.has(rung.height)) {
|
|
1680
|
+
return false;
|
|
1681
|
+
}
|
|
1682
|
+
seen.add(rung.height);
|
|
1683
|
+
return true;
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
/**
|
|
1688
|
+
* Choose the software encode settings (resolution + preset) that fit the
|
|
1689
|
+
* realtime budget on this host. From the resolution ladder (ceiling downward),
|
|
1690
|
+
* pick the HIGHEST rung whose encode throughput — predicted from the startup
|
|
1691
|
+
* benchmark's fastest preset — clears the speed this file's own supply
|
|
1692
|
+
* demands (`speedBar`). Then, at that resolution, pick the highest-quality
|
|
1693
|
+
* preset that still clears it. When even the lowest rung cannot clear it, use the lowest rung with
|
|
1694
|
+
* the fastest preset (best effort — a smaller picture beats sub-realtime
|
|
1695
|
+
* playback at full size). Returns null when no benchmark or ceiling is
|
|
1696
|
+
* available (the caller keeps the ceiling resolution and the default preset).
|
|
1697
|
+
*
|
|
1698
|
+
* @param {Array<{ preset: string, pixelsPerSec: number }>} benchmark - slowest→fastest
|
|
1699
|
+
* @param {{ width: number, height: number }} ceiling
|
|
1700
|
+
* @param {number} outputFps
|
|
1701
|
+
* @param {{ decodeModel?: object | null, source?: { megapixelsPerSecond: number, megabitsPerSecond: number } | null, requiredSpeed?: number | null }} [cost]
|
|
1702
|
+
* @returns {{ width: number, height: number, preset: string, ladder: Array<{ width: number, height: number }>, rungIndex: number } | null}
|
|
1703
|
+
*/
|
|
1704
|
+
export function chooseSoftwareEncodeSettings(benchmark, ceiling, outputFps, cost = {}) {
|
|
1705
|
+
if (!Array.isArray(benchmark) || benchmark.length === 0) {
|
|
1706
|
+
return null;
|
|
1707
|
+
}
|
|
1708
|
+
const fps = Number.isFinite(outputFps) && outputFps > 0 ? outputFps : TRANSCODE_FPS;
|
|
1709
|
+
const ladder = buildResolutionLadder(ceiling?.width, ceiling?.height);
|
|
1710
|
+
if (ladder.length === 0) {
|
|
1711
|
+
return null;
|
|
1712
|
+
}
|
|
1713
|
+
const fastest = cheapestPresetPixelsPerSec(benchmark); // the cheapest preset's throughput
|
|
1714
|
+
const bar = barFor(cost);
|
|
1715
|
+
let chosenIndex = ladder.length - 1; // default: lowest rung (best effort)
|
|
1716
|
+
for (let i = 0; i < ladder.length; i += 1) {
|
|
1717
|
+
const speed = predictedRealtimeSpeed({
|
|
1718
|
+
decodeModel: cost.decodeModel ?? null,
|
|
1719
|
+
encodePixelsPerSec: fastest,
|
|
1720
|
+
outputPixelsPerSec: ladder[i].width * ladder[i].height * fps,
|
|
1721
|
+
source: cost.source ?? null
|
|
1722
|
+
});
|
|
1723
|
+
if (speed !== null && speed >= bar) {
|
|
1724
|
+
chosenIndex = i;
|
|
1725
|
+
break;
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
const chosen = ladder[chosenIndex];
|
|
1729
|
+
const preset = pickSoftwarePreset(benchmark, chosen.width * chosen.height * fps, cost);
|
|
1730
|
+
return { width: chosen.width, height: chosen.height, preset, ladder, rungIndex: chosenIndex };
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
/**
|
|
1734
|
+
* How fast this machine COPIES a picture, in seconds of film per second.
|
|
1735
|
+
*
|
|
1736
|
+
* The startup measurements price encoding and decoding, and a copied picture
|
|
1737
|
+
* does neither: it reads packets and writes them out again. That left one whole
|
|
1738
|
+
* branch of what this proxy does with no figure at all, and a figure is what
|
|
1739
|
+
* every decision in the encoding layer is made from — where to put an encoder,
|
|
1740
|
+
* how many to run, whether anybody will be left waiting. Without it a copied
|
|
1741
|
+
* output was planned with no speed until its own run had been running long
|
|
1742
|
+
* enough to report one, which is exactly the moment the plan matters most.
|
|
1743
|
+
*
|
|
1744
|
+
* Measured the same way as the others: ffmpeg's own progress, read as a slope
|
|
1745
|
+
* over a window, so the process starting is outside the figure.
|
|
1746
|
+
*
|
|
1747
|
+
* The clip is joined to itself first rather than looped with `-stream_loop`.
|
|
1748
|
+
* Looping charges a re-initialisation per lap — measured on the addon host at
|
|
1749
|
+
* 0.03 s for 480p and 0.12 s for 1080p — and a copy of a five-second clip laps
|
|
1750
|
+
* many times a second, so the reading would have been mostly re-initialisation.
|
|
1751
|
+
*
|
|
1752
|
+
* @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, clipsDir?: string }} params
|
|
1753
|
+
* @returns {Promise<number | null>} Seconds of film per second, or null where
|
|
1754
|
+
* the reading could not be taken. Null means unmeasured and is never a
|
|
1755
|
+
* substitute for a number.
|
|
1756
|
+
*/
|
|
1757
|
+
export async function benchmarkCopySpeed({ ffmpegBin, logger, clipsDir = CALIBRATION_DIR }) {
|
|
1758
|
+
const log = logger ?? { info: () => {}, warn: () => {} };
|
|
1759
|
+
const startedAt = Date.now();
|
|
1760
|
+
// The largest clip in the set. A copy moves BYTES, so what it can do is a
|
|
1761
|
+
// statement about the biggest pictures this host will be asked to pass
|
|
1762
|
+
// through, and the small ones are covered by the same figure.
|
|
1763
|
+
const clip = path.join(clipsDir, "cal-h264-1080-hi.mp4");
|
|
1764
|
+
const speed = await measureCopySlope(ffmpegBin, clip);
|
|
1765
|
+
if (!(speed > 0)) {
|
|
1766
|
+
log.warn("hwaccel: copying could not be measured; a copied picture will be planned from its own run instead");
|
|
1767
|
+
return null;
|
|
1768
|
+
}
|
|
1769
|
+
log.info(
|
|
1770
|
+
`hwaccel: this host copies a picture at ${speed.toFixed(0)}x realtime ` +
|
|
1771
|
+
`(measured in ${((Date.now() - startedAt) / 1000).toFixed(1)}s)`
|
|
1772
|
+
);
|
|
1773
|
+
return speed;
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
/**
|
|
1777
|
+
* Seconds of film per second, copying one file, read from ffmpeg's progress.
|
|
1778
|
+
*
|
|
1779
|
+
* @param {string} ffmpegBin
|
|
1780
|
+
* @param {string} filePath
|
|
1781
|
+
* @returns {Promise<number | null>}
|
|
1782
|
+
*/
|
|
1783
|
+
function measureCopySlope(ffmpegBin, filePath) {
|
|
1784
|
+
return new Promise((resolve) => {
|
|
1785
|
+
const args = [
|
|
1786
|
+
"-hide_banner", "-loglevel", "error", "-nostats",
|
|
1787
|
+
// Played over and over, because a copy gets through a five-second clip in
|
|
1788
|
+
// milliseconds and a slope needs a window to be taken over. Looping
|
|
1789
|
+
// charges the demuxer being re-opened once a lap, so what comes out is a
|
|
1790
|
+
// FLOOR on what this host can copy — the safe direction, since a plan made
|
|
1791
|
+
// from it expects copying to be slower than it is.
|
|
1792
|
+
"-stream_loop", "-1", "-i", filePath,
|
|
1793
|
+
// What a copied output does: packets in, packets out, nothing decoded and
|
|
1794
|
+
// nothing encoded. Written nowhere, so the figure is this machine's own
|
|
1795
|
+
// handling and not the disk under a temp directory.
|
|
1796
|
+
"-c", "copy", "-f", "null", "-",
|
|
1797
|
+
// Progress is reported every half second by default, which over a window
|
|
1798
|
+
// of one second is two readings. This asks for twenty.
|
|
1799
|
+
"-stats_period", "0.05",
|
|
1800
|
+
"-progress", "pipe:1"
|
|
1801
|
+
];
|
|
1802
|
+
/** @type {Array<{ wallSec: number, outSec: number }>} */
|
|
1803
|
+
const samples = [];
|
|
1804
|
+
let settled = false;
|
|
1805
|
+
let buffered = "";
|
|
1806
|
+
let child;
|
|
1807
|
+
const startedAt = Date.now();
|
|
1808
|
+
const finish = (value) => {
|
|
1809
|
+
if (settled) {
|
|
1810
|
+
return;
|
|
1811
|
+
}
|
|
1812
|
+
settled = true;
|
|
1813
|
+
clearTimeout(timer);
|
|
1814
|
+
try {
|
|
1815
|
+
child?.kill("SIGKILL");
|
|
1816
|
+
} catch {
|
|
1817
|
+
// already gone
|
|
1818
|
+
}
|
|
1819
|
+
resolve(value);
|
|
1820
|
+
};
|
|
1821
|
+
const timer = setTimeout(() => finish(null), ENCODE_BENCHMARK_TIMEOUT_MS);
|
|
1822
|
+
try {
|
|
1823
|
+
child = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
|
|
1824
|
+
} catch {
|
|
1825
|
+
finish(null);
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
child.stdout.on("data", (chunk) => {
|
|
1829
|
+
buffered += String(chunk);
|
|
1830
|
+
let newline = buffered.indexOf(NEWLINE);
|
|
1831
|
+
while (newline >= 0) {
|
|
1832
|
+
const line = buffered.slice(0, newline).trim();
|
|
1833
|
+
buffered = buffered.slice(newline + 1);
|
|
1834
|
+
if (line.startsWith("out_time_ms=")) {
|
|
1835
|
+
const outSec = Number(line.slice("out_time_ms=".length)) / 1e6;
|
|
1836
|
+
if (Number.isFinite(outSec) && outSec >= 0) {
|
|
1837
|
+
samples.push({ wallSec: (Date.now() - startedAt) / 1000, outSec });
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
newline = buffered.indexOf(NEWLINE);
|
|
1841
|
+
}
|
|
1842
|
+
const slope = slopeOf(samples);
|
|
1843
|
+
if (slope !== null) {
|
|
1844
|
+
finish(slope);
|
|
1845
|
+
}
|
|
1846
|
+
});
|
|
1847
|
+
child.on("error", () => finish(null));
|
|
1848
|
+
child.on("exit", () => finish(slopeOf(samples, ENCODE_BENCHMARK_MIN_WINDOW_SEC)));
|
|
1849
|
+
});
|
|
1850
|
+
}
|