carta1 1.6.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/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 {Object} Validation result
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 {Object} Validation result
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.quiet = quiet
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
- if (!this.quiet) {
117
- const elapsed = (performance.now() - this.startTime) / 1000
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
- * Stop the progress bar display
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
- if (!this.quiet && this.bar) {
137
- this.bar.stop()
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 stream = fs.createReadStream(this.filePath)
179
- const reader = new wav.Reader()
180
- stream.pipe(reader)
181
-
182
- return new Promise((resolve, reject) => {
183
- reader.on('format', (format) => {
184
- this.channels = format.channels
185
- this.sampleRate = format.sampleRate
186
- this.bitDepth = format.bitDepth
187
-
188
- const fileStats = fs.statSync(this.filePath)
189
- const wavHeaderSize = 44
190
- const dataSize = fileStats.size - wavHeaderSize
191
- const bytesPerSample = this.bitDepth / 8
192
-
193
- if (this.channels > 0 && bytesPerSample > 0) {
194
- const totalChannelSamples = dataSize / bytesPerSample
195
- this.totalSamples = Math.floor(totalChannelSamples / this.channels)
196
- this.duration = this.totalSamples / this.sampleRate
197
- }
198
-
199
- if (this.sampleRate !== SAMPLE_RATE) {
200
- console.log(
201
- `Warning: Input sample rate ${this.sampleRate}Hz, expected ${SAMPLE_RATE}Hz`
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
- stream.destroy()
206
- resolve()
207
- })
208
- reader.on('error', reject)
209
- stream.on('error', reject)
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
- * @param {number} [frameSize=SAMPLES_PER_FRAME] - Samples per frame
217
- * @yields {Float32Array|Array<Float32Array>} Audio frame data
218
- * - Mono: Float32Array of samples
219
- * - Stereo: [left, right] Float32Arrays
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 fileStream = fs.createReadStream(this.filePath)
223
- const wavReader = new wav.Reader()
224
- fileStream.pipe(wavReader)
225
-
226
- let pcmQueue = []
227
- let streamEnded = false
228
- let streamError = null
229
- let resolveDataPromise = null
230
-
231
- wavReader.on('data', (chunk) => {
232
- pcmQueue.push(chunk)
233
- if (resolveDataPromise) {
234
- resolveDataPromise()
235
- resolveDataPromise = null
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
- wavReader.on('end', () => {
240
- streamEnded = true
241
- if (resolveDataPromise) {
242
- resolveDataPromise()
243
- resolveDataPromise = null
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
- wavReader.on('error', (err) => {
248
- streamError = err
249
- if (resolveDataPromise) {
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
- let buffer = Buffer.alloc(0)
256
- const bytesPerSample = this.bitDepth / 8
257
- const frameByteSize = frameSize * this.channels * bytesPerSample
258
-
259
- while (true) {
260
- if (streamError) throw streamError
261
-
262
- while (pcmQueue.length > 0) {
263
- buffer = Buffer.concat([buffer, ...pcmQueue])
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
- while (buffer.length >= frameByteSize) {
268
- const frameBuffer = buffer.slice(0, frameByteSize)
269
- buffer = buffer.slice(frameByteSize)
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
- if (streamEnded && pcmQueue.length === 0) {
274
- if (buffer.length > 0) {
275
- const paddedFrame = Buffer.concat([
276
- buffer,
277
- Buffer.alloc(frameByteSize - buffer.length),
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
- if (!streamEnded) {
285
- await new Promise((resolve) => {
286
- resolveDataPromise = resolve
287
- if (pcmQueue.length > 0 || streamEnded) {
288
- resolveDataPromise = null
289
- resolve()
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
- * Process raw PCM buffer into float32 frame data
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
- _processFrameBuffer(frameBuffer, frameSize) {
305
- const channels = pcmBytesToChannels(
306
- frameBuffer,
307
- this.bitDepth,
308
- this.channels,
309
- frameSize
310
- )
311
- return this.channels === 1 ? channels[0] : channels
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 blob = await AudioProcessor.createAeaBlob(encodedFrames, {
392
- title,
393
- channelCount: reader.channels,
394
- sampleCount: reader.totalSamples,
395
- })
396
-
397
- const buffer = await blob.arrayBuffer()
398
- await fs.promises.writeFile(outputFile, new Uint8Array(buffer))
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 pcmFrames = await AudioProcessor.collectFrames(decodedFrames)
451
- const wavBlob = AudioProcessor.createPcmWaveBlob(
452
- pcmFrames,
453
- metadata.channelCount,
454
- SAMPLE_RATE
609
+ const output = await fs.promises.open(
610
+ outputFile,
611
+ options.force ? 'w' : 'wx'
455
612
  )
456
-
457
- const buffer = await wavBlob.arrayBuffer()
458
- await fs.promises.writeFile(outputFile, new Uint8Array(buffer))
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
- * Dump AEA file structure to JSON format
701
+ * Report invalid command-line syntax without an internal stack trace.
466
702
  *
467
- * Extracts and exports all metadata and frame information from an AEA file
468
- * for inspection and analysis. Includes header info, frame structure,
469
- * and statistical analysis.
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} inputFile - Path to input AEA file
472
- * @param {string} outputFile - Path to output JSON file
473
- * @param {Object} options - CLI options
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
- async function dumpFile(inputFile, outputFile, options) {
479
- const bytes = await fs.promises.readFile(inputFile)
480
- if (!options.quiet) console.log(`${inputFile} (AEA) → ${outputFile} (JSON)`)
481
- const frameCount = Math.floor(
482
- (bytes.length - AEA_HEADER_SIZE) / SOUND_UNIT_SIZE
483
- )
484
- const progress = new ProgressTracker(frameCount, 'Analyzing', options.quiet)
485
- try {
486
- const dump = inspectAea(bytes, inputFile, () =>
487
- progress.update(SAMPLE_RATE)
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, decoding,
499
- * or dump operations with error handling and validation.
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
- program
508
- .name('carta1')
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, options.json].filter(Boolean)
808
+ const modes = [options.encode, options.decode].filter(Boolean)
538
809
  if (modes.length === 0) {
539
- console.error('Error: Must specify one of --encode, --decode, or --json')
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
- main().catch((error) => {
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
+ }