@qvac/decoder-audio 0.2.4 → 0.2.6

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.
@@ -1,98 +0,0 @@
1
- 'use strict'
2
-
3
- const QvacLogger = require('@qvac/logging')
4
-
5
- class ChannelPortStream {
6
- constructor (channelPort, logger) {
7
- this.channelPort = channelPort
8
- this.logger = new QvacLogger(logger)
9
-
10
- this.channelEnd = false
11
- this.channelClose = false
12
-
13
- this.channelPort.on('end', () => {
14
- this.logger.debug('ChannelPortStream Channel port ended')
15
- this.channelEnd = true
16
- })
17
- this.channelPort.on('close', () => {
18
- this.logger.debug('ChannelPortStream Channel port closed')
19
- this.channelClose = true
20
- })
21
-
22
- this.bufferArray = []
23
- this.bufferOneOffset = 0
24
- }
25
-
26
- portHasData () {
27
- const hasData = (this.channelEnd || this.channelClose) && this.channelPort._queue.length
28
- return hasData !== 0
29
- }
30
-
31
- _readFromChannelPort () {
32
- let portHasDataCount = 0
33
- while (this.portHasData()) {
34
- portHasDataCount++
35
- const chunk = this.channelPort.readSync()
36
- if (!chunk || chunk.length === 0) {
37
- this.logger.debug('Read chunk of length 0 from channelPort')
38
- break
39
- }
40
- this.logger.debug(`Read chunk of length ${chunk.length} from channelPort`)
41
- this.bufferArray.push(chunk)
42
- }
43
- this.logger.debug(`portHasData() loop ran ${portHasDataCount} times, bufferArray.length=${this.bufferArray.length}`)
44
- }
45
-
46
- _readFromBufferArray (buffer, len) {
47
- let finalLen = 0
48
- let bytesCopied = 0
49
- if (this.bufferArray.length > 0) {
50
- while (finalLen < len) {
51
- // Get pending bytes in first buffer
52
- const firstBufferPending = this.bufferArray[0].length - this.bufferOneOffset
53
-
54
- // Get bytes to copy in case pending len is less than firstBufferPending
55
- const toCopy = Math.min(len - finalLen, firstBufferPending)
56
- this.logger.debug(`Copying ${toCopy} bytes from bufferArray[0] (pending: ${firstBufferPending}), bufferOneOffset=${this.bufferOneOffset}, finalLen=${finalLen}`)
57
-
58
- // Copy bytes to buffer
59
- bytesCopied += this.bufferArray[0].copy(buffer, finalLen, this.bufferOneOffset, this.bufferOneOffset + toCopy)
60
- this.bufferOneOffset += toCopy
61
-
62
- // Shift out buffer if it's empty
63
- if (this.bufferOneOffset >= this.bufferArray[0].length) {
64
- this.logger.debug('Finished bufferArray[0], shifting it out')
65
- this.bufferArray.shift()
66
- this.bufferOneOffset = 0
67
- }
68
-
69
- // Update finalLen
70
- finalLen += toCopy
71
-
72
- // Break inner loop if bufferArray has no more buffers
73
- if (this.bufferArray.length === 0) {
74
- this.logger.debug('bufferArray is empty, breaking inner loop')
75
- break
76
- }
77
- }
78
- } else {
79
- this.logger.debug('bufferArray is empty, nothing to copy')
80
- }
81
-
82
- this.logger.debug(`_readFromBufferArray bytesCopied=${bytesCopied}`)
83
- return finalLen
84
- }
85
-
86
- read (buffer, len) {
87
- this.logger.debug(`Called with len=${len}`)
88
-
89
- this._readFromChannelPort()
90
-
91
- const finalLen = this._readFromBufferArray(buffer, len)
92
-
93
- this.logger.debug(`Returning finalLen=${finalLen}`)
94
- return finalLen
95
- }
96
- }
97
-
98
- module.exports = ChannelPortStream
@@ -1,23 +0,0 @@
1
- 'use strict'
2
-
3
- const FFmpegDecoderMessages = {
4
- // Decoder messages
5
- INIT: 'init', // Initialization message
6
- STREAM_START: 'stream-start', // Start streaming message
7
- CLEANUP: 'cleanup' // Cleanup message
8
- }
9
-
10
- const FFmpegWorkerMessages = {
11
- // Worker messages
12
- READY: 'ready', // Ready message
13
- INIT_RESULT: 'init-result', // Initialization result message
14
- RESULT_CHUNK: 'result-chunk', // Result chunk message
15
- RESULT_END: 'result-end', // End streaming message
16
- CLEANUP_DONE: 'cleanup-done', // Cleanup done message
17
- ERROR: 'error' // Error message
18
- }
19
-
20
- module.exports = {
21
- FFmpegDecoderMessages,
22
- FFmpegWorkerMessages
23
- }
@@ -1,293 +0,0 @@
1
- 'use strict'
2
-
3
- const { parentPort } = require('bare-worker')
4
- const ffmpeg = require('bare-ffmpeg')
5
- const QvacLogger = require('@qvac/logging')
6
- const Channel = require('bare-channel')
7
- const ChannelPortStream = require('./channel-port-stream')
8
- const { FFmpegDecoderMessages, FFmpegWorkerMessages } = require('./constants')
9
-
10
- class FFmpegWorker {
11
- SUPPORTED_AUDIO_FORMATS = {
12
- s16le: {
13
- format: ffmpeg.constants.sampleFormats.S16,
14
- byteLength: 2
15
- },
16
- f32le: {
17
- format: ffmpeg.constants.sampleFormats.FLT,
18
- byteLength: 4
19
- }
20
- }
21
-
22
- // Whisper addon expectations
23
- OUTPUT_FORMAT_BYTE_LENGTH = 2 // S16LE uses 16 bits = 2 bytes
24
- OUTPUT_FORMAT = ffmpeg.constants.sampleFormats.S16
25
- OUTPUT_SAMPLE_RATE = 16000
26
- OUTPUT_CHANNEL_LAYOUT = ffmpeg.constants.channelLayouts.MONO
27
-
28
- constructor (parentPort, logger = new QvacLogger(console)) {
29
- this.parentPort = parentPort
30
- this.logger = logger
31
-
32
- this.channel = null
33
- this.channelPort = null
34
- this.channelPortStream = null
35
-
36
- this.config = null
37
- this.totalReadLen = 0
38
-
39
- // Encoder delay handling
40
- this.samplesSkipped = 0
41
- this.totalSkipSamples = 0
42
- }
43
-
44
- sendMessage (type, data) {
45
- this.parentPort.postMessage({ type, data })
46
- }
47
-
48
- sendResultChunk (data) {
49
- this.sendMessage(FFmpegWorkerMessages.RESULT_CHUNK, data)
50
- }
51
-
52
- sendEndMessage () {
53
- this.logger.debug('[ffmpeg-worker] Sending end message')
54
- this.sendMessage(FFmpegWorkerMessages.RESULT_END)
55
- }
56
-
57
- initializeDecoder (data) {
58
- const { channelHandle, config } = data
59
- this.config = config
60
-
61
- if (!this.SUPPORTED_AUDIO_FORMATS[config.audioFormat]) {
62
- this.logger.error('[ffmpeg-worker] Unsupported audio format:', config.audioFormat)
63
- return { success: false, error: 'Unsupported audio format' }
64
- }
65
-
66
- this.OUTPUT_FORMAT = this.SUPPORTED_AUDIO_FORMATS[config.audioFormat].format
67
- this.OUTPUT_FORMAT_BYTE_LENGTH = this.SUPPORTED_AUDIO_FORMATS[config.audioFormat].byteLength
68
-
69
- this.logger.info('[ffmpeg-worker] Initializing decoder...')
70
- try {
71
- this.channel = Channel.from(channelHandle)
72
- this.channelPort = this.channel.connect()
73
- this.channelPortStream = new ChannelPortStream(this.channelPort, this.logger)
74
- return { success: true }
75
- } catch (err) {
76
- this.logger.error('[ffmpeg-worker] Failed to initialize decoder:', err)
77
- return { success: false, error: err.message }
78
- }
79
- }
80
-
81
- startStream () {
82
- this.decodeStream()
83
- }
84
-
85
- _processFrame (decoder, raw, resampler) {
86
- while (decoder.receiveFrame(raw)) {
87
- const output = new ffmpeg.Frame()
88
- output.channelLayout = this.OUTPUT_CHANNEL_LAYOUT
89
- output.format = this.OUTPUT_FORMAT
90
- output.sampleRate = this.OUTPUT_SAMPLE_RATE
91
- output.nbSamples = raw.nbSamples
92
-
93
- const samples = new ffmpeg.Samples(
94
- output.format,
95
- output.channelLayout.nbChannels,
96
- output.nbSamples
97
- )
98
- samples.fill(output)
99
-
100
- // samples.data.length is always fixed, like 8192 bytes. So we need to
101
- // extract only the data we need through `subarray`. `resampler.convert`
102
- // gives the number of samples converted per channel. So
103
- // `bytesPerSample` * `samplesPerChannel` * `channelsPerSample` gives
104
- // total amount of bytes.
105
- const count = resampler.convert(raw, output)
106
-
107
- // Handle encoder delay by skipping initial samples
108
- if (this.samplesSkipped < this.totalSkipSamples) {
109
- const samplesToSkip = Math.min(count, this.totalSkipSamples - this.samplesSkipped)
110
- this.samplesSkipped += samplesToSkip
111
- if (samplesToSkip >= count) continue // Skip entire frame
112
-
113
- // Skip partial frame
114
- const skipBytes = this.OUTPUT_FORMAT_BYTE_LENGTH * samplesToSkip * output.channelLayout.nbChannels
115
- const length = this.OUTPUT_FORMAT_BYTE_LENGTH * (count - samplesToSkip) * output.channelLayout.nbChannels
116
- this.sendResultChunk(Buffer.from(samples.data.subarray(skipBytes, skipBytes + length)))
117
- } else {
118
- const length = this.OUTPUT_FORMAT_BYTE_LENGTH * count * output.channelLayout.nbChannels
119
- this.sendResultChunk(Buffer.from(samples.data.subarray(0, length)))
120
- }
121
- }
122
- }
123
-
124
- _processPacket (format, packet, raw, decoder, resampler) {
125
- while (format.readFrame(packet)) {
126
- decoder.sendPacket(packet)
127
- this._processFrame(decoder, raw, resampler)
128
- packet.unref()
129
- }
130
- }
131
-
132
- _processStream (format, stream) {
133
- console.log(stream.codec, stream.codecParameters)
134
- const packet = new ffmpeg.Packet()
135
- const raw = new ffmpeg.Frame()
136
-
137
- const resampler = new ffmpeg.Resampler(
138
- stream.codecParameters.sampleRate,
139
- stream.codecParameters.channelLayout,
140
- stream.codecParameters.format,
141
- this.OUTPUT_SAMPLE_RATE,
142
- this.OUTPUT_CHANNEL_LAYOUT,
143
- this.OUTPUT_FORMAT
144
- )
145
-
146
- const decoder = stream.decoder()
147
- decoder.open()
148
-
149
- // Auto-detect encoder delay: lossy codecs need ~400ms skipped to remove artifacts
150
- // Lossless codecs (WAV, FLAC) need no skipping
151
- const codecName = stream.codec.name.toLowerCase()
152
- const SKIP_MS = {
153
- mp3: 400,
154
- vorbis: 400,
155
- opus: 150,
156
- aac: 300
157
- }
158
-
159
- const skipMs = SKIP_MS[codecName] || 0
160
- this.samplesSkipped = 0
161
- this.totalSkipSamples = Math.floor((this.OUTPUT_SAMPLE_RATE * skipMs) / 1000)
162
-
163
- if (this.totalSkipSamples > 0) {
164
- console.log(`[ffmpeg-worker] Skipping ${skipMs}ms (${this.totalSkipSamples} samples) for ${codecName} to remove encoder artifacts`)
165
- this.logger.info(`[ffmpeg-worker] Skipping ${skipMs}ms for ${codecName} to remove encoder artifacts`)
166
- }
167
-
168
- this._processPacket(format, packet, raw, decoder, resampler)
169
-
170
- const output = new ffmpeg.Frame()
171
- output.channelLayout = this.OUTPUT_CHANNEL_LAYOUT
172
- output.format = this.OUTPUT_FORMAT
173
- output.sampleRate = this.OUTPUT_SAMPLE_RATE
174
- output.nbSamples = 1024
175
-
176
- const samples = new ffmpeg.Samples(
177
- output.format,
178
- output.channelLayout.nbChannels,
179
- output.nbSamples
180
- )
181
- samples.fill(output)
182
-
183
- while (resampler.flush(output) > 0) {
184
- this.sendResultChunk(Buffer.from(samples.data))
185
- }
186
-
187
- decoder.destroy()
188
- this.sendEndMessage()
189
- }
190
-
191
- _getBufferSize (inputBitrate) {
192
- const maxBufferSize = 1024 * 1024 // 1MB max
193
- return Math.min((inputBitrate / 8) * 4, maxBufferSize)
194
- }
195
-
196
- decodeStream () {
197
- const {
198
- streamIndex = 0,
199
- inputBitrate
200
- } = this.config
201
-
202
- this.logger.debug('[ffmpeg-worker] Starting deocde with config', this.config)
203
-
204
- if (!this.channelPortStream) {
205
- this.logger.error('[ffmpeg-worker] Channel port stream not initialized')
206
- return this.sendMessage(FFmpegWorkerMessages.ERROR, { error: 'Channel port stream not initialized' })
207
- }
208
-
209
- try {
210
- const bufferSize = this._getBufferSize(inputBitrate)
211
-
212
- const io = new ffmpeg.IOContext(bufferSize, {
213
- onread: (buffer, requestedLen) => {
214
- return this.channelPortStream.read(buffer, requestedLen)
215
- }
216
- })
217
-
218
- this.logger.debug('[ffmpeg-worker] IOContext created')
219
- const format = new ffmpeg.InputFormatContext(io)
220
- this.logger.debug('[ffmpeg-worker] InputFormatContext created')
221
-
222
- if (format.streams[streamIndex] === undefined) {
223
- this.logger.error('[ffmpeg-worker] Stream index out of bounds')
224
- return this.sendMessage(FFmpegWorkerMessages.ERROR, { error: 'Stream index out of bounds' })
225
- }
226
-
227
- this._processStream(format, format.streams[streamIndex])
228
- } catch (err) {
229
- this.logger.error('[ffmpeg-worker] Error during decodeChunk:', err)
230
- return this.sendMessage(FFmpegWorkerMessages.ERROR, { error: err.message })
231
- }
232
- }
233
-
234
- cleanup () {
235
- this.logger.info('[ffmpeg-worker] Cleaning up decoder resources...')
236
- this.logger.info('[ffmpeg-worker] Cleanup complete')
237
- if (this.channelPort) {
238
- this.channelPort.close()
239
- this.logger.debug('[ffmpeg-worker] Channel port disposed')
240
- }
241
- if (this.channel) {
242
- this.channel = null
243
- this.logger.debug('[ffmpeg-worker] Channel disposed')
244
- }
245
- }
246
- }
247
-
248
- const logger = new QvacLogger()
249
- const ffmpegWorkerInstance = new FFmpegWorker(parentPort, logger)
250
-
251
- // Handle messages from main thread
252
- parentPort.on('message', ({ type, data }) => {
253
- logger.debug(`[ffmpeg-worker] Received message: ${type}`)
254
- switch (type) {
255
- case FFmpegDecoderMessages.INIT: {
256
- logger.info('[ffmpeg-worker] Handling init message with channel handle:', data)
257
- const initResult = ffmpegWorkerInstance.initializeDecoder(data)
258
- parentPort.postMessage({ type: FFmpegWorkerMessages.INIT_RESULT, ...initResult })
259
- break
260
- }
261
-
262
- case FFmpegDecoderMessages.STREAM_START: {
263
- logger.info('[ffmpeg-worker] Handling decode message')
264
- ffmpegWorkerInstance.startStream()
265
- break
266
- }
267
-
268
- case FFmpegDecoderMessages.CLEANUP: {
269
- logger.info('[ffmpeg-worker] Handling cleanup message')
270
- ffmpegWorkerInstance.cleanup()
271
- parentPort.postMessage({ type: FFmpegWorkerMessages.CLEANUP_DONE, success: true })
272
- break
273
- }
274
-
275
- default: {
276
- logger.warn(`[ffmpeg-worker] Unknown message type: ${type}`)
277
- parentPort.postMessage({ type: FFmpegWorkerMessages.ERROR, error: 'Unknown message type' })
278
- }
279
- }
280
- })
281
-
282
- parentPort.on('close', () => {
283
- logger.info('[ffmpeg-worker] Worker exiting')
284
- })
285
-
286
- parentPort.on('error', (err) => {
287
- logger.error('[ffmpeg-worker] Worker error:', err)
288
- parentPort.postMessage({ type: FFmpegWorkerMessages.ERROR, error: err })
289
- })
290
-
291
- // Notify main thread that worker is ready
292
- logger.info('[ffmpeg-worker] Worker ready')
293
- parentPort.postMessage({ type: 'ready' })