@kmamal/media-decoders 0.0.0-stage → 0.1.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/LICENSE +19 -0
- package/README.md +152 -2
- package/binding.gyp +138 -0
- package/package.json +61 -4
- package/scripts/build-ffmpeg.mjs +35 -0
- package/scripts/build.mjs +67 -0
- package/scripts/download-ffmpeg.mjs +25 -0
- package/scripts/download-release.mjs +20 -0
- package/scripts/install.mjs +26 -0
- package/scripts/util/common.js +54 -0
- package/src/javascript/audio-reader.js +121 -0
- package/src/javascript/byte-source.js +144 -0
- package/src/javascript/common.js +44 -0
- package/src/javascript/decode.js +272 -0
- package/src/javascript/events.js +80 -0
- package/src/javascript/feed.js +451 -0
- package/src/javascript/index.js +23 -0
- package/src/javascript/media-file.js +270 -0
- package/src/javascript/track-reader.js +45 -0
- package/src/javascript/video-reader.js +93 -0
- package/src/native/audio-feed-reader-core.cpp +322 -0
- package/src/native/audio-feed-reader-core.h +50 -0
- package/src/native/audio-feed-reader.cpp +166 -0
- package/src/native/audio-feed-reader.h +29 -0
- package/src/native/audio-feed-writer.cpp +364 -0
- package/src/native/audio-feed-writer.h +63 -0
- package/src/native/audio-feed.cpp +44 -0
- package/src/native/audio-feed.h +83 -0
- package/src/native/audio-pipeline.cpp +141 -0
- package/src/native/audio-pipeline.h +52 -0
- package/src/native/audio-track.cpp +236 -0
- package/src/native/audio-track.h +65 -0
- package/src/native/audio-trim.cpp +53 -0
- package/src/native/audio-trim.h +26 -0
- package/src/native/byte-source-state.h +48 -0
- package/src/native/byte-source.cpp +339 -0
- package/src/native/byte-source.h +35 -0
- package/src/native/codec.cpp +63 -0
- package/src/native/codec.h +36 -0
- package/src/native/env-registry.h +40 -0
- package/src/native/feed-binding.cpp +62 -0
- package/src/native/feed-binding.h +14 -0
- package/src/native/feed-link.cpp +89 -0
- package/src/native/feed-link.h +68 -0
- package/src/native/feed-reader-base.h +145 -0
- package/src/native/feed-reader-core-base.h +84 -0
- package/src/native/feed.cpp +146 -0
- package/src/native/feed.h +152 -0
- package/src/native/ffmpeg.h +34 -0
- package/src/native/file-binding.cpp +265 -0
- package/src/native/file-core.cpp +875 -0
- package/src/native/file-core.h +219 -0
- package/src/native/file-info.cpp +88 -0
- package/src/native/file-info.h +47 -0
- package/src/native/file.h +40 -0
- package/src/native/log-capture.cpp +46 -0
- package/src/native/log-capture.h +27 -0
- package/src/native/media-input.cpp +116 -0
- package/src/native/media-input.h +38 -0
- package/src/native/module.cpp +114 -0
- package/src/native/packet-decoder.cpp +216 -0
- package/src/native/packet-decoder.h +84 -0
- package/src/native/resampler.cpp +56 -0
- package/src/native/resampler.h +22 -0
- package/src/native/silent-track.cpp +23 -0
- package/src/native/silent-track.h +33 -0
- package/src/native/time-epsilon.h +6 -0
- package/src/native/track.cpp +117 -0
- package/src/native/track.h +142 -0
- package/src/native/video-feed-reader-core.cpp +164 -0
- package/src/native/video-feed-reader-core.h +47 -0
- package/src/native/video-feed-reader.cpp +132 -0
- package/src/native/video-feed-reader.h +33 -0
- package/src/native/video-feed-writer.cpp +213 -0
- package/src/native/video-feed-writer.h +44 -0
- package/src/native/video-feed.cpp +69 -0
- package/src/native/video-feed.h +78 -0
- package/src/native/video-output.cpp +245 -0
- package/src/native/video-output.h +68 -0
- package/src/native/video-track.cpp +453 -0
- package/src/native/video-track.h +107 -0
- package/src/types/index.d.ts +425 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
const { feedView, createAudioFeed, readerClosedError, readSignal, checkSampleRate, readChannelOptions, checkChannelArrays, AudioFeedReader } = require('./feed')
|
|
2
|
+
const { TrackReader } = require('./track-reader')
|
|
3
|
+
const { checkOptions, checkInteger } = require('./common')
|
|
4
|
+
|
|
5
|
+
const CHUNK_FRAMES = 16384
|
|
6
|
+
const BUFFER_FRAMES = 4 * CHUNK_FRAMES
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class AudioReader extends TrackReader {
|
|
10
|
+
constructor (file, track, options = {}, buffer = BUFFER_FRAMES) {
|
|
11
|
+
checkOptions(options)
|
|
12
|
+
super(file, track)
|
|
13
|
+
const { channels, maxChannels, sampleRate = track.sampleRate } = options
|
|
14
|
+
checkSampleRate(sampleRate)
|
|
15
|
+
const mix = readChannelOptions(channels, maxChannels)
|
|
16
|
+
this.sampleRate = sampleRate
|
|
17
|
+
this.channels = mix.fixed ? channels : Math.min(Math.max(1, track.channels), mix.count)
|
|
18
|
+
const feedOptions = mix.fixed
|
|
19
|
+
? { sampleRate, channels, buffer: buffer / sampleRate }
|
|
20
|
+
: { sampleRate, maxChannels: this.channels, buffer: buffer / sampleRate }
|
|
21
|
+
const feed = createAudioFeed()
|
|
22
|
+
try {
|
|
23
|
+
file._native.attach(track.index, feedView(feed))
|
|
24
|
+
this._feedReader = new AudioFeedReader(feed, feedOptions)
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
feed.destroy()
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
readChannels (frames, options) {
|
|
32
|
+
return this._readFrames(frames, false, options)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
readInterleaved (frames, options) {
|
|
36
|
+
return this._readFrames(frames, true, options)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
readChannelsInto (channels, options) {
|
|
40
|
+
checkChannelArrays(channels)
|
|
41
|
+
return this._readInto(Math.min(...channels.map((x) => x.length)), channels, false, options)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
readInterleavedInto (data, options) {
|
|
45
|
+
if (!(data instanceof Float32Array)) { throw new TypeError("data must be a Float32Array") }
|
|
46
|
+
return this._readInto(Math.floor(data.length / this.channels), data, true, options)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
_readFrames (frames, interleaved, options) {
|
|
50
|
+
checkInteger(frames, "frames must be a positive integer", (x) => x > 0)
|
|
51
|
+
const signal = readSignal(options)
|
|
52
|
+
return this._read(frames, null, interleaved, signal)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
_readInto (frames, out, interleaved, options) {
|
|
56
|
+
if (frames <= 0) { throw new RangeError("the block must hold at least one frame") }
|
|
57
|
+
const signal = readSignal(options)
|
|
58
|
+
return this._read(frames, out, interleaved, signal)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
_view (block, offset, interleaved) {
|
|
62
|
+
if (offset === 0) { return block }
|
|
63
|
+
return interleaved
|
|
64
|
+
? block.subarray(offset * this.channels)
|
|
65
|
+
: block.map((channel) => channel.subarray(offset))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async _read (frames, out, interleaved, signal) {
|
|
69
|
+
for (;;) {
|
|
70
|
+
signal?.throwIfAborted()
|
|
71
|
+
if (this.closed) { throw readerClosedError() }
|
|
72
|
+
if (this._feedReader._seeking) {
|
|
73
|
+
await this._feedReader._waitUntil(() => !this._feedReader._seeking, signal)
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
if (this.ended) {
|
|
77
|
+
this._throwIfFailed()
|
|
78
|
+
return null
|
|
79
|
+
}
|
|
80
|
+
const block = out ?? (interleaved
|
|
81
|
+
? new Float32Array(frames * this.channels)
|
|
82
|
+
: Array.from({ length: this.channels }, () => new Float32Array(frames)))
|
|
83
|
+
let filled = 0
|
|
84
|
+
let entry = -1
|
|
85
|
+
let timestamp = 0
|
|
86
|
+
let segment = -1
|
|
87
|
+
while (filled < frames) {
|
|
88
|
+
const wanted = Math.min(frames - filled, CHUNK_FRAMES)
|
|
89
|
+
await this._feedReader.wait(wanted, { signal })
|
|
90
|
+
if (this.closed) { throw readerClosedError() }
|
|
91
|
+
const raw = this._feedReader._readBlock(this._view(block, filled, interleaved), this.channels, entry)
|
|
92
|
+
if (filled === 0) {
|
|
93
|
+
entry = raw.entry
|
|
94
|
+
timestamp = raw.timestamp
|
|
95
|
+
segment = raw.segment
|
|
96
|
+
}
|
|
97
|
+
filled += raw.frames
|
|
98
|
+
if (raw.frames < wanted) { break }
|
|
99
|
+
}
|
|
100
|
+
if (filled > 0) {
|
|
101
|
+
let samples = block
|
|
102
|
+
if (!out && filled < frames) {
|
|
103
|
+
samples = interleaved
|
|
104
|
+
? block.subarray(0, filled * this.channels)
|
|
105
|
+
: block.map((channel) => channel.subarray(0, filled))
|
|
106
|
+
}
|
|
107
|
+
const result = interleaved
|
|
108
|
+
? { data: samples, channels: this.channels }
|
|
109
|
+
: { channels: samples }
|
|
110
|
+
result.frames = filled
|
|
111
|
+
result.timestamp = timestamp
|
|
112
|
+
result.segment = segment
|
|
113
|
+
return result
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
module.exports = {
|
|
120
|
+
AudioReader,
|
|
121
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
const { bindings, codedError, checkOptions, checkInteger } = require('./common')
|
|
2
|
+
const { Emitter } = require('./events')
|
|
3
|
+
|
|
4
|
+
const closedError = () => codedError('ERR_SOURCE_CLOSED', "the byte source is closed")
|
|
5
|
+
|
|
6
|
+
const checkOffset = (value, name) => {
|
|
7
|
+
checkInteger(value, `${name} must be a non-negative integer`, (x) => x >= 0 && Number.isSafeInteger(x))
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const checkLimit = (value, name) => {
|
|
11
|
+
checkInteger(value, `${name} must be a positive integer`, (x) => x > 0 && Number.isSafeInteger(x))
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ByteSource extends Emitter {
|
|
16
|
+
constructor (options = {}) {
|
|
17
|
+
checkOptions(options)
|
|
18
|
+
const { size, window } = options
|
|
19
|
+
if (size !== undefined) { checkOffset(size, 'size') }
|
|
20
|
+
let limits = null
|
|
21
|
+
if (window !== undefined) {
|
|
22
|
+
if (window === null || typeof window !== 'object') { throw new TypeError("window must be an object") }
|
|
23
|
+
const { ahead = 16 * 1024 * 1024, behind = 4 * 1024 * 1024 } = window
|
|
24
|
+
checkLimit(ahead, 'window.ahead')
|
|
25
|
+
checkLimit(behind, 'window.behind')
|
|
26
|
+
limits = Object.freeze({ ahead, behind })
|
|
27
|
+
}
|
|
28
|
+
super([ 'request', 'drain', 'close' ])
|
|
29
|
+
|
|
30
|
+
this._drainWaiters = []
|
|
31
|
+
const ref = new WeakRef(this)
|
|
32
|
+
this._native = new bindings.ByteSource({ size, window: limits }, () => { ref.deref()?._onNotify() })
|
|
33
|
+
this.window = limits
|
|
34
|
+
this._closed = false
|
|
35
|
+
this._closeCalled = false
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
get closed () { return this._closed }
|
|
39
|
+
|
|
40
|
+
_onNotify () {
|
|
41
|
+
if (this.closed) { return }
|
|
42
|
+
const { request, space } = this._native.takeEvents()
|
|
43
|
+
if (space || request !== null) { this._resolveDrain() }
|
|
44
|
+
if (space) { this._tryEmit('drain', { type: 'drain' }) }
|
|
45
|
+
if (request !== null) { this._tryEmit('request', { type: 'request', offset: request }) }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
_resolveDrain () {
|
|
49
|
+
const waiters = this._drainWaiters
|
|
50
|
+
this._drainWaiters = []
|
|
51
|
+
for (const { resolve } of waiters) { resolve() }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
push (offset, bytes) {
|
|
55
|
+
checkOffset(offset, 'offset')
|
|
56
|
+
let view
|
|
57
|
+
if (ArrayBuffer.isView(bytes)) { view = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) }
|
|
58
|
+
else if (bytes instanceof ArrayBuffer || bytes instanceof SharedArrayBuffer) { view = new Uint8Array(bytes) }
|
|
59
|
+
else { throw new TypeError("bytes must be an ArrayBuffer or an ArrayBufferView") }
|
|
60
|
+
if (this.closed) { throw closedError() }
|
|
61
|
+
return this._native.push(offset, view)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
drain () {
|
|
65
|
+
if (this.closed) { return Promise.reject(closedError()) }
|
|
66
|
+
return new Promise((resolve, reject) => { this._drainWaiters.push({ resolve, reject }) })
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
restart (offset) {
|
|
70
|
+
checkOffset(offset, 'offset')
|
|
71
|
+
if (this.closed) { throw closedError() }
|
|
72
|
+
this._native.restart(offset)
|
|
73
|
+
this._resolveDrain()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
end () {
|
|
77
|
+
if (this.closed) { throw closedError() }
|
|
78
|
+
this._native.end()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
fail (message) {
|
|
82
|
+
if (message !== undefined && typeof message !== 'string') { throw new TypeError("message must be a string") }
|
|
83
|
+
if (this.closed) { throw closedError() }
|
|
84
|
+
this._native.fail(message || 'error')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
setSize (size) {
|
|
88
|
+
checkOffset(size, 'size')
|
|
89
|
+
if (this.closed) { throw closedError() }
|
|
90
|
+
this._native.setSize(size)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
get size () {
|
|
94
|
+
if (this.closed) { return null }
|
|
95
|
+
const size = this._native.size()
|
|
96
|
+
return size < 0 ? null : size
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
get bufferedRanges () {
|
|
100
|
+
if (this.closed) { return [] }
|
|
101
|
+
return this._native.bufferedRanges()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
close () {
|
|
105
|
+
if (this._closeCalled) { throw closedError() }
|
|
106
|
+
this._closeCalled = true
|
|
107
|
+
this._close()
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
_close () {
|
|
111
|
+
if (this.closed) { return }
|
|
112
|
+
this._closed = true
|
|
113
|
+
this._native.close()
|
|
114
|
+
const waiters = this._drainWaiters
|
|
115
|
+
this._drainWaiters = []
|
|
116
|
+
for (const { reject } of waiters) { reject(closedError()) }
|
|
117
|
+
this._retire(closedError)
|
|
118
|
+
this._tryEmit('close', { type: 'close' })
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const createByteSource = (options) => new ByteSource(options)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
const parseSource = (source) => {
|
|
126
|
+
if (typeof source === 'string') { return { input: source, byteSource: null } }
|
|
127
|
+
if (source instanceof ByteSource) {
|
|
128
|
+
if (source.closed) { throw closedError() }
|
|
129
|
+
return { input: source._native, byteSource: source }
|
|
130
|
+
}
|
|
131
|
+
if (source instanceof ArrayBuffer || source instanceof SharedArrayBuffer) {
|
|
132
|
+
return { input: new Uint8Array(source), byteSource: null }
|
|
133
|
+
}
|
|
134
|
+
if (ArrayBuffer.isView(source)) {
|
|
135
|
+
return { input: new Uint8Array(source.buffer, source.byteOffset, source.byteLength), byteSource: null }
|
|
136
|
+
}
|
|
137
|
+
throw new TypeError("source must be a path, a buffer or a byte source")
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = {
|
|
141
|
+
ByteSource,
|
|
142
|
+
createByteSource,
|
|
143
|
+
parseSource,
|
|
144
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const bindings = require('../../dist/media_decoders.node')
|
|
2
|
+
|
|
3
|
+
const pinned = new Set()
|
|
4
|
+
|
|
5
|
+
const codedError = (code, message, properties) => Object.assign(new Error(message), { code, ...properties })
|
|
6
|
+
|
|
7
|
+
const ffmpegError = (code, { message, code: errno }, properties) => codedError(code, message, { errno: errno || null, ...properties })
|
|
8
|
+
|
|
9
|
+
const checkOptions = (options) => {
|
|
10
|
+
if (options === null || typeof options !== 'object') { throw new TypeError("options must be an object") }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const checkSignal = (signal) => {
|
|
14
|
+
if (signal !== undefined && !(signal instanceof AbortSignal)) {
|
|
15
|
+
throw new TypeError("signal must be an AbortSignal")
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const checkNumber = (value, message, valid) => {
|
|
20
|
+
if (typeof value !== 'number') { throw new TypeError(message) }
|
|
21
|
+
if (!valid(value)) { throw new RangeError(message) }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const checkInteger = (value, message, valid) => {
|
|
25
|
+
if (!Number.isInteger(value)) { throw new TypeError(message) }
|
|
26
|
+
if (!valid(value)) { throw new RangeError(message) }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const checkOneOf = (value, values, message) => {
|
|
30
|
+
if (typeof value !== 'string') { throw new TypeError(message) }
|
|
31
|
+
if (!values.includes(value)) { throw new RangeError(message) }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
module.exports = {
|
|
35
|
+
bindings,
|
|
36
|
+
pinned,
|
|
37
|
+
codedError,
|
|
38
|
+
ffmpegError,
|
|
39
|
+
checkOptions,
|
|
40
|
+
checkSignal,
|
|
41
|
+
checkNumber,
|
|
42
|
+
checkInteger,
|
|
43
|
+
checkOneOf,
|
|
44
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
const { bindings, codedError, checkOptions, checkSignal, checkNumber, checkInteger } = require('./common')
|
|
2
|
+
const { parseSource } = require('./byte-source')
|
|
3
|
+
const { openParsed } = require('./media-file')
|
|
4
|
+
const { checkVideoOptions } = require('./video-reader')
|
|
5
|
+
const { checkSampleRate, readChannelOptions } = require('./feed')
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
const ownInput = (parsed) => {
|
|
9
|
+
if (parsed.input instanceof Uint8Array) { parsed.input = bindings.copyBytes(parsed.input) }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const checkRange = (start, end) => {
|
|
13
|
+
checkNumber(start, "start must be a non-negative number", (x) => Number.isFinite(x) && x >= 0)
|
|
14
|
+
if (end !== undefined) { checkNumber(end, "end must be a number greater than start", (x) => Number.isFinite(x) && x > start) }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const checkSelectTrack = (selectTrack) => {
|
|
18
|
+
if (selectTrack !== undefined && typeof selectTrack !== 'function') { throw new TypeError("selectTrack must be a function") }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// The file's thread decodes up to this many frames ahead (about 22 seconds at 48 kHz) while the JS thread copies them into the result.
|
|
22
|
+
// If the JS thread stays blocked once that much is waiting, the decode stalls until it is free again.
|
|
23
|
+
const DECODE_BUFFER_FRAMES = 1 << 20
|
|
24
|
+
const DECODE_CHUNK_FRAMES = 65536
|
|
25
|
+
|
|
26
|
+
class DecodedAudioBuilder {
|
|
27
|
+
constructor (channels, interleaved, capacity) {
|
|
28
|
+
this._channels = channels
|
|
29
|
+
this._interleaved = interleaved
|
|
30
|
+
this._width = interleaved ? channels : 1
|
|
31
|
+
this._buffers = Array.from({ length: interleaved ? 1 : channels }, () => new ArrayBuffer(capacity * this._width * 4))
|
|
32
|
+
this.capacity = capacity
|
|
33
|
+
this.frames = 0
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
reserve (count) {
|
|
37
|
+
if (this.frames + count <= this.capacity) { return }
|
|
38
|
+
this.capacity = Math.max(this.frames + count, this.capacity * 2)
|
|
39
|
+
this._buffers = this._buffers.map((buffer) => buffer.transfer(this.capacity * this._width * 4))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
views (count) {
|
|
43
|
+
const length = Math.min(count, this.capacity - this.frames)
|
|
44
|
+
return this._buffers.map((buffer) => new Float32Array(buffer, this.frames * this._width * 4, length * this._width))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
result () {
|
|
48
|
+
const buffers = this._buffers.map((buffer) => this.frames === this.capacity ? buffer : buffer.transfer(this.frames * this._width * 4))
|
|
49
|
+
const arrays = buffers.map((buffer) => new Float32Array(buffer))
|
|
50
|
+
return this._interleaved
|
|
51
|
+
? { data: arrays[0], channels: this._channels }
|
|
52
|
+
: { channels: arrays }
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const readAudio = async (file, options, interleaved) => {
|
|
57
|
+
const { selectTrack, sampleRate, maxFrames, start, end } = options
|
|
58
|
+
const track = pickTrack(file, 'audio', selectTrack)
|
|
59
|
+
const rate = sampleRate ?? track.sampleRate
|
|
60
|
+
const first = Math.round(start * rate)
|
|
61
|
+
const last = end === undefined ? Infinity : Math.max(first, Math.round(end * rate))
|
|
62
|
+
const tooLong = (frames) => maxFrames !== undefined && Math.min(frames, end === undefined ? Infinity : end * rate) - start * rate > maxFrames
|
|
63
|
+
|
|
64
|
+
const duration = track.duration ?? (file.duration > 0 ? file.duration : 0)
|
|
65
|
+
if (tooLong(duration * rate)) { throw codedError('ERR_TOO_LONG', "the decoded audio is too long") }
|
|
66
|
+
|
|
67
|
+
const expected = duration > 0 ? Math.max(0, Math.ceil(Math.min(duration * rate, last) - first)) : 0
|
|
68
|
+
const reader = track._createReader({ sampleRate: rate, channels: options.channels, maxChannels: options.maxChannels }, Math.min(DECODE_BUFFER_FRAMES, Math.max(DECODE_CHUNK_FRAMES, expected)))
|
|
69
|
+
const { channels } = reader
|
|
70
|
+
const output = new DecodedAudioBuilder(channels, interleaved, expected || DECODE_CHUNK_FRAMES)
|
|
71
|
+
let segment = 0
|
|
72
|
+
// _seekPreroll is null in containers whose timestamps are coarser than one sample, such as Matroska and WebM (whole milliseconds).
|
|
73
|
+
// A seek there can't land on an exact sample, so all of the audio before start is decoded instead.
|
|
74
|
+
if (track._seekPreroll !== null) {
|
|
75
|
+
const time = Math.floor(start - track._seekPreroll)
|
|
76
|
+
if (time > 0 && time < duration) { segment = file.seek(time) }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const read = (into) => {
|
|
80
|
+
if (!into) {
|
|
81
|
+
return interleaved
|
|
82
|
+
? reader.readInterleaved(DECODE_CHUNK_FRAMES)
|
|
83
|
+
: reader.readChannels(DECODE_CHUNK_FRAMES)
|
|
84
|
+
}
|
|
85
|
+
return interleaved
|
|
86
|
+
? reader.readInterleavedInto(into[0])
|
|
87
|
+
: reader.readChannelsInto(into)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let position = null
|
|
91
|
+
while (position === null || position < last) {
|
|
92
|
+
const direct = position !== null && position >= first && output.frames < output.capacity
|
|
93
|
+
let block
|
|
94
|
+
try {
|
|
95
|
+
block = await read(direct ? output.views(Math.min(DECODE_CHUNK_FRAMES, last - position)) : null)
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (position === null) { throw error }
|
|
99
|
+
break
|
|
100
|
+
}
|
|
101
|
+
if (!block) {
|
|
102
|
+
if (position !== null || segment === 0) { break }
|
|
103
|
+
segment = file.seek(0)
|
|
104
|
+
continue
|
|
105
|
+
}
|
|
106
|
+
if (direct) {
|
|
107
|
+
output.frames += block.frames
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
if (block.segment < segment) { continue }
|
|
111
|
+
position ??= Math.round(block.timestamp * rate)
|
|
112
|
+
const from = Math.max(0, first - position)
|
|
113
|
+
const to = Math.min(block.frames, last - position)
|
|
114
|
+
if (to > from) {
|
|
115
|
+
output.reserve(to - from)
|
|
116
|
+
const views = output.views(to - from)
|
|
117
|
+
if (interleaved) { views[0].set(block.data.subarray(from * channels, to * channels)) }
|
|
118
|
+
else { views.forEach((view, i) => { view.set(block.channels[i].subarray(from, to)) }) }
|
|
119
|
+
output.frames += to - from
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
position += block.frames
|
|
123
|
+
if (tooLong(position)) { throw codedError('ERR_TOO_LONG', "the decoded audio is too long") }
|
|
124
|
+
}
|
|
125
|
+
if (position === null) { throw codedError('ERR_NO_DATA', "no audio data") }
|
|
126
|
+
return { sampleRate: rate, ...output.result() }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const runDecodeAudio = (source, options, interleaved) => {
|
|
130
|
+
checkOptions(options)
|
|
131
|
+
const { selectTrack, sampleRate, channels, maxChannels, maxFrames, start = 0, end, signal } = options
|
|
132
|
+
checkSelectTrack(selectTrack)
|
|
133
|
+
if (sampleRate !== undefined) { checkSampleRate(sampleRate) }
|
|
134
|
+
readChannelOptions(channels, maxChannels)
|
|
135
|
+
if (maxFrames !== undefined) { checkInteger(maxFrames, "maxFrames must be a positive integer", (x) => x > 0 && Number.isSafeInteger(x)) }
|
|
136
|
+
checkRange(start, end)
|
|
137
|
+
checkSignal(signal)
|
|
138
|
+
const parsed = parseSource(source)
|
|
139
|
+
const { byteSource } = parsed
|
|
140
|
+
if (signal?.aborted) {
|
|
141
|
+
byteSource?._close()
|
|
142
|
+
return Promise.reject(signal.reason)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const opening = openParsed(parsed)
|
|
146
|
+
|
|
147
|
+
let file = null
|
|
148
|
+
let aborted = false
|
|
149
|
+
let onAbort = null
|
|
150
|
+
const cancelled = new Promise((resolve) => {
|
|
151
|
+
onAbort = () => {
|
|
152
|
+
aborted = true
|
|
153
|
+
byteSource?._close()
|
|
154
|
+
file?._close()
|
|
155
|
+
resolve(signal.reason)
|
|
156
|
+
}
|
|
157
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
const run = async () => {
|
|
161
|
+
try {
|
|
162
|
+
file = await opening
|
|
163
|
+
if (aborted) { file._close() }
|
|
164
|
+
return await readAudio(file, { selectTrack, sampleRate, channels, maxChannels, maxFrames, start, end }, interleaved)
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
file?._close()
|
|
168
|
+
byteSource?._close()
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const result = run()
|
|
173
|
+
if (!signal) { return result }
|
|
174
|
+
return Promise.race([ result, cancelled.then((reason) => { throw reason }) ])
|
|
175
|
+
.finally(() => { signal.removeEventListener('abort', onAbort) })
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const decodeAudio = (source, options = {}) => runDecodeAudio(source, options, false)
|
|
179
|
+
|
|
180
|
+
const decodeAudioInterleaved = (source, options = {}) => runDecodeAudio(source, options, true)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
const pickTrack = (file, type, selectTrack) => {
|
|
184
|
+
if (selectTrack === undefined) {
|
|
185
|
+
const best = file.tracks[file._bestTracks[type]]
|
|
186
|
+
if (best) { return best }
|
|
187
|
+
const tracks = file.tracks.filter((track) => track.type === type)
|
|
188
|
+
if (tracks.length === 0) { throw codedError('ERR_NO_TRACK', `no ${type} track`) }
|
|
189
|
+
throw codedError('ERR_NO_DECODER', `no decoder for ${tracks[0].codec}`)
|
|
190
|
+
}
|
|
191
|
+
const tracks = file.tracks.filter((track) => track.type === type)
|
|
192
|
+
if (tracks.length === 0) { throw codedError('ERR_NO_TRACK', `no ${type} track`) }
|
|
193
|
+
const track = selectTrack(tracks)
|
|
194
|
+
if (track === undefined || track === null) { throw codedError('ERR_NO_TRACK', `no ${type} track was chosen`) }
|
|
195
|
+
if (!tracks.includes(track)) { throw new TypeError(`selectTrack must return one of the given ${type} tracks`) }
|
|
196
|
+
if (!track.decodable) { throw codedError('ERR_NO_DECODER', `no decoder for ${track.codec}`) }
|
|
197
|
+
return track
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const readVideo = async function * (parsed, selectTrack, start, end, options, signal) {
|
|
201
|
+
const file = await openParsed(parsed, { signal })
|
|
202
|
+
const onAbort = () => { file._close() }
|
|
203
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
204
|
+
try {
|
|
205
|
+
signal?.throwIfAborted()
|
|
206
|
+
const reader = pickTrack(file, 'video', selectTrack).createReader(options)
|
|
207
|
+
const segment = start > 0 ? file.seek(start) : 0
|
|
208
|
+
for (;;) {
|
|
209
|
+
const frame = await reader.read()
|
|
210
|
+
if (!frame) {
|
|
211
|
+
signal?.throwIfAborted()
|
|
212
|
+
return
|
|
213
|
+
}
|
|
214
|
+
if (frame.segment < segment) {
|
|
215
|
+
reader.release(frame)
|
|
216
|
+
continue
|
|
217
|
+
}
|
|
218
|
+
if (end !== undefined && frame.timestamp >= end) { return }
|
|
219
|
+
yield frame
|
|
220
|
+
reader.release(frame)
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
signal?.throwIfAborted()
|
|
225
|
+
throw error
|
|
226
|
+
}
|
|
227
|
+
finally {
|
|
228
|
+
signal?.removeEventListener('abort', onAbort)
|
|
229
|
+
file._close()
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const decodeVideo = (source, options = {}) => {
|
|
234
|
+
checkOptions(options)
|
|
235
|
+
const { selectTrack, start = 0, end, signal, ...readerOptions } = options
|
|
236
|
+
checkSelectTrack(selectTrack)
|
|
237
|
+
checkSignal(signal)
|
|
238
|
+
checkRange(start, end)
|
|
239
|
+
checkVideoOptions(readerOptions)
|
|
240
|
+
const parsed = parseSource(source)
|
|
241
|
+
ownInput(parsed)
|
|
242
|
+
return readVideo(parsed, selectTrack, start, end, readerOptions, signal)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const decodeFrame = (source, time, options = {}) => {
|
|
246
|
+
checkNumber(time, "time must be a non-negative number", (x) => Number.isFinite(x) && x >= 0)
|
|
247
|
+
checkOptions(options)
|
|
248
|
+
const { selectTrack, signal, frames, ...rest } = options
|
|
249
|
+
const readerOptions = { ...rest, frames: 2 }
|
|
250
|
+
checkSelectTrack(selectTrack)
|
|
251
|
+
checkSignal(signal)
|
|
252
|
+
checkVideoOptions(readerOptions)
|
|
253
|
+
return firstFrame(parseSource(source), selectTrack, time, readerOptions, signal)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const firstFrame = async (parsed, selectTrack, time, readerOptions, signal) => {
|
|
257
|
+
const iterator = readVideo(parsed, selectTrack, time, undefined, readerOptions, signal)
|
|
258
|
+
try {
|
|
259
|
+
const { value } = await iterator.next()
|
|
260
|
+
return value ?? null
|
|
261
|
+
}
|
|
262
|
+
finally {
|
|
263
|
+
await iterator.return()
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
module.exports = {
|
|
268
|
+
decodeAudio,
|
|
269
|
+
decodeAudioInterleaved,
|
|
270
|
+
decodeVideo,
|
|
271
|
+
decodeFrame,
|
|
272
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
const { EventEmitter } = require('node:events')
|
|
2
|
+
|
|
3
|
+
const commonEvents = [ 'newListener', 'removeListener', 'error', '*' ]
|
|
4
|
+
const metaEvents = [ 'newListener', 'removeListener' ]
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Emitter extends EventEmitter {
|
|
8
|
+
constructor (validEvents) {
|
|
9
|
+
super()
|
|
10
|
+
this._validEvents = validEvents
|
|
11
|
+
this._internalListeners = new Set()
|
|
12
|
+
this._makeRetiredError = null
|
|
13
|
+
|
|
14
|
+
const onNewListener = (type) => {
|
|
15
|
+
if (this._makeRetiredError) { throw this._makeRetiredError() }
|
|
16
|
+
if (!commonEvents.includes(type) && !validEvents.includes(type)) {
|
|
17
|
+
throw Object.assign(new TypeError("invalid event"), { type })
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
this._internalListeners.add(onNewListener)
|
|
21
|
+
this.on('newListener', onNewListener)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
_retire (makeError) {
|
|
25
|
+
this._makeRetiredError = makeError
|
|
26
|
+
process.nextTick(() => { this.removeAllListeners() })
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
_tryEmit (type, event) {
|
|
30
|
+
try { this.emit(type, event) }
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (type === 'error') {
|
|
33
|
+
rethrow(error)
|
|
34
|
+
return
|
|
35
|
+
}
|
|
36
|
+
try { this.emit('error', error) }
|
|
37
|
+
catch (error2) { rethrow(error2) }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
removeAllListeners (type) {
|
|
42
|
+
if (type === undefined) {
|
|
43
|
+
const types = this.eventNames().filter((name) => name !== 'removeListener')
|
|
44
|
+
for (const eventType of [ ...types, 'removeListener' ]) {
|
|
45
|
+
this.removeAllListeners(eventType)
|
|
46
|
+
}
|
|
47
|
+
return this
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (!metaEvents.includes(type)) {
|
|
51
|
+
super.removeAllListeners(type)
|
|
52
|
+
return this
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
for (const listener of this.listeners(type)) {
|
|
56
|
+
if (this._internalListeners.has(listener)) { continue }
|
|
57
|
+
this.removeListener(type, listener)
|
|
58
|
+
}
|
|
59
|
+
return this
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
emit (type, ...args) {
|
|
63
|
+
const isCommon = commonEvents.includes(type)
|
|
64
|
+
if (!isCommon && !this._validEvents.includes(type)) {
|
|
65
|
+
throw Object.assign(new TypeError("invalid event"), { type })
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
let hadListeners = super.emit(type, ...args)
|
|
69
|
+
if (!isCommon) {
|
|
70
|
+
hadListeners = super.emit('*', type, ...args) || hadListeners
|
|
71
|
+
}
|
|
72
|
+
return hadListeners
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const rethrow = (error) => {
|
|
77
|
+
process.nextTick(() => { throw error })
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = { Emitter }
|