-
Notifications
You must be signed in to change notification settings - Fork 76
/
beamstreams.js
692 lines (619 loc) · 24.2 KB
/
beamstreams.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/*
Aerostat Beam Coder - Node.js native bindings to FFmpeg
Copyright (C) 2019 Streampunk Media Ltd.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
https://www.streampunk.media/ mailto:[email protected]
14 Ormiscaig, Aultbea, Achnasheen, IV22 2JJ U.K.
*/
const beamcoder = require('bindings')('beamcoder');
const { Writable, Readable, Transform } = require('stream');
const doTimings = false;
const timings = [];
function frameDicer(encoder, isAudio) {
let sampleBytes = 4; // Assume floating point 4 byte samples for now...
const numChannels = encoder.channels;
const dstNumSamples = encoder.frame_size;
let dstFrmBytes = dstNumSamples * sampleBytes;
const doDice = false === beamcoder.encoders()[encoder.name].capabilities.VARIABLE_FRAME_SIZE;
let lastFrm = null;
let lastBuf = [];
const nullBuf = [];
for (let b = 0; b < numChannels; ++b)
nullBuf.push(Buffer.alloc(0));
const addFrame = srcFrm => {
let result = [];
let dstFrm;
let curStart = 0;
if (!lastFrm) {
lastFrm = beamcoder.frame(srcFrm.toJSON());
lastBuf = nullBuf;
dstFrmBytes = dstNumSamples * sampleBytes;
}
if (lastBuf[0].length > 0)
dstFrm = beamcoder.frame(lastFrm.toJSON());
else
dstFrm = beamcoder.frame(srcFrm.toJSON());
dstFrm.nb_samples = dstNumSamples;
dstFrm.pkt_duration = dstNumSamples;
while (curStart + dstFrmBytes - lastBuf[0].length <= srcFrm.nb_samples * sampleBytes) {
const resFrm = beamcoder.frame(dstFrm.toJSON());
resFrm.data = lastBuf.map((d, i) =>
Buffer.concat([
d, srcFrm.data[i].slice(curStart, curStart + dstFrmBytes - d.length)],
dstFrmBytes));
result.push(resFrm);
dstFrm.pts += dstNumSamples;
dstFrm.pkt_dts += dstNumSamples;
curStart += dstFrmBytes - lastBuf[0].length;
lastFrm.pts = 0;
lastFrm.pkt_dts = 0;
lastBuf = nullBuf;
}
lastFrm.pts = dstFrm.pts;
lastFrm.pkt_dts = dstFrm.pkt_dts;
lastBuf = srcFrm.data.map(d => d.slice(curStart, srcFrm.nb_samples * sampleBytes));
return result;
};
const getLast = () => {
let result = [];
if (lastBuf[0].length > 0) {
const resFrm = beamcoder.frame(lastFrm.toJSON());
resFrm.data = lastBuf.map(d => d.slice(0));
resFrm.nb_samples = lastBuf[0].length / sampleBytes;
resFrm.pkt_duration = resFrm.nb_samples;
lastFrm.pts = 0;
lastBuf = nullBuf;
result.push(resFrm);
}
return result;
};
this.dice = (frames, flush = false) => {
if (isAudio && doDice) {
let result = frames.reduce((muxFrms, frm) => {
addFrame(frm).forEach(f => muxFrms.push(f));
return muxFrms;
}, []);
if (flush)
getLast().forEach(f => result.push(f));
return result;
}
return frames;
};
}
function serialBalancer(numStreams) {
let pending = [];
// initialise with negative ts and no pkt
// - there should be no output until each stream has sent its first packet
for (let s = 0; s < numStreams; ++s)
pending.push({ ts: -Number.MAX_VALUE, streamIndex: s });
const adjustTS = (pkt, srcTB, dstTB) => {
const adj = (srcTB[0] * dstTB[1]) / (srcTB[1] * dstTB[0]);
pkt.pts = Math.round(pkt.pts * adj);
pkt.dts = Math.round(pkt.dts * adj);
pkt.duration > 0 ? Math.round(pkt.duration * adj) : Math.round(adj);
};
const pullPkts = (pkt, streamIndex, ts) => {
return new Promise(resolve => {
Object.assign(pending[streamIndex], { pkt: pkt, ts: ts, resolve: resolve });
const minTS = pending.reduce((acc, pend) => Math.min(acc, pend.ts), Number.MAX_VALUE);
// console.log(streamIndex, pending.map(p => p.ts), minTS);
const nextPend = pending.find(pend => pend.pkt && (pend.ts === minTS));
if (nextPend) nextPend.resolve(nextPend.pkt);
if (!pkt) resolve();
});
};
this.writePkts = (packets, srcStream, dstStream, writeFn, final = false) => {
if (packets && packets.packets.length) {
return packets.packets.reduce(async (promise, pkt) => {
await promise;
pkt.stream_index = dstStream.index;
adjustTS(pkt, srcStream.time_base, dstStream.time_base);
const pktTS = pkt.pts * dstStream.time_base[0] / dstStream.time_base[1];
return writeFn(await pullPkts(pkt, dstStream.index, pktTS));
}, Promise.resolve());
} else if (final)
return pullPkts(null, dstStream.index, Number.MAX_VALUE);
};
}
function parallelBalancer(params, streamType, numStreams) {
let resolveGet = null;
const tag = 'video' === streamType ? 'v' : 'a';
const pending = [];
// initialise with negative ts and no pkt
// - there should be no output until each stream has sent its first packet
for (let s = 0; s < numStreams; ++s)
pending.push({ ts: -Number.MAX_VALUE, streamIndex: s });
const makeSet = resolve => {
if (resolve) {
// console.log('makeSet', pending.map(p => p.ts));
const nextPends = pending.every(pend => pend.pkt) ? pending : null;
const final = pending.filter(pend => true === pend.final);
if (nextPends) {
nextPends.forEach(pend => pend.resolve());
resolve({
value: nextPends.map(pend => {
return { name: `in${pend.streamIndex}:${tag}`, frames: [ pend.pkt ] }; }),
done: false });
resolveGet = null;
pending.forEach(pend => Object.assign(pend, { pkt: null, ts: Number.MAX_VALUE }));
} else if (final.length > 0) {
final.forEach(f => f.resolve());
resolve({ done: true });
} else {
resolveGet = resolve;
}
}
};
const pushPkt = async (pkt, streamIndex, ts) =>
new Promise(resolve => {
Object.assign(pending[streamIndex], { pkt: pkt, ts: ts, final: pkt ? false : true, resolve: resolve });
makeSet(resolveGet);
});
const pullSet = async () => new Promise(resolve => makeSet(resolve));
const readStream = new Readable({
objectMode: true,
highWaterMark: params.highWaterMark ? params.highWaterMark || 4 : 4,
read() {
(async () => {
const start = process.hrtime();
const reqTime = start[0] * 1e3 + start[1] / 1e6;
const result = await pullSet();
if (result.done)
this.push(null);
else {
result.value.timings = result.value[0].frames[0].timings;
result.value.timings[params.name] = { reqTime: reqTime, elapsed: process.hrtime(start)[1] / 1000000 };
this.push(result.value);
}
})();
},
});
readStream.pushPkts = (packets, stream, streamIndex, final = false) => {
if (packets && packets.frames.length) {
return packets.frames.reduce(async (promise, pkt) => {
await promise;
const ts = pkt.pts * stream.time_base[0] / stream.time_base[1];
pkt.timings = packets.timings;
return pushPkt(pkt, streamIndex, ts);
}, Promise.resolve());
} else if (final) {
return pushPkt(null, streamIndex, Number.MAX_VALUE);
}
};
return readStream;
}
function teeBalancer(params, numStreams) {
let resolvePush = null;
const pending = [];
for (let s = 0; s < numStreams; ++s)
pending.push({ frames: null, resolve: null, final: false });
const pullFrame = async index => {
return new Promise(resolve => {
if (pending[index].frames) {
resolve({ value: pending[index].frames, done: false });
Object.assign(pending[index], { frames: null, resolve: null });
} else if (pending[index].final)
resolve({ done: true });
else
pending[index].resolve = resolve;
if (resolvePush && pending.every(p => null === p.frames)) {
resolvePush();
resolvePush = null;
}
});
};
const readStreams = [];
for (let s = 0; s < numStreams; ++s)
readStreams.push(new Readable({
objectMode: true,
highWaterMark: params.highWaterMark ? params.highWaterMark || 4 : 4,
read() {
(async () => {
const start = process.hrtime();
const reqTime = start[0] * 1e3 + start[1] / 1e6;
const result = await pullFrame(s);
if (result.done)
this.push(null);
else {
result.value.timings[params.name] = { reqTime: reqTime, elapsed: process.hrtime(start)[1] / 1000000 };
this.push(result.value);
}
})();
},
}));
readStreams.pushFrames = frames => {
return new Promise(resolve => {
pending.forEach((p, index) => {
if (frames.length)
p.frames = frames[index].frames;
else
p.final = true;
});
pending.forEach(p => {
if (p.resolve) {
if (p.frames) {
p.frames.timings = frames.timings;
p.resolve({ value: p.frames, done: false });
} else if (p.final)
p.resolve({ done: true });
}
Object.assign(p, { frames: null, resolve: null });
});
resolvePush = resolve;
});
};
return readStreams;
}
function transformStream(params, processFn, flushFn, reject) {
return new Transform({
objectMode: true,
highWaterMark: params.highWaterMark ? params.highWaterMark || 4 : 4,
transform(val, encoding, cb) {
(async () => {
const start = process.hrtime();
const reqTime = start[0] * 1e3 + start[1] / 1e6;
const result = await processFn(val);
result.timings = val.timings;
if (result.timings)
result.timings[params.name] = { reqTime: reqTime, elapsed: process.hrtime(start)[1] / 1000000 };
cb(null, result);
})().catch(cb);
},
flush(cb) {
(async () => {
const result = flushFn ? await flushFn() : null;
if (result) result.timings = {};
cb(null, result);
})().catch(cb);
}
}).on('error', err => reject(err));
}
const calcStats = (arr, elem, prop) => {
const mean = arr.reduce((acc, cur) => cur[elem] ? acc + cur[elem][prop] : acc, 0) / arr.length;
const stdDev = Math.pow(arr.reduce((acc, cur) => cur[elem] ? acc + Math.pow(cur[elem][prop] - mean, 2) : acc, 0) / arr.length, 0.5);
const max = arr.reduce((acc, cur) => cur[elem] ? Math.max(cur[elem][prop], acc) : acc, 0);
const min = arr.reduce((acc, cur) => cur[elem] ? Math.min(cur[elem][prop], acc) : acc, Number.MAX_VALUE);
return { mean: mean, stdDev: stdDev, max: max, min: min };
};
function writeStream(params, processFn, finalFn, reject) {
return new Writable({
objectMode: true,
highWaterMark: params.highWaterMark ? params.highWaterMark || 4 : 4,
write(val, encoding, cb) {
(async () => {
const start = process.hrtime();
const reqTime = start[0] * 1e3 + start[1] / 1e6;
const result = await processFn(val);
if ('mux' === params.name) {
const pktTimings = val.timings;
pktTimings[params.name] = { reqTime: reqTime, elapsed: process.hrtime(start)[1] / 1000000 };
if (doTimings)
timings.push(pktTimings);
}
cb(null, result);
})().catch(cb);
},
final(cb) {
(async () => {
const result = finalFn ? await finalFn() : null;
if (doTimings && ('mux' === params.name)) {
const elapsedStats = {};
Object.keys(timings[0]).forEach(k => elapsedStats[k] = calcStats(timings.slice(10, -10), k, 'elapsed'));
console.log('elapsed:');
console.table(elapsedStats);
const absArr = timings.map(t => {
const absDelays = {};
const keys = Object.keys(t);
keys.forEach((k, i) => absDelays[k] = { reqDelta: i > 0 ? t[k].reqTime - t[keys[i-1]].reqTime : 0 });
return absDelays;
});
const absStats = {};
Object.keys(absArr[0]).forEach(k => absStats[k] = calcStats(absArr.slice(10, -10), k, 'reqDelta'));
console.log('request time delta:');
console.table(absStats);
const totalsArr = timings.map(t => {
const total = (t.mux && t.read) ? t.mux.reqTime - t.read.reqTime + t.mux.elapsed : 0;
return { total: { total: total }};
});
console.log('total time:');
console.table(calcStats(totalsArr.slice(10, -10), 'total', 'total'));
}
cb(null, result);
})().catch(cb);
}
}).on('error', err => reject(err));
}
function readStream(params, demuxer, ms, index) {
const time_base = demuxer.streams[index].time_base;
const end_pts = ms ? ms.end * time_base[1] / time_base[0] : Number.MAX_SAFE_INTEGER;
async function getPacket() {
let packet = null;
do { packet = await demuxer.read(); }
while (packet && packet.stream_index !== index);
return packet;
}
return new Readable({
objectMode: true,
highWaterMark: params.highWaterMark ? params.highWaterMark || 4 : 4,
read() {
(async () => {
const start = process.hrtime();
const reqTime = start[0] * 1e3 + start[1] / 1e6;
const packet = await getPacket();
if (packet && (packet.pts < end_pts)) {
packet.timings = {};
packet.timings.read = { reqTime: reqTime, elapsed: process.hrtime(start)[1] / 1000000 };
this.push(packet);
} else
this.push(null);
})();
}
});
}
function createBeamWritableStream(params, governor) {
const beamStream = new Writable({
highWaterMark: params.highwaterMark || 16384,
write: (chunk, encoding, cb) => {
(async () => {
await governor.write(chunk);
cb();
})();
}
});
return beamStream;
}
function demuxerStream(params) {
const governor = new beamcoder.governor({});
const stream = createBeamWritableStream(params, governor);
stream.on('finish', () => governor.finish());
stream.on('error', console.error);
stream.demuxer = options => {
options.governor = governor;
// delay initialisation of demuxer until stream has been written to - avoids lock-up
return new Promise(resolve => setTimeout(async () => resolve(await beamcoder.demuxer(options)), 20));
};
return stream;
}
function createBeamReadableStream(params, governor) {
const beamStream = new Readable({
highWaterMark: params.highwaterMark || 16384,
read: size => {
(async () => {
const chunk = await governor.read(size);
if (0 === chunk.length)
beamStream.push(null);
else
beamStream.push(chunk);
})();
}
});
return beamStream;
}
function muxerStream(params) {
const governor = new beamcoder.governor({ highWaterMark: 1 });
const stream = createBeamReadableStream(params, governor);
stream.on('end', () => governor.finish());
stream.on('error', console.error);
stream.muxer = options => {
options.governor = governor;
return beamcoder.muxer(options);
};
return stream;
}
async function makeSources(params) {
if (!params.video) params.video = [];
if (!params.audio) params.audio = [];
params.video.forEach(p => p.sources.forEach(src => {
if (src.input_stream) {
const demuxerStream = beamcoder.demuxerStream({ highwaterMark: 1024 });
src.input_stream.pipe(demuxerStream);
src.format = demuxerStream.demuxer({ iformat: src.iformat, options: src.options });
} else
src.format = beamcoder.demuxer({ url: src.url, iformat: src.iformat, options: src.options });
}));
params.audio.forEach(p => p.sources.forEach(src => {
if (src.input_stream) {
const demuxerStream = beamcoder.demuxerStream({ highwaterMark: 1024 });
src.input_stream.pipe(demuxerStream);
src.format = demuxerStream.demuxer({ iformat: src.iformat, options: src.options });
} else
src.format = beamcoder.demuxer({ url: src.url, iformat: src.iformat, options: src.options });
}));
await params.video.reduce(async (promise, p) => {
await promise;
return p.sources.reduce(async (promise, src) => {
await promise;
src.format = await src.format;
if (src.ms && !src.input_stream)
src.format.seek({ time: src.ms.start });
return src.format;
}, Promise.resolve());
}, Promise.resolve());
await params.audio.reduce(async (promise, p) => {
await promise;
return p.sources.reduce(async (promise, src) => {
await promise;
src.format = await src.format;
if (src.ms && !src.input_stream)
src.format.seek({ time: src.ms.start });
return src.format;
}, Promise.resolve());
}, Promise.resolve());
params.video.forEach(p => p.sources.forEach(src =>
src.stream = readStream({ highWaterMark : 1 }, src.format, src.ms, src.streamIndex)));
params.audio.forEach(p => p.sources.forEach(src =>
src.stream = readStream({ highWaterMark : 1 }, src.format, src.ms, src.streamIndex)));
}
function runStreams(streamType, sources, filterer, streams, mux, muxBalancer) {
return new Promise((resolve, reject) => {
if (!sources.length)
return resolve();
const timeBaseStream = sources[0].format.streams[sources[0].streamIndex];
const filterBalancer = parallelBalancer({ name: 'filterBalance', highWaterMark : 1 }, streamType, sources.length);
sources.forEach((src, srcIndex) => {
const decStream = transformStream({ name: 'decode', highWaterMark : 1 },
pkts => src.decoder.decode(pkts), () => src.decoder.flush(), reject);
const filterSource = writeStream({ name: 'filterSource', highWaterMark : 1 },
pkts => filterBalancer.pushPkts(pkts, src.format.streams[src.streamIndex], srcIndex),
() => filterBalancer.pushPkts(null, src.format.streams[src.streamIndex], srcIndex, true), reject);
src.stream.pipe(decStream).pipe(filterSource);
});
const streamTee = teeBalancer({ name: 'streamTee', highWaterMark : 1 }, streams.length);
const filtStream = transformStream({ name: 'filter', highWaterMark : 1 }, frms => {
if (filterer.cb) filterer.cb(frms[0].frames[0].pts);
return filterer.filter(frms);
}, () => {}, reject);
const streamSource = writeStream({ name: 'streamSource', highWaterMark : 1 },
frms => streamTee.pushFrames(frms), () => streamTee.pushFrames([], true), reject);
filterBalancer.pipe(filtStream).pipe(streamSource);
streams.forEach((str, i) => {
const dicer = new frameDicer(str.encoder, 'audio' === streamType);
const diceStream = transformStream({ name: 'dice', highWaterMark : 1 },
frms => dicer.dice(frms), () => dicer.dice([], true), reject);
const encStream = transformStream({ name: 'encode', highWaterMark : 1 },
frms => str.encoder.encode(frms), () => str.encoder.flush(), reject);
const muxStream = writeStream({ name: 'mux', highWaterMark : 1 },
pkts => muxBalancer.writePkts(pkts, timeBaseStream, str.stream, pkts => mux.writeFrame(pkts)),
() => muxBalancer.writePkts(null, timeBaseStream, str.stream, pkts => mux.writeFrame(pkts), true), reject);
muxStream.on('finish', resolve);
streamTee[i].pipe(diceStream).pipe(encStream).pipe(muxStream);
});
});
}
async function makeStreams(params) {
params.video.forEach(p => {
p.sources.forEach(src =>
src.decoder = beamcoder.decoder({ demuxer: src.format, stream_index: src.streamIndex }));
});
params.audio.forEach(p => {
p.sources.forEach(src =>
src.decoder = beamcoder.decoder({ demuxer: src.format, stream_index: src.streamIndex }));
});
params.video.forEach(p => {
p.filter = beamcoder.filterer({
filterType: 'video',
inputParams: p.sources.map((src, i) => {
const stream = src.format.streams[src.streamIndex];
return {
name: `in${i}:v`,
width: stream.codecpar.width,
height: stream.codecpar.height,
pixelFormat: stream.codecpar.format,
timeBase: stream.time_base,
pixelAspect: stream.sample_aspect_ratio };
}),
outputParams: p.streams.map((str, i) => { return { name: `out${i}:v`, pixelFormat: str.codecpar.format }; }),
filterSpec: p.filterSpec });
});
const vidFilts = await Promise.all(params.video.map(p => p.filter));
params.video.forEach((p, i) => p.filter = vidFilts[i]);
// params.video.forEach(p => console.log(p.filter.graph.dump()));
params.audio.forEach(p => {
p.filter = beamcoder.filterer({
filterType: 'audio',
inputParams: p.sources.map((src, i) => {
const stream = src.format.streams[src.streamIndex];
return {
name: `in${i}:a`,
sampleRate: src.decoder.sample_rate,
sampleFormat: src.decoder.sample_fmt,
channelLayout: src.decoder.channel_layout,
timeBase: stream.time_base };
}),
outputParams: p.streams.map((str, i) => {
return {
name: `out${i}:a`,
sampleRate: str.codecpar.sample_rate,
sampleFormat: str.codecpar.format,
channelLayout: str.codecpar.channel_layout }; }),
filterSpec: p.filterSpec });
});
const audFilts = await Promise.all(params.audio.map(p => p.filter));
params.audio.forEach((p, i) => p.filter = audFilts[i]);
// params.audio.forEach(p => console.log(p.filter.graph.dump()));
let mux;
if (params.out.output_stream) {
let muxerStream = beamcoder.muxerStream({ highwaterMark: 1024 });
muxerStream.pipe(params.out.output_stream);
mux = muxerStream.muxer({ format_name: params.out.formatName });
} else
mux = beamcoder.muxer({ format_name: params.out.formatName });
params.video.forEach(p => {
p.streams.forEach((str, i) => {
const encParams = p.filter.graph.filters.find(f => f.name === `out${i}:v`).inputs[0];
str.encoder = beamcoder.encoder({
name: str.name,
width: encParams.w,
height: encParams.h,
pix_fmt: encParams.format,
sample_aspect_ratio: encParams.sample_aspect_ratio,
time_base: encParams.time_base,
// framerate: [encParams.time_base[1], encParams.time_base[0]],
// bit_rate: 2000000,
// gop_size: 10,
// max_b_frames: 1,
// priv_data: { preset: 'slow' }
priv_data: { crf: 23 } }); // ... more required ...
});
});
params.audio.forEach(p => {
p.streams.forEach((str, i) => {
const encParams = p.filter.graph.filters.find(f => f.name === `out${i}:a`).inputs[0];
str.encoder = beamcoder.encoder({
name: str.name,
sample_fmt: encParams.format,
sample_rate: encParams.sample_rate,
channel_layout: encParams.channel_layout,
flags: { GLOBAL_HEADER: mux.oformat.flags.GLOBALHEADER } });
str.codecpar.frame_size = str.encoder.frame_size;
});
});
params.video.forEach(p => {
p.streams.forEach(str => {
str.stream = mux.newStream({
name: str.name,
time_base: str.time_base,
interleaved: true }); // Set to false for manual interleaving, true for automatic
Object.assign(str.stream.codecpar, str.codecpar);
});
});
params.audio.forEach(p => {
p.streams.forEach(str => {
str.stream = mux.newStream({
name: str.name,
time_base: str.time_base,
interleaved: true }); // Set to false for manual interleaving, true for automatic
Object.assign(str.stream.codecpar, str.codecpar);
});
});
return {
run: async () => {
await mux.openIO({
url: params.out.url ? params.out.url : '',
flags: params.out.flags ? params.out.flags : {}
});
await mux.writeHeader({ options: params.out.options ? params.out.options : {} });
const muxBalancer = new serialBalancer(mux.streams.length);
const muxStreamPromises = [];
params.video.forEach(p => muxStreamPromises.push(runStreams('video', p.sources, p.filter, p.streams, mux, muxBalancer)));
params.audio.forEach(p => muxStreamPromises.push(runStreams('audio', p.sources, p.filter, p.streams, mux, muxBalancer)));
await Promise.all(muxStreamPromises);
await mux.writeTrailer();
}
};
}
module.exports = {
demuxerStream,
muxerStream,
makeSources,
makeStreams
};