forked from Storyboard-fm/little-media-box
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mux.js
95 lines (81 loc) · 2.32 KB
/
mux.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
const nanoprocess = require('nanoprocess')
const { Source } = require('./source')
const settings = require('./settings')
const rimraf = require('rimraf')
const Batch = require('batch')
const once = require('once')
const url = require('url')
/**
* @public
* @param {Array<String|Source>} sources
* @param {Object} opts
* @param {?(Boolean)} opts.append
* @param {String} opts.output
* @param {?(Boolean)} opts.strict
* @param {Function}
*/
function mux(sources, opts, callback) {
const batch = new Batch()
// callback may be called several times, lets ensure it is called
// only once
callback = once(callback)
// ensures all items in `sources` are `Source` instances
sources = sources.map((source) => Source.from(source))
// open all sources
for (const source of sources) {
batch.push((next) => source.open(next))
}
batch.end((err) => {
if (err) { return callback(err) }
const args = ['--output', opts.output]
if (true === opts.append) {
for (const source of sources) {
if (source === sources[0]) {
args.push(source.pathname)
} else {
args.push(`+${source.pathname}`)
}
}
} else {
args.push(...sources.map((source) => source.pathname))
}
const mkvmerge = nanoprocess(settings.bin.mkvmerge, args, {
stdio: 'pipe'
})
const stdout = []
const stderr = []
rimraf(opts.output, (err) => {
if (err) { return callback(err) }
mkvmerge.open((err) => {
if (err) { return callback(err) }
mkvmerge.process.once('error', (err) => {
callback(err)
})
mkvmerge.stderr.on('data', (data) => {
stderr.push(data)
})
mkvmerge.stdout.on('data', (data) => {
stdout.push(data)
})
mkvmerge.process.on('close', (code) => {
if ((code > 0 && opts.strict) || code > 1) {
const message = Buffer.concat(stderr.length ? stderr : stdout)
return callback(Object.assign(new Error(message), { code }))
} else {
const output = Source.from(opts.output, opts)
output.open((err) => {
if (err) { return callback(err) }
callback(null, output)
})
}
})
})
})
})
}
/**
* Module exports.
*/
module.exports = {
mux
}