carta1 1.5.0 → 1.6.1
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/README.md +5 -4
- package/bin/cli.js +447 -341
- package/codec/allocation/solve.js +19 -16
- package/codec/analysis/blocks.js +4 -1
- package/codec/analysis/spectrum.js +5 -5
- package/codec/boundary/container.js +1 -1
- package/codec/boundary/pcm.js +2 -2
- package/codec/boundary/processor.js +4 -4
- package/codec/boundary/reader.js +2 -2
- package/codec/boundary/stream.js +2 -2
- package/codec/core/geometry.js +2 -2
- package/codec/quantization/spectrum.js +4 -4
- package/codec/signal/fft.js +1 -0
- package/codec/signal/mdct.js +48 -38
- package/codec/signal/qmf.js +93 -88
- package/codec/syntax/bitstream.js +9 -9
- package/codec/syntax/frame.js +11 -2
- package/codec/synthesis/bands.js +5 -5
- package/dist/carta1-worker.min.js +1 -1
- package/dist/carta1-worker.min.js.map +1 -1
- package/dist/carta1.min.js +1 -1
- package/dist/carta1.min.js.map +1 -1
- package/dist/carta1.wme +0 -0
- package/dist/wme/index.js.map +1 -1
- package/package.json +4 -9
- package/bin/build-wme.js +0 -69
package/bin/cli.js
CHANGED
|
@@ -12,26 +12,23 @@
|
|
|
12
12
|
* carta1 --decode input.aea output.wav
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import { program } from 'commander'
|
|
16
15
|
import fs from 'fs'
|
|
17
16
|
import path from 'path'
|
|
18
|
-
import { performance } from 'perf_hooks'
|
|
19
|
-
import cliProgress from 'cli-progress'
|
|
20
|
-
import wav from 'wav'
|
|
21
17
|
|
|
22
18
|
import { AudioProcessor } from '../codec/boundary/processor.js'
|
|
23
19
|
import { AeaReader } from '../codec/boundary/reader.js'
|
|
24
20
|
import { AeaFile, validateAeaTitle } from '../codec/boundary/container.js'
|
|
25
|
-
import {
|
|
21
|
+
import { createPcmWaveHeader, interleavePcm16 } from '../codec/boundary/pcm.js'
|
|
22
|
+
import { serializeFrame } from '../codec/syntax/frame.js'
|
|
26
23
|
import { EncoderOptions } from '../codec/core/options.js'
|
|
27
24
|
import {
|
|
28
25
|
SAMPLE_RATE,
|
|
29
26
|
SAMPLES_PER_FRAME,
|
|
30
27
|
BITRATE_PER_CHANNEL,
|
|
31
|
-
AEA_HEADER_SIZE,
|
|
32
|
-
SOUND_UNIT_SIZE,
|
|
33
28
|
} from '../codec/core/constants.js'
|
|
34
29
|
|
|
30
|
+
const LITTLE_ENDIAN_PCM = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1
|
|
31
|
+
|
|
35
32
|
/**
|
|
36
33
|
* Format duration in seconds to MM:SS format
|
|
37
34
|
*
|
|
@@ -50,9 +47,7 @@ function formatTime(seconds) {
|
|
|
50
47
|
* Validate an AEA title for its fixed-width UTF-8 field.
|
|
51
48
|
*
|
|
52
49
|
* @param {string} title - Title to validate
|
|
53
|
-
* @returns {
|
|
54
|
-
* @returns {boolean} returns.valid - Whether title is valid
|
|
55
|
-
* @returns {string} [returns.error] - Error message if invalid
|
|
50
|
+
* @returns {{valid: boolean, error?: string}} Validation result
|
|
56
51
|
*/
|
|
57
52
|
function validateTitle(title) {
|
|
58
53
|
return validateAeaTitle(title)
|
|
@@ -62,12 +57,9 @@ function validateTitle(title) {
|
|
|
62
57
|
* Validate fixed block modes format and values
|
|
63
58
|
*
|
|
64
59
|
* @param {string} modes - Modes string in format "a,b,c"
|
|
65
|
-
* @returns {
|
|
66
|
-
* @returns {boolean} returns.valid - Whether modes are valid
|
|
67
|
-
* @returns {Array<number>} [returns.modes] - Parsed modes if valid
|
|
68
|
-
* @returns {string} [returns.error] - Error message if invalid
|
|
60
|
+
* @returns {{valid: boolean, modes?: Array<number>, error?: string}} Validation result
|
|
69
61
|
*/
|
|
70
|
-
function validateModes(modes) {
|
|
62
|
+
export function validateModes(modes) {
|
|
71
63
|
if (!modes) {
|
|
72
64
|
return { valid: true }
|
|
73
65
|
}
|
|
@@ -121,7 +113,7 @@ function validateModes(modes) {
|
|
|
121
113
|
*/
|
|
122
114
|
class ProgressTracker {
|
|
123
115
|
/**
|
|
124
|
-
* Create a progress tracker
|
|
116
|
+
* Create a progress tracker.
|
|
125
117
|
*
|
|
126
118
|
* @param {number} frameCount - Total number of frames to process
|
|
127
119
|
* @param {string} operation - Operation name ('Encoding' or 'Decoding')
|
|
@@ -129,55 +121,79 @@ class ProgressTracker {
|
|
|
129
121
|
*/
|
|
130
122
|
constructor(frameCount, operation, quiet = false) {
|
|
131
123
|
this.totalFrames = frameCount
|
|
132
|
-
this.
|
|
124
|
+
this.operation = operation
|
|
125
|
+
this.enabled = !quiet && process.stderr.isTTY
|
|
133
126
|
this.startTime = performance.now()
|
|
127
|
+
this.lastRender = -Infinity
|
|
134
128
|
this.frameCount = 0
|
|
135
|
-
|
|
136
|
-
if (!quiet) {
|
|
137
|
-
this.bar = new cliProgress.SingleBar(
|
|
138
|
-
{
|
|
139
|
-
autopadding: true,
|
|
140
|
-
format: `${operation} |{bar}| {percentage}% | {value}/{total} frames | {elapsed}/{remaining} | RT: {speed}x`,
|
|
141
|
-
},
|
|
142
|
-
cliProgress.Presets.rect
|
|
143
|
-
)
|
|
144
|
-
this.bar.start(frameCount, 0)
|
|
145
|
-
}
|
|
129
|
+
this.render()
|
|
146
130
|
}
|
|
147
131
|
|
|
148
132
|
/**
|
|
149
|
-
* Update progress with a new processed frame
|
|
133
|
+
* Update progress with a new processed frame.
|
|
150
134
|
*
|
|
151
135
|
* @param {number} sampleRate - Audio sample rate for RT speed calculation
|
|
152
136
|
*/
|
|
153
137
|
update(sampleRate) {
|
|
154
138
|
this.frameCount++
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
const audioProcessed = (this.frameCount * SAMPLES_PER_FRAME) / sampleRate
|
|
158
|
-
const rtSpeed = elapsed > 0 ? audioProcessed / elapsed : 0
|
|
159
|
-
const progress = this.frameCount / this.totalFrames
|
|
160
|
-
const estimatedTotal = progress > 0 ? elapsed / progress : 0
|
|
161
|
-
const remaining = Math.max(0, estimatedTotal - elapsed)
|
|
162
|
-
|
|
163
|
-
this.bar.update(this.frameCount, {
|
|
164
|
-
speed: rtSpeed.toFixed(1),
|
|
165
|
-
elapsed: formatTime(elapsed),
|
|
166
|
-
remaining: formatTime(remaining),
|
|
167
|
-
})
|
|
168
|
-
}
|
|
139
|
+
this.sampleRate = sampleRate
|
|
140
|
+
this.render()
|
|
169
141
|
}
|
|
170
142
|
|
|
171
143
|
/**
|
|
172
|
-
*
|
|
144
|
+
* Render a throttled progress update on an interactive terminal.
|
|
145
|
+
*
|
|
146
|
+
* @param {boolean} [force=false] - Render even inside the throttle interval
|
|
173
147
|
*/
|
|
148
|
+
render(force = false) {
|
|
149
|
+
if (!this.enabled) return
|
|
150
|
+
const now = performance.now()
|
|
151
|
+
if (!force && now - this.lastRender < 100) return
|
|
152
|
+
this.lastRender = now
|
|
153
|
+
const elapsed = (now - this.startTime) / 1000
|
|
154
|
+
const fraction =
|
|
155
|
+
this.totalFrames > 0 ? Math.min(1, this.frameCount / this.totalFrames) : 1
|
|
156
|
+
const filled = Math.floor(fraction * 24)
|
|
157
|
+
const remaining = fraction > 0 ? elapsed * (1 / fraction - 1) : 0
|
|
158
|
+
const speed =
|
|
159
|
+
elapsed > 0
|
|
160
|
+
? (this.frameCount * SAMPLES_PER_FRAME) /
|
|
161
|
+
(this.sampleRate || SAMPLE_RATE) /
|
|
162
|
+
elapsed
|
|
163
|
+
: 0
|
|
164
|
+
process.stderr.write(
|
|
165
|
+
`\r\x1b[2K${this.operation} |${'█'.repeat(filled)}${'░'.repeat(24 - filled)}| ${Math.floor(fraction * 100)}% | ${this.frameCount}/${this.totalFrames} frames | ${formatTime(elapsed)}/${formatTime(remaining)} | RT: ${speed.toFixed(1)}x`
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Stop the progress display after rendering the final frame count. */
|
|
174
170
|
stop() {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
}
|
|
171
|
+
this.render(true)
|
|
172
|
+
if (this.enabled) process.stderr.write('\n')
|
|
178
173
|
}
|
|
179
174
|
}
|
|
180
175
|
|
|
176
|
+
/**
|
|
177
|
+
* Convert PCM sample to normalized float32 value
|
|
178
|
+
*
|
|
179
|
+
* @private
|
|
180
|
+
* @param {Buffer} buffer - PCM data buffer
|
|
181
|
+
* @param {i32} offset - Byte offset to sample
|
|
182
|
+
* @param {number} bitDepth - PCM sample width in bits
|
|
183
|
+
* @returns {number} Normalized float value [-1.0, 1.0]
|
|
184
|
+
*/
|
|
185
|
+
function readPcmSample(buffer, offset, bitDepth) {
|
|
186
|
+
if (bitDepth === 16) return buffer.readInt16LE(offset) / 32768.0
|
|
187
|
+
if (bitDepth === 24) {
|
|
188
|
+
let s =
|
|
189
|
+
buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16)
|
|
190
|
+
if (s > 0x7fffff) s -= 0x1000000
|
|
191
|
+
return s / 8388608.0
|
|
192
|
+
}
|
|
193
|
+
if (bitDepth === 32) return buffer.readInt32LE(offset) / 2147483648.0
|
|
194
|
+
return 0
|
|
195
|
+
}
|
|
196
|
+
|
|
181
197
|
/**
|
|
182
198
|
* WAV file reader with streaming support
|
|
183
199
|
*
|
|
@@ -214,121 +230,104 @@ class WavReader {
|
|
|
214
230
|
* @throws {Error} If file cannot be read or has invalid format
|
|
215
231
|
*/
|
|
216
232
|
async loadMetadata() {
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
)
|
|
233
|
+
const handle = await fs.promises.open(this.filePath, 'r')
|
|
234
|
+
try {
|
|
235
|
+
const header = Buffer.alloc(12)
|
|
236
|
+
await handle.read(header, 0, 12, 0)
|
|
237
|
+
if (
|
|
238
|
+
header.toString('ascii', 0, 4) !== 'RIFF' ||
|
|
239
|
+
header.toString('ascii', 8, 12) !== 'WAVE'
|
|
240
|
+
)
|
|
241
|
+
throw new Error('Invalid RIFF/WAVE input')
|
|
242
|
+
const size = (await handle.stat()).size
|
|
243
|
+
let format = false
|
|
244
|
+
let data = false
|
|
245
|
+
for (let offset = 12; offset + 8 <= size;) {
|
|
246
|
+
const chunk = Buffer.alloc(8)
|
|
247
|
+
await handle.read(chunk, 0, 8, offset)
|
|
248
|
+
const length = chunk.readUInt32LE(4)
|
|
249
|
+
if (offset + 8 + length > size) throw new Error('Truncated WAV chunk')
|
|
250
|
+
const name = chunk.toString('ascii', 0, 4)
|
|
251
|
+
if (name === 'fmt ') {
|
|
252
|
+
if (length < 16) throw new Error('Invalid WAV format')
|
|
253
|
+
const bytes = Buffer.alloc(16)
|
|
254
|
+
await handle.read(bytes, 0, 16, offset + 8)
|
|
255
|
+
if (bytes.readUInt16LE(0) !== 1)
|
|
256
|
+
throw new Error('Expected integer PCM WAV')
|
|
257
|
+
this.channels = bytes.readUInt16LE(2)
|
|
258
|
+
this.sampleRate = bytes.readUInt32LE(4)
|
|
259
|
+
this.bitDepth = bytes.readUInt16LE(14)
|
|
260
|
+
format = true
|
|
261
|
+
} else if (name === 'data') {
|
|
262
|
+
this.dataOffset = offset + 8
|
|
263
|
+
this.dataSize = length
|
|
264
|
+
data = true
|
|
242
265
|
}
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
266
|
+
if (format && data) break
|
|
267
|
+
offset += 8 + length + (length & 1)
|
|
268
|
+
}
|
|
269
|
+
if (
|
|
270
|
+
!format ||
|
|
271
|
+
!data ||
|
|
272
|
+
![16, 24, 32].includes(this.bitDepth) ||
|
|
273
|
+
![1, 2].includes(this.channels)
|
|
274
|
+
)
|
|
275
|
+
throw new Error('Expected mono/stereo 16/24/32-bit PCM WAV')
|
|
276
|
+
const stride = (this.channels * this.bitDepth) / 8
|
|
277
|
+
if (this.dataSize % stride !== 0) throw new Error('Incomplete WAV sample')
|
|
278
|
+
this.totalSamples = this.dataSize / stride
|
|
279
|
+
this.duration = this.totalSamples / this.sampleRate
|
|
280
|
+
if (this.sampleRate !== SAMPLE_RATE)
|
|
281
|
+
console.log(
|
|
282
|
+
`Warning: Input sample rate ${this.sampleRate}Hz, expected ${SAMPLE_RATE}Hz`
|
|
283
|
+
)
|
|
284
|
+
} finally {
|
|
285
|
+
await handle.close()
|
|
286
|
+
}
|
|
250
287
|
}
|
|
251
288
|
|
|
252
289
|
/**
|
|
253
|
-
* Async iterator for streaming WAV file frames
|
|
290
|
+
* Async iterator for streaming WAV file frames.
|
|
291
|
+
*
|
|
292
|
+
* Reads bounded PCM batches, yielding one frame at a time and zero-padding
|
|
293
|
+
* a final partial frame.
|
|
294
|
+
* Channel state belongs to the downstream encoder closures.
|
|
254
295
|
*
|
|
255
|
-
* @param {
|
|
256
|
-
* @yields {Float32Array|Array<Float32Array>}
|
|
257
|
-
* - Mono: Float32Array of samples
|
|
258
|
-
* - Stereo: [left, right] Float32Arrays
|
|
296
|
+
* @param {i32} [frameSize=SAMPLES_PER_FRAME] - Samples per frame
|
|
297
|
+
* @yields {Float32Array|Array<Float32Array>} Mono samples or stereo channels
|
|
259
298
|
*/
|
|
260
299
|
async *[Symbol.asyncIterator](frameSize = SAMPLES_PER_FRAME) {
|
|
261
|
-
const
|
|
262
|
-
const
|
|
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
|
-
if (resolveDataPromise) {
|
|
289
|
-
resolveDataPromise()
|
|
290
|
-
resolveDataPromise = null
|
|
291
|
-
}
|
|
292
|
-
})
|
|
293
|
-
|
|
294
|
-
let buffer = Buffer.alloc(0)
|
|
295
|
-
const bytesPerSample = this.bitDepth / 8
|
|
296
|
-
const frameByteSize = frameSize * this.channels * bytesPerSample
|
|
297
|
-
|
|
298
|
-
while (true) {
|
|
299
|
-
if (streamError) throw streamError
|
|
300
|
-
|
|
301
|
-
while (pcmQueue.length > 0) {
|
|
302
|
-
buffer = Buffer.concat([buffer, ...pcmQueue])
|
|
303
|
-
pcmQueue = []
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
while (buffer.length >= frameByteSize) {
|
|
307
|
-
const frameBuffer = buffer.slice(0, frameByteSize)
|
|
308
|
-
buffer = buffer.slice(frameByteSize)
|
|
309
|
-
yield this._processFrameBuffer(frameBuffer, frameSize)
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
if (streamEnded && pcmQueue.length === 0) {
|
|
313
|
-
if (buffer.length > 0) {
|
|
314
|
-
const paddedFrame = Buffer.concat([
|
|
315
|
-
buffer,
|
|
316
|
-
Buffer.alloc(frameByteSize - buffer.length),
|
|
317
|
-
])
|
|
318
|
-
yield this._processFrameBuffer(paddedFrame, frameSize)
|
|
300
|
+
const handle = await fs.promises.open(this.filePath, 'r')
|
|
301
|
+
const frameBytes = (frameSize * this.channels * this.bitDepth) / 8
|
|
302
|
+
const batchBytes = frameBytes * 32
|
|
303
|
+
try {
|
|
304
|
+
for (let offset = 0; offset < this.dataSize; offset += batchBytes) {
|
|
305
|
+
const bytes = Buffer.alloc(batchBytes)
|
|
306
|
+
const count = Math.min(batchBytes, this.dataSize - offset)
|
|
307
|
+
let read = 0
|
|
308
|
+
while (read < count) {
|
|
309
|
+
const result = await handle.read(
|
|
310
|
+
bytes,
|
|
311
|
+
read,
|
|
312
|
+
count - read,
|
|
313
|
+
this.dataOffset + offset + read
|
|
314
|
+
)
|
|
315
|
+
if (result.bytesRead === 0) throw new Error('Truncated WAV input')
|
|
316
|
+
read += result.bytesRead
|
|
317
|
+
}
|
|
318
|
+
for (
|
|
319
|
+
let frameOffset = 0;
|
|
320
|
+
frameOffset < count;
|
|
321
|
+
frameOffset += frameBytes
|
|
322
|
+
) {
|
|
323
|
+
yield this._processFrameBuffer(
|
|
324
|
+
bytes.subarray(frameOffset, frameOffset + frameBytes),
|
|
325
|
+
frameSize
|
|
326
|
+
)
|
|
319
327
|
}
|
|
320
|
-
break
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
if (!streamEnded) {
|
|
324
|
-
await new Promise((resolve) => {
|
|
325
|
-
resolveDataPromise = resolve
|
|
326
|
-
if (pcmQueue.length > 0 || streamEnded) {
|
|
327
|
-
resolveDataPromise = null
|
|
328
|
-
resolve()
|
|
329
|
-
}
|
|
330
|
-
})
|
|
331
328
|
}
|
|
329
|
+
} finally {
|
|
330
|
+
await handle.close()
|
|
332
331
|
}
|
|
333
332
|
}
|
|
334
333
|
|
|
@@ -337,46 +336,118 @@ class WavReader {
|
|
|
337
336
|
*
|
|
338
337
|
* @private
|
|
339
338
|
* @param {Buffer} frameBuffer - Raw PCM data
|
|
340
|
-
* @param {
|
|
339
|
+
* @param {i32} frameSize - Number of samples per channel
|
|
341
340
|
* @returns {Float32Array|Array<Float32Array>} Processed frame data
|
|
342
341
|
*/
|
|
343
342
|
_processFrameBuffer(frameBuffer, frameSize) {
|
|
344
|
-
|
|
343
|
+
const channels = this.channels | 0
|
|
344
|
+
const bitDepth = this.bitDepth | 0
|
|
345
|
+
const bytesPerSample = bitDepth / 8
|
|
346
|
+
if (bitDepth === 16 && LITTLE_ENDIAN_PCM) {
|
|
347
|
+
const samples = new Int16Array(
|
|
348
|
+
frameBuffer.buffer,
|
|
349
|
+
frameBuffer.byteOffset,
|
|
350
|
+
frameBuffer.length / 2
|
|
351
|
+
)
|
|
352
|
+
const left = new Float32Array(frameSize)
|
|
353
|
+
for (let i = 0; i < frameSize; i++) {
|
|
354
|
+
left[i] = samples[i * channels] / 32768.0
|
|
355
|
+
}
|
|
356
|
+
if (channels === 1) return left
|
|
357
|
+
|
|
358
|
+
const right = new Float32Array(frameSize)
|
|
359
|
+
for (let i = 0; i < frameSize; i++) {
|
|
360
|
+
right[i] = samples[i * 2 + 1] / 32768.0
|
|
361
|
+
}
|
|
362
|
+
return [left, right]
|
|
363
|
+
}
|
|
364
|
+
if (bitDepth === 32 && LITTLE_ENDIAN_PCM) {
|
|
365
|
+
const samples = new Int32Array(
|
|
366
|
+
frameBuffer.buffer,
|
|
367
|
+
frameBuffer.byteOffset,
|
|
368
|
+
frameBuffer.length / 4
|
|
369
|
+
)
|
|
370
|
+
const left = new Float32Array(frameSize)
|
|
371
|
+
for (let i = 0; i < frameSize; i++) {
|
|
372
|
+
left[i] = samples[i * channels] / 2147483648.0
|
|
373
|
+
}
|
|
374
|
+
if (channels === 1) return left
|
|
375
|
+
|
|
376
|
+
const right = new Float32Array(frameSize)
|
|
377
|
+
for (let i = 0; i < frameSize; i++) {
|
|
378
|
+
right[i] = samples[i * 2 + 1] / 2147483648.0
|
|
379
|
+
}
|
|
380
|
+
return [left, right]
|
|
381
|
+
}
|
|
382
|
+
if (channels === 1) {
|
|
345
383
|
const frame = new Float32Array(frameSize)
|
|
346
384
|
for (let i = 0; i < frameSize; i++) {
|
|
347
|
-
frame[i] =
|
|
385
|
+
frame[i] = readPcmSample(frameBuffer, i * bytesPerSample, bitDepth)
|
|
348
386
|
}
|
|
349
387
|
return frame
|
|
350
388
|
} else {
|
|
351
389
|
const left = new Float32Array(frameSize)
|
|
352
390
|
const right = new Float32Array(frameSize)
|
|
353
391
|
for (let i = 0; i < frameSize; i++) {
|
|
354
|
-
const offset = i *
|
|
355
|
-
left[i] =
|
|
356
|
-
right[i] =
|
|
392
|
+
const offset = i * channels * bytesPerSample
|
|
393
|
+
left[i] = readPcmSample(frameBuffer, offset, bitDepth)
|
|
394
|
+
right[i] = readPcmSample(frameBuffer, offset + bytesPerSample, bitDepth)
|
|
357
395
|
}
|
|
358
396
|
return [left, right]
|
|
359
397
|
}
|
|
360
398
|
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Write a complete byte block, handling partial filesystem writes.
|
|
403
|
+
*
|
|
404
|
+
* @param {import('node:fs/promises').FileHandle} handle - Open output file
|
|
405
|
+
* @param {Uint8Array} bytes - Bytes to write
|
|
406
|
+
* @param {number|null} [position=null] - Absolute offset or the current position
|
|
407
|
+
* @returns {Promise<void>}
|
|
408
|
+
*/
|
|
409
|
+
async function writeBytes(handle, bytes, position = null) {
|
|
410
|
+
let offset = 0
|
|
411
|
+
while (offset < bytes.length) {
|
|
412
|
+
const result = await handle.write(
|
|
413
|
+
bytes,
|
|
414
|
+
offset,
|
|
415
|
+
bytes.length - offset,
|
|
416
|
+
position === null ? null : position + offset
|
|
417
|
+
)
|
|
418
|
+
if (result.bytesWritten === 0) throw new Error('Could not write output')
|
|
419
|
+
offset += result.bytesWritten
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** Buffer frame writes without retaining the encoded or decoded stream. */
|
|
424
|
+
class BufferedWriter {
|
|
425
|
+
/** @param {import('node:fs/promises').FileHandle} handle - Open output file */
|
|
426
|
+
constructor(handle) {
|
|
427
|
+
this.handle = handle
|
|
428
|
+
this.buffer = Buffer.alloc(65536)
|
|
429
|
+
this.used = 0
|
|
430
|
+
}
|
|
361
431
|
|
|
362
432
|
/**
|
|
363
|
-
*
|
|
364
|
-
*
|
|
365
|
-
* @private
|
|
366
|
-
* @param {Buffer} buffer - PCM data buffer
|
|
367
|
-
* @param {number} offset - Byte offset to sample
|
|
368
|
-
* @returns {number} Normalized float value [-1.0, 1.0]
|
|
433
|
+
* @param {Uint8Array} bytes - Next frame's bytes
|
|
434
|
+
* @returns {Promise<void>}
|
|
369
435
|
*/
|
|
370
|
-
|
|
371
|
-
if (this.
|
|
372
|
-
if (
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
if (s > 0x7fffff) s -= 0x1000000
|
|
376
|
-
return s / 8388608.0
|
|
436
|
+
async write(bytes) {
|
|
437
|
+
if (this.used + bytes.length > this.buffer.length) await this.flush()
|
|
438
|
+
if (bytes.length >= this.buffer.length) {
|
|
439
|
+
await writeBytes(this.handle, bytes)
|
|
440
|
+
return
|
|
377
441
|
}
|
|
378
|
-
|
|
379
|
-
|
|
442
|
+
this.buffer.set(bytes, this.used)
|
|
443
|
+
this.used += bytes.length
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** @returns {Promise<void>} Resolves when all pending bytes are written. */
|
|
447
|
+
async flush() {
|
|
448
|
+
if (this.used === 0) return
|
|
449
|
+
await writeBytes(this.handle, this.buffer.subarray(0, this.used))
|
|
450
|
+
this.used = 0
|
|
380
451
|
}
|
|
381
452
|
}
|
|
382
453
|
|
|
@@ -456,14 +527,34 @@ async function encodeFile(inputFile, outputFile, options) {
|
|
|
456
527
|
})
|
|
457
528
|
|
|
458
529
|
const title = options.title || path.basename(outputFile, '.aea')
|
|
459
|
-
const
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
530
|
+
const output = await fs.promises.open(
|
|
531
|
+
outputFile,
|
|
532
|
+
options.force ? 'w' : 'wx'
|
|
533
|
+
)
|
|
534
|
+
const writer = new BufferedWriter(output)
|
|
535
|
+
/** @type {f64} Total sound units written to the stream. */
|
|
536
|
+
let count = 0
|
|
537
|
+
try {
|
|
538
|
+
await writeBytes(
|
|
539
|
+
output,
|
|
540
|
+
AeaFile.createHeader(title, 0, reader.channels, reader.totalSamples)
|
|
541
|
+
)
|
|
542
|
+
for await (const frame of encodedFrames) {
|
|
543
|
+
const bytes = serializeFrame(frame)
|
|
544
|
+
await writer.write(bytes)
|
|
545
|
+
count++
|
|
546
|
+
}
|
|
547
|
+
await writer.flush()
|
|
548
|
+
const header = AeaFile.createHeader(
|
|
549
|
+
title,
|
|
550
|
+
count,
|
|
551
|
+
reader.channels,
|
|
552
|
+
reader.totalSamples
|
|
553
|
+
)
|
|
554
|
+
await writeBytes(output, header, 0)
|
|
555
|
+
} finally {
|
|
556
|
+
await output.close()
|
|
557
|
+
}
|
|
467
558
|
} finally {
|
|
468
559
|
progress.stop()
|
|
469
560
|
}
|
|
@@ -515,191 +606,208 @@ async function decodeFile(inputFile, outputFile, options) {
|
|
|
515
606
|
onProgress,
|
|
516
607
|
})
|
|
517
608
|
|
|
518
|
-
const
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
metadata.channelCount,
|
|
522
|
-
SAMPLE_RATE
|
|
609
|
+
const output = await fs.promises.open(
|
|
610
|
+
outputFile,
|
|
611
|
+
options.force ? 'w' : 'wx'
|
|
523
612
|
)
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
613
|
+
const writer = new BufferedWriter(output)
|
|
614
|
+
/** @type {f64} Total samples written to the stream. */
|
|
615
|
+
let sampleCount = 0
|
|
616
|
+
try {
|
|
617
|
+
await writeBytes(
|
|
618
|
+
output,
|
|
619
|
+
createPcmWaveHeader({
|
|
620
|
+
sampleCount: 0,
|
|
621
|
+
sampleRate: SAMPLE_RATE,
|
|
622
|
+
channels: metadata.channelCount,
|
|
623
|
+
})
|
|
624
|
+
)
|
|
625
|
+
for await (const frame of decodedFrames) {
|
|
626
|
+
const channels = metadata.channelCount === 1 ? [frame] : frame
|
|
627
|
+
await writer.write(interleavePcm16(channels))
|
|
628
|
+
sampleCount += channels[0].length
|
|
629
|
+
}
|
|
630
|
+
await writer.flush()
|
|
631
|
+
const header = createPcmWaveHeader({
|
|
632
|
+
sampleCount,
|
|
633
|
+
sampleRate: SAMPLE_RATE,
|
|
634
|
+
channels: metadata.channelCount,
|
|
635
|
+
})
|
|
636
|
+
await writeBytes(output, header, 0)
|
|
637
|
+
} finally {
|
|
638
|
+
await output.close()
|
|
639
|
+
}
|
|
527
640
|
} finally {
|
|
528
641
|
progress.stop()
|
|
529
642
|
}
|
|
530
643
|
}
|
|
531
644
|
|
|
645
|
+
/** Command-line options shared by parsing and help output. */
|
|
646
|
+
const CLI_OPTIONS = [
|
|
647
|
+
{ short: 'V', name: 'version', description: 'output the version number' },
|
|
648
|
+
{ short: 'e', name: 'encode', description: 'Encode WAV to AEA' },
|
|
649
|
+
{ short: 'd', name: 'decode', description: 'Decode AEA to WAV' },
|
|
650
|
+
{
|
|
651
|
+
short: 'q',
|
|
652
|
+
name: 'quiet',
|
|
653
|
+
description: 'Suppress all output except errors',
|
|
654
|
+
},
|
|
655
|
+
{
|
|
656
|
+
short: 'f',
|
|
657
|
+
name: 'force',
|
|
658
|
+
description: 'Overwrite output file if it exists',
|
|
659
|
+
},
|
|
660
|
+
{
|
|
661
|
+
short: 't',
|
|
662
|
+
name: 'title',
|
|
663
|
+
value: 'title',
|
|
664
|
+
description: 'Custom UTF-8 title for AEA file metadata (encoding only)',
|
|
665
|
+
},
|
|
666
|
+
{
|
|
667
|
+
short: 'b',
|
|
668
|
+
name: 'bias',
|
|
669
|
+
value: 'value',
|
|
670
|
+
description: 'Bit allocation bias (default: 1.0)',
|
|
671
|
+
},
|
|
672
|
+
{
|
|
673
|
+
short: 'm',
|
|
674
|
+
name: 'modes',
|
|
675
|
+
value: 'modes',
|
|
676
|
+
description:
|
|
677
|
+
'Fixed block modes [0/2],[0/2],[0/3] for low,mid,high bands (skips transient detection)',
|
|
678
|
+
},
|
|
679
|
+
{ short: 'h', name: 'help', description: 'display help for command' },
|
|
680
|
+
]
|
|
681
|
+
|
|
682
|
+
/** Print usage and the supported options. */
|
|
683
|
+
function printHelp() {
|
|
684
|
+
console.log(`Usage: carta1 [options] <input> <output>
|
|
685
|
+
|
|
686
|
+
ATRAC1 Audio Codec
|
|
687
|
+
|
|
688
|
+
Arguments:
|
|
689
|
+
input Input file path
|
|
690
|
+
output Output file path
|
|
691
|
+
|
|
692
|
+
Options:`)
|
|
693
|
+
for (const option of CLI_OPTIONS) {
|
|
694
|
+
const value = option.value ? ` <${option.value}>` : ''
|
|
695
|
+
const flags = `-${option.short}, --${option.name}${value}`
|
|
696
|
+
console.log(` ${flags.padEnd(21)}${option.description}`)
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
532
700
|
/**
|
|
533
|
-
*
|
|
701
|
+
* Report invalid command-line syntax without an internal stack trace.
|
|
534
702
|
*
|
|
535
|
-
*
|
|
536
|
-
*
|
|
537
|
-
* and statistical analysis.
|
|
538
|
-
*
|
|
539
|
-
* @param {string} inputFile - Path to input AEA file
|
|
540
|
-
* @param {string} outputFile - Path to output JSON file
|
|
541
|
-
* @param {Object} options - CLI options
|
|
542
|
-
* @param {boolean} options.quiet - Suppress progress output
|
|
543
|
-
* @returns {Promise<void>} Resolves when dump is complete
|
|
544
|
-
* @throws {Error} If input file is invalid or cannot be read
|
|
703
|
+
* @param {string} message - Argument error to display.
|
|
704
|
+
* @returns {never}
|
|
545
705
|
*/
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
console.log(`${inputFile} (AEA) → ${outputFile} (JSON)`)
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
const handle = await fs.promises.open(inputFile, 'r')
|
|
554
|
-
const headerBuffer = Buffer.alloc(AEA_HEADER_SIZE)
|
|
555
|
-
await handle.read(headerBuffer, 0, AEA_HEADER_SIZE, 0)
|
|
556
|
-
|
|
557
|
-
let metadata
|
|
558
|
-
try {
|
|
559
|
-
metadata = AeaFile.parseHeader(headerBuffer)
|
|
560
|
-
} catch (err) {
|
|
561
|
-
throw new Error(`Invalid AEA header: ${err.message}`)
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
const frameCount = Math.floor(
|
|
565
|
-
(stats.size - AEA_HEADER_SIZE) / SOUND_UNIT_SIZE
|
|
566
|
-
)
|
|
567
|
-
|
|
568
|
-
const dump = {
|
|
569
|
-
file: {
|
|
570
|
-
path: inputFile,
|
|
571
|
-
size: stats.size,
|
|
572
|
-
headerSize: AEA_HEADER_SIZE,
|
|
573
|
-
dataSize: stats.size - AEA_HEADER_SIZE,
|
|
574
|
-
expectedDataSize: frameCount * SOUND_UNIT_SIZE,
|
|
575
|
-
sizeDifference:
|
|
576
|
-
stats.size - AEA_HEADER_SIZE - frameCount * SOUND_UNIT_SIZE,
|
|
577
|
-
},
|
|
578
|
-
header: {
|
|
579
|
-
magic: Array.from(headerBuffer.slice(0, 4))
|
|
580
|
-
.map((b) => b.toString(16).padStart(2, '0'))
|
|
581
|
-
.join(' '),
|
|
582
|
-
title: metadata.title,
|
|
583
|
-
frameCount: metadata.frameCount,
|
|
584
|
-
channelCount: metadata.channelCount,
|
|
585
|
-
framesPerChannel: metadata.frameCount / metadata.channelCount,
|
|
586
|
-
duration: ((metadata.frameCount / metadata.channelCount) * 512) / 44100,
|
|
587
|
-
},
|
|
588
|
-
frames: [],
|
|
589
|
-
}
|
|
706
|
+
function argumentError(message) {
|
|
707
|
+
console.error(`error: ${message}`)
|
|
708
|
+
process.exit(1)
|
|
709
|
+
}
|
|
590
710
|
|
|
591
|
-
|
|
711
|
+
/**
|
|
712
|
+
* Parse long options, combined short flags, option values, and positional paths.
|
|
713
|
+
* A double dash ends option parsing so paths may start with a dash.
|
|
714
|
+
*
|
|
715
|
+
* @param {string[]} args - Arguments after the executable and script names.
|
|
716
|
+
* @param {string} version - Package version to display for --version.
|
|
717
|
+
* @returns {{options: object, paths: string[]}} Parsed options and paths.
|
|
718
|
+
*/
|
|
719
|
+
function parseArguments(args, version) {
|
|
720
|
+
const options = {}
|
|
721
|
+
const paths = []
|
|
722
|
+
let positional = false
|
|
723
|
+
let unknownOption = null
|
|
724
|
+
|
|
725
|
+
for (let index = 0; index < args.length; index++) {
|
|
726
|
+
const argument = args[index]
|
|
727
|
+
if (positional || argument === '-' || !argument.startsWith('-')) {
|
|
728
|
+
paths.push(argument)
|
|
729
|
+
continue
|
|
730
|
+
}
|
|
731
|
+
if (argument === '--') {
|
|
732
|
+
positional = true
|
|
733
|
+
continue
|
|
734
|
+
}
|
|
592
735
|
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
(coeffs) => coeffs && coeffs.some((c) => c !== 0)
|
|
613
|
-
),
|
|
614
|
-
}
|
|
736
|
+
const long = argument.startsWith('--')
|
|
737
|
+
const equals = long ? argument.indexOf('=') : -1
|
|
738
|
+
let offset = 1
|
|
739
|
+
do {
|
|
740
|
+
const name = long
|
|
741
|
+
? argument.slice(2, equals === -1 ? argument.length : equals)
|
|
742
|
+
: argument[offset++]
|
|
743
|
+
const option = CLI_OPTIONS.find((candidate) =>
|
|
744
|
+
long ? candidate.name === name : candidate.short === name
|
|
745
|
+
)
|
|
746
|
+
const flag = long ? `--${name}` : `-${name}`
|
|
747
|
+
if (
|
|
748
|
+
!option ||
|
|
749
|
+
(!option.value && equals !== -1) ||
|
|
750
|
+
(option.name === 'help' && !long && offset < argument.length)
|
|
751
|
+
) {
|
|
752
|
+
unknownOption ||= argument
|
|
753
|
+
break
|
|
754
|
+
}
|
|
615
755
|
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
756
|
+
let value = true
|
|
757
|
+
if (option.value) {
|
|
758
|
+
if (equals !== -1) {
|
|
759
|
+
value = argument.slice(equals + 1)
|
|
760
|
+
} else if (!long && offset < argument.length) {
|
|
761
|
+
value = argument.slice(offset)
|
|
762
|
+
} else {
|
|
763
|
+
value = args[++index]
|
|
764
|
+
if (value === undefined) {
|
|
765
|
+
argumentError(`option '${flag}' argument missing`)
|
|
766
|
+
}
|
|
621
767
|
}
|
|
622
|
-
|
|
623
|
-
dump.frames.push(frameInfo)
|
|
624
|
-
} catch (err) {
|
|
625
|
-
dump.frames.push({
|
|
626
|
-
index: i,
|
|
627
|
-
offset: offset,
|
|
628
|
-
offsetHex: '0x' + offset.toString(16),
|
|
629
|
-
error: err.message,
|
|
630
|
-
})
|
|
768
|
+
offset = argument.length
|
|
631
769
|
}
|
|
632
770
|
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
771
|
+
if (option.name === 'help') {
|
|
772
|
+
printHelp()
|
|
773
|
+
process.exit(0)
|
|
774
|
+
}
|
|
775
|
+
if (option.name === 'version') {
|
|
776
|
+
console.log(version)
|
|
777
|
+
process.exit(0)
|
|
778
|
+
}
|
|
779
|
+
options[option.name] = option.name === 'bias' ? parseFloat(value) : value
|
|
780
|
+
} while (!long && offset < argument.length)
|
|
639
781
|
}
|
|
640
782
|
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
silentFrames: dump.frames.filter(
|
|
647
|
-
(f) => !f.error && !f.hasNonZeroScaleFactors && !f.hasNonZeroWordLengths
|
|
648
|
-
).length,
|
|
649
|
-
activeFrames: dump.frames.filter(
|
|
650
|
-
(f) => !f.error && (f.hasNonZeroScaleFactors || f.hasNonZeroWordLengths)
|
|
651
|
-
).length,
|
|
783
|
+
if (unknownOption) argumentError(`unknown option '${unknownOption}'`)
|
|
784
|
+
if (paths.length < 2) {
|
|
785
|
+
argumentError(
|
|
786
|
+
`missing required argument '${paths.length ? 'output' : 'input'}'`
|
|
787
|
+
)
|
|
652
788
|
}
|
|
653
|
-
|
|
654
|
-
const jsonOutput = JSON.stringify(dump, null, 2)
|
|
655
|
-
await fs.promises.writeFile(outputFile, jsonOutput)
|
|
789
|
+
return { options, paths }
|
|
656
790
|
}
|
|
657
791
|
|
|
658
792
|
/**
|
|
659
793
|
* Main CLI entry point
|
|
660
794
|
*
|
|
661
|
-
* Parses command line arguments and executes encoding
|
|
662
|
-
*
|
|
795
|
+
* Parses command line arguments and executes encoding or decoding
|
|
796
|
+
* with error handling and validation.
|
|
663
797
|
*
|
|
664
798
|
* @returns {Promise<void>} Resolves when operation is complete
|
|
665
799
|
*/
|
|
666
800
|
async function main() {
|
|
667
801
|
const { version } = JSON.parse(
|
|
668
|
-
fs.readFileSync(new URL('../package.json', import.meta.url))
|
|
802
|
+
fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')
|
|
669
803
|
)
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
.description('ATRAC1 Audio Codec')
|
|
673
|
-
.version(version)
|
|
674
|
-
.option('-e, --encode', 'Encode WAV to AEA')
|
|
675
|
-
.option('-d, --decode', 'Decode AEA to WAV')
|
|
676
|
-
.option('-j, --json', 'Dump AEA file structure to JSON')
|
|
677
|
-
.option('-q, --quiet', 'Suppress all output except errors')
|
|
678
|
-
.option('-f, --force', 'Overwrite output file if it exists')
|
|
679
|
-
.option(
|
|
680
|
-
'-t, --title <title>',
|
|
681
|
-
'Custom UTF-8 title for AEA file metadata (encoding only)'
|
|
682
|
-
)
|
|
683
|
-
.option(
|
|
684
|
-
'-b, --bias <value>',
|
|
685
|
-
'Bit allocation bias (default: 1.0)',
|
|
686
|
-
parseFloat
|
|
687
|
-
)
|
|
688
|
-
.option(
|
|
689
|
-
'-m, --modes <modes>',
|
|
690
|
-
'Fixed block modes [0/2],[0/2],[0/3] for low,mid,high bands (skips transient detection)'
|
|
691
|
-
)
|
|
692
|
-
.argument('<input>', 'Input file path')
|
|
693
|
-
.argument('<output>', 'Output file path')
|
|
694
|
-
.parse()
|
|
695
|
-
|
|
696
|
-
const options = program.opts()
|
|
697
|
-
const [inputFile, outputFile] = program.args
|
|
804
|
+
const { options, paths } = parseArguments(process.argv.slice(2), version)
|
|
805
|
+
const [inputFile, outputFile] = paths
|
|
698
806
|
|
|
699
807
|
// Validate operation mode
|
|
700
|
-
const modes = [options.encode, options.decode
|
|
808
|
+
const modes = [options.encode, options.decode].filter(Boolean)
|
|
701
809
|
if (modes.length === 0) {
|
|
702
|
-
console.error('Error: Must specify
|
|
810
|
+
console.error('Error: Must specify --encode or --decode')
|
|
703
811
|
process.exit(1)
|
|
704
812
|
}
|
|
705
813
|
if (modes.length > 1) {
|
|
@@ -719,8 +827,6 @@ async function main() {
|
|
|
719
827
|
await encodeFile(inputFile, outputFile, options)
|
|
720
828
|
} else if (options.decode) {
|
|
721
829
|
await decodeFile(inputFile, outputFile, options)
|
|
722
|
-
} else if (options.json) {
|
|
723
|
-
await dumpFile(inputFile, outputFile, options)
|
|
724
830
|
}
|
|
725
831
|
} catch (error) {
|
|
726
832
|
if (error.code === 'ENOENT') {
|
|
@@ -735,10 +841,10 @@ async function main() {
|
|
|
735
841
|
}
|
|
736
842
|
}
|
|
737
843
|
|
|
738
|
-
|
|
844
|
+
try {
|
|
845
|
+
await main()
|
|
846
|
+
} catch (error) {
|
|
739
847
|
console.error(`An unhandled error occurred: ${error.message}`)
|
|
740
848
|
console.error(error.stack)
|
|
741
849
|
process.exit(1)
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
export { validateModes }
|
|
850
|
+
}
|