carta1 1.6.0 → 1.7.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/README.md +4 -61
- package/bin/cli.js +508 -239
- package/codec/allocation/solve.js +46 -28
- package/codec/analysis/blocks.js +4 -1
- package/codec/analysis/spectrum.js +17 -15
- package/codec/boundary/container.js +1 -1
- package/codec/boundary/pcm.js +2 -88
- package/codec/boundary/processor.js +4 -4
- package/codec/boundary/reader.js +2 -2
- package/codec/boundary/stream.js +56 -50
- package/codec/core/constants.js +6 -5
- package/codec/core/geometry.js +2 -2
- package/codec/core/tables.js +21 -98
- package/codec/quantization/spectrum.js +6 -6
- package/codec/signal/fft.js +1 -0
- package/codec/signal/mdct.js +48 -38
- package/codec/signal/qmf.js +37 -465
- package/codec/syntax/bitstream.js +9 -9
- package/codec/syntax/frame.js +11 -2
- package/codec/synthesis/bands.js +13 -14
- package/codec/synthesis/pcm.js +4 -0
- 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/package.json +4 -16
- package/bin/options.js +0 -41
- package/codec/boundary/inspect.js +0 -96
- package/dist/carta1.wme +0 -0
- package/dist/wme/index.js +0 -2
- package/dist/wme/index.js.map +0 -1
- package/docs/native.md +0 -107
- package/docs/porffor.md +0 -23
package/bin/cli.js
CHANGED
|
@@ -12,28 +12,23 @@
|
|
|
12
12
|
* carta1 --decode input.aea output.wav
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import { program } from 'commander'
|
|
16
|
-
import { validateModes } from './options.js'
|
|
17
|
-
import { inspectAea } from '../codec/boundary/inspect.js'
|
|
18
15
|
import fs from 'fs'
|
|
19
16
|
import path from 'path'
|
|
20
|
-
import { performance } from 'perf_hooks'
|
|
21
|
-
import cliProgress from 'cli-progress'
|
|
22
|
-
import wav from 'wav'
|
|
23
17
|
|
|
24
|
-
import { pcmBytesToChannels } from '../codec/boundary/pcm.js'
|
|
25
18
|
import { AudioProcessor } from '../codec/boundary/processor.js'
|
|
26
19
|
import { AeaReader } from '../codec/boundary/reader.js'
|
|
27
|
-
import { validateAeaTitle } from '../codec/boundary/container.js'
|
|
20
|
+
import { AeaFile, validateAeaTitle } from '../codec/boundary/container.js'
|
|
21
|
+
import { createPcmWaveHeader, interleavePcm16 } from '../codec/boundary/pcm.js'
|
|
22
|
+
import { serializeFrame } from '../codec/syntax/frame.js'
|
|
28
23
|
import { EncoderOptions } from '../codec/core/options.js'
|
|
29
24
|
import {
|
|
30
25
|
SAMPLE_RATE,
|
|
31
26
|
SAMPLES_PER_FRAME,
|
|
32
27
|
BITRATE_PER_CHANNEL,
|
|
33
|
-
AEA_HEADER_SIZE,
|
|
34
|
-
SOUND_UNIT_SIZE,
|
|
35
28
|
} from '../codec/core/constants.js'
|
|
36
29
|
|
|
30
|
+
const LITTLE_ENDIAN_PCM = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1
|
|
31
|
+
|
|
37
32
|
/**
|
|
38
33
|
* Format duration in seconds to MM:SS format
|
|
39
34
|
*
|
|
@@ -52,9 +47,7 @@ function formatTime(seconds) {
|
|
|
52
47
|
* Validate an AEA title for its fixed-width UTF-8 field.
|
|
53
48
|
*
|
|
54
49
|
* @param {string} title - Title to validate
|
|
55
|
-
* @returns {
|
|
56
|
-
* @returns {boolean} returns.valid - Whether title is valid
|
|
57
|
-
* @returns {string} [returns.error] - Error message if invalid
|
|
50
|
+
* @returns {{valid: boolean, error?: string}} Validation result
|
|
58
51
|
*/
|
|
59
52
|
function validateTitle(title) {
|
|
60
53
|
return validateAeaTitle(title)
|
|
@@ -64,11 +57,49 @@ function validateTitle(title) {
|
|
|
64
57
|
* Validate fixed block modes format and values
|
|
65
58
|
*
|
|
66
59
|
* @param {string} modes - Modes string in format "a,b,c"
|
|
67
|
-
* @returns {
|
|
68
|
-
* @returns {boolean} returns.valid - Whether modes are valid
|
|
69
|
-
* @returns {Array<number>} [returns.modes] - Parsed modes if valid
|
|
70
|
-
* @returns {string} [returns.error] - Error message if invalid
|
|
60
|
+
* @returns {{valid: boolean, modes?: Array<number>, error?: string}} Validation result
|
|
71
61
|
*/
|
|
62
|
+
export function validateModes(modes) {
|
|
63
|
+
if (!modes) {
|
|
64
|
+
return { valid: true }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const parts = modes.split(',')
|
|
68
|
+
if (parts.length !== 3) {
|
|
69
|
+
return {
|
|
70
|
+
valid: false,
|
|
71
|
+
error: `Modes must have exactly 3 values separated by commas, got ${parts.length}`,
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const parsedModes = []
|
|
76
|
+
const validValues = [
|
|
77
|
+
[0, 2], // Position 1: 0 or 2
|
|
78
|
+
[0, 2], // Position 2: 0 or 2
|
|
79
|
+
[0, 3], // Position 3: 0 or 3
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
for (let i = 0; i < 3; i++) {
|
|
83
|
+
const mode = parseInt(parts[i], 10)
|
|
84
|
+
if (isNaN(mode)) {
|
|
85
|
+
return {
|
|
86
|
+
valid: false,
|
|
87
|
+
error: `Mode at position ${i + 1} is not a number: "${parts[i]}"`,
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (!validValues[i].includes(mode)) {
|
|
92
|
+
return {
|
|
93
|
+
valid: false,
|
|
94
|
+
error: `Mode at position ${i + 1} must be ${validValues[i].join(' or ')}, got ${mode}`,
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
parsedModes.push(mode)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return { valid: true, modes: parsedModes }
|
|
102
|
+
}
|
|
72
103
|
|
|
73
104
|
/**
|
|
74
105
|
* Progress tracking utility for encoding/decoding operations
|
|
@@ -82,7 +113,7 @@ function validateTitle(title) {
|
|
|
82
113
|
*/
|
|
83
114
|
class ProgressTracker {
|
|
84
115
|
/**
|
|
85
|
-
* Create a progress tracker
|
|
116
|
+
* Create a progress tracker.
|
|
86
117
|
*
|
|
87
118
|
* @param {number} frameCount - Total number of frames to process
|
|
88
119
|
* @param {string} operation - Operation name ('Encoding' or 'Decoding')
|
|
@@ -90,53 +121,77 @@ class ProgressTracker {
|
|
|
90
121
|
*/
|
|
91
122
|
constructor(frameCount, operation, quiet = false) {
|
|
92
123
|
this.totalFrames = frameCount
|
|
93
|
-
this.
|
|
124
|
+
this.operation = operation
|
|
125
|
+
this.enabled = !quiet && process.stderr.isTTY
|
|
94
126
|
this.startTime = performance.now()
|
|
127
|
+
this.lastRender = -Infinity
|
|
95
128
|
this.frameCount = 0
|
|
96
|
-
|
|
97
|
-
if (!quiet) {
|
|
98
|
-
this.bar = new cliProgress.SingleBar(
|
|
99
|
-
{
|
|
100
|
-
autopadding: true,
|
|
101
|
-
format: `${operation} |{bar}| {percentage}% | {value}/{total} frames | {elapsed}/{remaining} | RT: {speed}x`,
|
|
102
|
-
},
|
|
103
|
-
cliProgress.Presets.rect
|
|
104
|
-
)
|
|
105
|
-
this.bar.start(frameCount, 0)
|
|
106
|
-
}
|
|
129
|
+
this.render()
|
|
107
130
|
}
|
|
108
131
|
|
|
109
132
|
/**
|
|
110
|
-
* Update progress with a new processed frame
|
|
133
|
+
* Update progress with a new processed frame.
|
|
111
134
|
*
|
|
112
135
|
* @param {number} sampleRate - Audio sample rate for RT speed calculation
|
|
113
136
|
*/
|
|
114
137
|
update(sampleRate) {
|
|
115
138
|
this.frameCount++
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const audioProcessed = (this.frameCount * SAMPLES_PER_FRAME) / sampleRate
|
|
119
|
-
const rtSpeed = elapsed > 0 ? audioProcessed / elapsed : 0
|
|
120
|
-
const progress = this.frameCount / this.totalFrames
|
|
121
|
-
const estimatedTotal = progress > 0 ? elapsed / progress : 0
|
|
122
|
-
const remaining = Math.max(0, estimatedTotal - elapsed)
|
|
123
|
-
|
|
124
|
-
this.bar.update(this.frameCount, {
|
|
125
|
-
speed: rtSpeed.toFixed(1),
|
|
126
|
-
elapsed: formatTime(elapsed),
|
|
127
|
-
remaining: formatTime(remaining),
|
|
128
|
-
})
|
|
129
|
-
}
|
|
139
|
+
this.sampleRate = sampleRate
|
|
140
|
+
this.render()
|
|
130
141
|
}
|
|
131
142
|
|
|
132
143
|
/**
|
|
133
|
-
*
|
|
144
|
+
* Render a throttled progress update on an interactive terminal.
|
|
145
|
+
*
|
|
146
|
+
* @param {boolean} [force=false] - Render even inside the throttle interval
|
|
134
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. */
|
|
135
170
|
stop() {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
171
|
+
this.render(true)
|
|
172
|
+
if (this.enabled) process.stderr.write('\n')
|
|
173
|
+
}
|
|
174
|
+
}
|
|
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
|
|
139
192
|
}
|
|
193
|
+
if (bitDepth === 32) return buffer.readInt32LE(offset) / 2147483648.0
|
|
194
|
+
return 0
|
|
140
195
|
}
|
|
141
196
|
|
|
142
197
|
/**
|
|
@@ -175,140 +230,224 @@ class WavReader {
|
|
|
175
230
|
* @throws {Error} If file cannot be read or has invalid format
|
|
176
231
|
*/
|
|
177
232
|
async loadMetadata() {
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
)
|
|
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
|
|
203
265
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
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
|
+
}
|
|
211
287
|
}
|
|
212
288
|
|
|
213
289
|
/**
|
|
214
|
-
* Async iterator for streaming WAV file frames
|
|
290
|
+
* Async iterator for streaming WAV file frames.
|
|
215
291
|
*
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
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.
|
|
295
|
+
*
|
|
296
|
+
* @param {i32} [frameSize=SAMPLES_PER_FRAME] - Samples per frame
|
|
297
|
+
* @yields {Float32Array|Array<Float32Array>} Mono samples or stereo channels
|
|
220
298
|
*/
|
|
221
299
|
async *[Symbol.asyncIterator](frameSize = SAMPLES_PER_FRAME) {
|
|
222
|
-
const
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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
|
+
)
|
|
327
|
+
}
|
|
236
328
|
}
|
|
237
|
-
}
|
|
329
|
+
} finally {
|
|
330
|
+
await handle.close()
|
|
331
|
+
}
|
|
332
|
+
}
|
|
238
333
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
334
|
+
/**
|
|
335
|
+
* Process raw PCM buffer into float32 frame data
|
|
336
|
+
*
|
|
337
|
+
* @private
|
|
338
|
+
* @param {Buffer} frameBuffer - Raw PCM data
|
|
339
|
+
* @param {i32} frameSize - Number of samples per channel
|
|
340
|
+
* @returns {Float32Array|Array<Float32Array>} Processed frame data
|
|
341
|
+
*/
|
|
342
|
+
_processFrameBuffer(frameBuffer, frameSize) {
|
|
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
|
|
244
355
|
}
|
|
245
|
-
|
|
356
|
+
if (channels === 1) return left
|
|
246
357
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
resolveDataPromise()
|
|
251
|
-
resolveDataPromise = null
|
|
358
|
+
const right = new Float32Array(frameSize)
|
|
359
|
+
for (let i = 0; i < frameSize; i++) {
|
|
360
|
+
right[i] = samples[i * 2 + 1] / 32768.0
|
|
252
361
|
}
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
pcmQueue = []
|
|
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
|
|
265
373
|
}
|
|
374
|
+
if (channels === 1) return left
|
|
266
375
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
yield this._processFrameBuffer(frameBuffer, frameSize)
|
|
376
|
+
const right = new Float32Array(frameSize)
|
|
377
|
+
for (let i = 0; i < frameSize; i++) {
|
|
378
|
+
right[i] = samples[i * 2 + 1] / 2147483648.0
|
|
271
379
|
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
])
|
|
279
|
-
yield this._processFrameBuffer(paddedFrame, frameSize)
|
|
280
|
-
}
|
|
281
|
-
break
|
|
380
|
+
return [left, right]
|
|
381
|
+
}
|
|
382
|
+
if (channels === 1) {
|
|
383
|
+
const frame = new Float32Array(frameSize)
|
|
384
|
+
for (let i = 0; i < frameSize; i++) {
|
|
385
|
+
frame[i] = readPcmSample(frameBuffer, i * bytesPerSample, bitDepth)
|
|
282
386
|
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
})
|
|
387
|
+
return frame
|
|
388
|
+
} else {
|
|
389
|
+
const left = new Float32Array(frameSize)
|
|
390
|
+
const right = new Float32Array(frameSize)
|
|
391
|
+
for (let i = 0; i < frameSize; i++) {
|
|
392
|
+
const offset = i * channels * bytesPerSample
|
|
393
|
+
left[i] = readPcmSample(frameBuffer, offset, bitDepth)
|
|
394
|
+
right[i] = readPcmSample(frameBuffer, offset + bytesPerSample, bitDepth)
|
|
292
395
|
}
|
|
396
|
+
return [left, right]
|
|
293
397
|
}
|
|
294
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
|
+
}
|
|
295
431
|
|
|
296
432
|
/**
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
* @private
|
|
300
|
-
* @param {Buffer} frameBuffer - Raw PCM data
|
|
301
|
-
* @param {number} frameSize - Number of samples per channel
|
|
302
|
-
* @returns {Float32Array|Array<Float32Array>} Processed frame data
|
|
433
|
+
* @param {Uint8Array} bytes - Next frame's bytes
|
|
434
|
+
* @returns {Promise<void>}
|
|
303
435
|
*/
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
this.
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
)
|
|
311
|
-
|
|
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
|
|
441
|
+
}
|
|
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
|
|
312
451
|
}
|
|
313
452
|
}
|
|
314
453
|
|
|
@@ -388,14 +527,34 @@ async function encodeFile(inputFile, outputFile, options) {
|
|
|
388
527
|
})
|
|
389
528
|
|
|
390
529
|
const title = options.title || path.basename(outputFile, '.aea')
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
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
|
+
}
|
|
399
558
|
} finally {
|
|
400
559
|
progress.stop()
|
|
401
560
|
}
|
|
@@ -447,96 +606,208 @@ async function decodeFile(inputFile, outputFile, options) {
|
|
|
447
606
|
onProgress,
|
|
448
607
|
})
|
|
449
608
|
|
|
450
|
-
const
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
metadata.channelCount,
|
|
454
|
-
SAMPLE_RATE
|
|
609
|
+
const output = await fs.promises.open(
|
|
610
|
+
outputFile,
|
|
611
|
+
options.force ? 'w' : 'wx'
|
|
455
612
|
)
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
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
|
+
}
|
|
459
640
|
} finally {
|
|
460
641
|
progress.stop()
|
|
461
642
|
}
|
|
462
643
|
}
|
|
463
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
|
+
|
|
464
700
|
/**
|
|
465
|
-
*
|
|
701
|
+
* Report invalid command-line syntax without an internal stack trace.
|
|
466
702
|
*
|
|
467
|
-
*
|
|
468
|
-
*
|
|
469
|
-
|
|
703
|
+
* @param {string} message - Argument error to display.
|
|
704
|
+
* @returns {never}
|
|
705
|
+
*/
|
|
706
|
+
function argumentError(message) {
|
|
707
|
+
console.error(`error: ${message}`)
|
|
708
|
+
process.exit(1)
|
|
709
|
+
}
|
|
710
|
+
|
|
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.
|
|
470
714
|
*
|
|
471
|
-
* @param {string}
|
|
472
|
-
* @param {string}
|
|
473
|
-
* @
|
|
474
|
-
* @param {boolean} options.quiet - Suppress progress output
|
|
475
|
-
* @returns {Promise<void>} Resolves when dump is complete
|
|
476
|
-
* @throws {Error} If input file is invalid or cannot be read
|
|
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.
|
|
477
718
|
*/
|
|
478
|
-
|
|
479
|
-
const
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
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
|
+
}
|
|
735
|
+
|
|
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
|
+
}
|
|
755
|
+
|
|
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
|
+
}
|
|
767
|
+
}
|
|
768
|
+
offset = argument.length
|
|
769
|
+
}
|
|
770
|
+
|
|
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)
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
if (unknownOption) argumentError(`unknown option '${unknownOption}'`)
|
|
784
|
+
if (paths.length < 2) {
|
|
785
|
+
argumentError(
|
|
786
|
+
`missing required argument '${paths.length ? 'output' : 'input'}'`
|
|
488
787
|
)
|
|
489
|
-
await fs.promises.writeFile(outputFile, JSON.stringify(dump, null, 2))
|
|
490
|
-
} finally {
|
|
491
|
-
progress.stop()
|
|
492
788
|
}
|
|
789
|
+
return { options, paths }
|
|
493
790
|
}
|
|
494
791
|
|
|
495
792
|
/**
|
|
496
793
|
* Main CLI entry point
|
|
497
794
|
*
|
|
498
|
-
* Parses command line arguments and executes encoding
|
|
499
|
-
*
|
|
795
|
+
* Parses command line arguments and executes encoding or decoding
|
|
796
|
+
* with error handling and validation.
|
|
500
797
|
*
|
|
501
798
|
* @returns {Promise<void>} Resolves when operation is complete
|
|
502
799
|
*/
|
|
503
800
|
async function main() {
|
|
504
801
|
const { version } = JSON.parse(
|
|
505
|
-
fs.readFileSync(new URL('../package.json', import.meta.url))
|
|
802
|
+
fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')
|
|
506
803
|
)
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
.description('ATRAC1 Audio Codec')
|
|
510
|
-
.version(version)
|
|
511
|
-
.option('-e, --encode', 'Encode WAV to AEA')
|
|
512
|
-
.option('-d, --decode', 'Decode AEA to WAV')
|
|
513
|
-
.option('-j, --json', 'Dump AEA file structure to JSON')
|
|
514
|
-
.option('-q, --quiet', 'Suppress all output except errors')
|
|
515
|
-
.option('-f, --force', 'Overwrite output file if it exists')
|
|
516
|
-
.option(
|
|
517
|
-
'-t, --title <title>',
|
|
518
|
-
'Custom UTF-8 title for AEA file metadata (encoding only)'
|
|
519
|
-
)
|
|
520
|
-
.option(
|
|
521
|
-
'-b, --bias <value>',
|
|
522
|
-
'Bit allocation bias (default: 1.0)',
|
|
523
|
-
parseFloat
|
|
524
|
-
)
|
|
525
|
-
.option(
|
|
526
|
-
'-m, --modes <modes>',
|
|
527
|
-
'Fixed block modes [0/2],[0/2],[0/3] for low,mid,high bands (skips transient detection)'
|
|
528
|
-
)
|
|
529
|
-
.argument('<input>', 'Input file path')
|
|
530
|
-
.argument('<output>', 'Output file path')
|
|
531
|
-
.parse()
|
|
532
|
-
|
|
533
|
-
const options = program.opts()
|
|
534
|
-
const [inputFile, outputFile] = program.args
|
|
804
|
+
const { options, paths } = parseArguments(process.argv.slice(2), version)
|
|
805
|
+
const [inputFile, outputFile] = paths
|
|
535
806
|
|
|
536
807
|
// Validate operation mode
|
|
537
|
-
const modes = [options.encode, options.decode
|
|
808
|
+
const modes = [options.encode, options.decode].filter(Boolean)
|
|
538
809
|
if (modes.length === 0) {
|
|
539
|
-
console.error('Error: Must specify
|
|
810
|
+
console.error('Error: Must specify --encode or --decode')
|
|
540
811
|
process.exit(1)
|
|
541
812
|
}
|
|
542
813
|
if (modes.length > 1) {
|
|
@@ -556,8 +827,6 @@ async function main() {
|
|
|
556
827
|
await encodeFile(inputFile, outputFile, options)
|
|
557
828
|
} else if (options.decode) {
|
|
558
829
|
await decodeFile(inputFile, outputFile, options)
|
|
559
|
-
} else if (options.json) {
|
|
560
|
-
await dumpFile(inputFile, outputFile, options)
|
|
561
830
|
}
|
|
562
831
|
} catch (error) {
|
|
563
832
|
if (error.code === 'ENOENT') {
|
|
@@ -572,10 +841,10 @@ async function main() {
|
|
|
572
841
|
}
|
|
573
842
|
}
|
|
574
843
|
|
|
575
|
-
|
|
844
|
+
try {
|
|
845
|
+
await main()
|
|
846
|
+
} catch (error) {
|
|
576
847
|
console.error(`An unhandled error occurred: ${error.message}`)
|
|
577
848
|
console.error(error.stack)
|
|
578
849
|
process.exit(1)
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
export { validateModes }
|
|
850
|
+
}
|