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.
@@ -65,10 +65,10 @@ function buildBiasedScaleFactorTable(bias) {
65
65
  /**
66
66
  * Evaluate one legal active-BFU count.
67
67
  *
68
- * @param {number} activeBfuCount
69
- * @param {number} maxBfuCount
70
- * @param {Int32Array} bfuSizes
71
- * @param {number} remainingBits
68
+ * @param {i32} activeBfuCount
69
+ * @param {i32} maxBfuCount
70
+ * @param {Array<number>} bfuSizes
71
+ * @param {i32} remainingBits
72
72
  * @param {Float64Array} biasedScaleFactors
73
73
  * @param {Int32Array} allScaleFactorIndices
74
74
  * @param {Float32Array} zeroBitDistortions
@@ -106,14 +106,15 @@ function search(
106
106
  * Calculates the total distortion for a given allocation.
107
107
  * This includes quantization distortion for coded bands and truncation
108
108
  * distortion for uncoded bands.
109
- * @param {number} activeBfuCount
110
- * @param {number} maxBfuCount
111
- * @param {Int32Array} bfuSizes
109
+ * @param {i32} activeBfuCount
110
+ * @param {i32} maxBfuCount
111
+ * @param {Array<number>} bfuSizes
112
112
  * @param {Int32Array} wordLengths
113
113
  * @param {Int32Array} scaleFactorIndices
114
- * @param {number} biasedScaleFactors
114
+ * @param {Float64Array} biasedScaleFactors
115
115
  * @param {Float32Array} zeroBitDistortions
116
116
  * @returns {number}
117
+ * @nativeUnchecked Native callers supply frame-bounded buffers and indices.
117
118
  */
118
119
  function measureDistortion(
119
120
  activeBfuCount,
@@ -154,12 +155,13 @@ function measureDistortion(
154
155
  * Distributes available bits across Band Frequency Units (BFUs) using Rate-Distortion Optimization.
155
156
  * (Modified to accept pre-calculated scale factors)
156
157
  *
157
- * @param {number} activeBfuCount
158
- * @param {Int32Array} bfuSizes
159
- * @param {number} remainingBits
158
+ * @param {i32} activeBfuCount
159
+ * @param {Array<number>} bfuSizes
160
+ * @param {i32} remainingBits
160
161
  * @param {Float64Array} biasedScaleFactors
161
162
  * @param {Int32Array} allScaleFactorIndices
162
163
  * @returns {object} Retained allocation decisions.
164
+ * @nativeUnchecked Native callers supply frame-bounded buffers and indices.
163
165
  */
164
166
  function distributeBits(
165
167
  activeBfuCount,
@@ -251,8 +253,9 @@ function distributeBits(
251
253
  *
252
254
  * @param {Int32Array} heapIndices
253
255
  * @param {Float32Array} heapPriorities
254
- * @param {number} startIndex
255
- * @param {number} heapSize
256
+ * @param {i32} startIndex
257
+ * @param {i32} heapSize
258
+ * @nativeUnchecked Native callers supply frame-bounded buffers and indices.
256
259
  */
257
260
  function siftDown(heapIndices, heapPriorities, startIndex, heapSize) {
258
261
  let i = startIndex
@@ -289,8 +292,8 @@ function siftDown(heapIndices, heapPriorities, startIndex, heapSize) {
289
292
  * minimizes the total perceptual distortion.
290
293
  *
291
294
  * @param {Array<Float32Array>} bfuData
292
- * @param {Int32Array} bfuSizes
293
- * @param {number} maxBfuCount
295
+ * @param {Array<number>} bfuSizes
296
+ * @param {i32} maxBfuCount
294
297
  * @param {number} allocationBias
295
298
  * @returns {{bfuCount:number, allocation:Int32Array, scaleFactorIndices:Int32Array}}
296
299
  */
@@ -360,7 +363,7 @@ export function solve(bfuData, bfuSizes, maxBfuCount, allocationBias) {
360
363
  * Find the optimal scale factor index for a set of coefficients.
361
364
  * Same semantics as the original.
362
365
  * @param {Float32Array} coefficients
363
- * @param {number} length
366
+ * @param {i32} length
364
367
  * @returns {number}
365
368
  */
366
369
  export function findScaleFactor(coefficients, length) {
@@ -44,6 +44,9 @@ function calculateSpectralFeatures(currentCoeffs, prevCoeffs) {
44
44
  /**
45
45
  * Calculate normalized spectral flux (positive spectral differences)
46
46
  * High values indicate sudden onset of new spectral components
47
+ * @param {Float32Array} currentCoeffs - Current frame coefficients
48
+ * @param {Float32Array} prevCoeffs - Previous frame coefficients
49
+ * @returns {number} Spectral flux normalized by current frame energy
47
50
  */
48
51
  function calculateSpectralFlux(currentCoeffs, prevCoeffs) {
49
52
  let flux = 0
@@ -184,7 +187,7 @@ function calculateTransientScore(features) {
184
187
  /**
185
188
  * Perform FFT on time-domain samples and return magnitude spectrum
186
189
  * @param {Float32Array} samples - Time-domain samples
187
- * @param {number} fftSize - FFT size (must be power of 2)
190
+ * @param {i32} fftSize - FFT size (must be power of 2)
188
191
  * @returns {Float32Array} Magnitude spectrum (positive frequencies only)
189
192
  */
190
193
  export function performFFT(samples, fftSize) {
@@ -35,8 +35,8 @@ export function transformSpectrum(context) {
35
35
 
36
36
  /**
37
37
  * @param {Float32Array} samples
38
- * @param {number} bandIndex
39
- * @param {number} blockMode
38
+ * @param {i32} bandIndex
39
+ * @param {i32} blockMode
40
40
  * @param {Float32Array} overlapBuffer
41
41
  * @returns {Float32Array}
42
42
  */
@@ -58,7 +58,7 @@ export function transformSpectrum(context) {
58
58
 
59
59
  /**
60
60
  * @param {Float32Array} samples
61
- * @param {number} bandIndex
61
+ * @param {i32} bandIndex
62
62
  * @param {Object} config
63
63
  * @param {Object} transformFunction
64
64
  * @param {Float32Array} overlapBuffer
@@ -91,7 +91,7 @@ export function transformSpectrum(context) {
91
91
 
92
92
  /**
93
93
  * @param {Float32Array} samples
94
- * @param {number} bandIndex
94
+ * @param {i32} bandIndex
95
95
  * @param {Object} config
96
96
  * @param {Float32Array} overlapBuffer
97
97
  * @returns {Float32Array}
@@ -126,7 +126,7 @@ export function transformSpectrum(context) {
126
126
  /**
127
127
  * @param {Float32Array} samples
128
128
  * @param {Float32Array} overlapBuffer
129
- * @param {number} blockSize
129
+ * @param {i32} blockSize
130
130
  */
131
131
  function applyTailWindowing(samples, overlapBuffer, blockSize) {
132
132
  const tailStart = blockSize - MDCT_OVERLAP_SIZE
@@ -46,7 +46,7 @@ export class AeaFile {
46
46
  *
47
47
  * @param {string} [title='']
48
48
  * @param {number} [frameCount=0]
49
- * @param {number} [channelCount=1]
49
+ * @param {i32} [channelCount=1]
50
50
  * @param {number} [sampleCount=0]
51
51
  * @param {number} [primingSampleCount=STREAM_PRIMING_SAMPLES]
52
52
  * @returns {Uint8Array}
@@ -17,7 +17,7 @@ import {
17
17
  * Write a four-character code.
18
18
  *
19
19
  * @param {DataView} output
20
- * @param {number} offset
20
+ * @param {i32} offset
21
21
  * @param {string} value
22
22
  */
23
23
  function writeFourCc(output, offset, value) {
@@ -26,92 +26,6 @@ function writeFourCc(output, offset, value) {
26
26
  }
27
27
  }
28
28
 
29
- /** Convert interleaved signed little-endian PCM into normalized channels. */
30
- export function pcmBytesToChannels(bytes, bitDepth, channelCount, sampleCount) {
31
- if (![16, 24, 32].includes(bitDepth)) {
32
- throw new RangeError(`Unsupported PCM bit depth: ${bitDepth}`)
33
- }
34
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
35
- const channels = Array.from(
36
- { length: channelCount },
37
- () => new Float32Array(sampleCount)
38
- )
39
- let offset = 0
40
- for (let sample = 0; sample < sampleCount; sample++) {
41
- for (const channel of channels) {
42
- let value
43
- if (bitDepth === 16) value = view.getInt16(offset, true) / 32768
44
- else if (bitDepth === 32) value = view.getInt32(offset, true) / 2147483648
45
- else {
46
- let integer =
47
- bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16)
48
- if (integer > 0x7fffff) integer -= 0x1000000
49
- value = integer / 8388608
50
- }
51
- channel[sample] = value
52
- offset += bitDepth / 8
53
- }
54
- }
55
- return channels
56
- }
57
-
58
- /** Read a RIFF/WAVE byte image. Native file I/O stays outside this boundary. */
59
- export function parsePcmWave(bytes) {
60
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
61
- const fourCc = (offset) =>
62
- String.fromCharCode(...bytes.subarray(offset, offset + 4))
63
- if (bytes.length < 12 || fourCc(0) !== 'RIFF' || fourCc(8) !== 'WAVE') {
64
- throw new Error('Invalid RIFF/WAVE file')
65
- }
66
- const end = view.getUint32(4, true) + 8
67
- if (end > bytes.length || end < 12)
68
- throw new Error('Truncated RIFF/WAVE file')
69
- let format = null
70
- let data = null
71
- for (let offset = 12; offset + 8 <= end;) {
72
- const size = view.getUint32(offset + 4, true)
73
- const start = offset + 8
74
- if (start + size > end) throw new Error('Truncated WAVE chunk')
75
- if (fourCc(offset) === 'fmt ') {
76
- if (size < 16) throw new Error('Invalid WAVE format chunk')
77
- format = {
78
- code: view.getUint16(start, true),
79
- channelCount: view.getUint16(start + 2, true),
80
- sampleRate: view.getUint32(start + 4, true),
81
- blockAlign: view.getUint16(start + 12, true),
82
- bitDepth: view.getUint16(start + 14, true),
83
- }
84
- } else if (fourCc(offset) === 'data' && data === null)
85
- data = bytes.subarray(start, start + size)
86
- offset = start + size + (size & 1)
87
- }
88
- if (!format || data === null)
89
- throw new Error('WAVE requires fmt and data chunks')
90
- const { code, channelCount, sampleRate, blockAlign, bitDepth } = format
91
- if (code !== 1 || ![16, 24, 32].includes(bitDepth)) {
92
- throw new Error('WAVE input must be signed 16, 24, or 32-bit integer PCM')
93
- }
94
- if (channelCount !== 1 && channelCount !== 2)
95
- throw new Error(`Unsupported channel count: ${channelCount}`)
96
- if (
97
- sampleRate < 1 ||
98
- blockAlign !== (channelCount * bitDepth) / 8 ||
99
- data.length % blockAlign !== 0
100
- ) {
101
- throw new Error('Invalid WAVE sample layout')
102
- }
103
- return {
104
- channels: pcmBytesToChannels(
105
- data,
106
- bitDepth,
107
- channelCount,
108
- data.length / blockAlign
109
- ),
110
- sampleRate,
111
- bitDepth,
112
- }
113
- }
114
-
115
29
  /**
116
30
  * Join complete PCM frames into one channel.
117
31
  *
@@ -134,7 +48,7 @@ export function joinChannelFrames(frames) {
134
48
  * Split planar PCM buffers into complete zero-padded codec frames.
135
49
  *
136
50
  * @param {Float32Array[]} buffers
137
- * @param {number} [frameSize=SAMPLES_PER_FRAME]
51
+ * @param {i32} [frameSize=SAMPLES_PER_FRAME]
138
52
  * @returns {Generator<Float32Array>|Generator<[Float32Array, Float32Array]>}
139
53
  * @throws {Error} If the channel count is unsupported
140
54
  */
@@ -65,7 +65,7 @@ export class AudioProcessor {
65
65
 
66
66
  /**
67
67
  * @param {Float32Array[]} buffers
68
- * @param {number} [frameSize]
68
+ * @param {i32} [frameSize]
69
69
  * @returns {Generator<Float32Array>|Generator<[Float32Array, Float32Array]>}
70
70
  */
71
71
  static *frameBufferToFrames(buffers, frameSize) {
@@ -144,7 +144,7 @@ export class AudioProcessor {
144
144
 
145
145
  /**
146
146
  * @param {Float32Array[]|[Float32Array, Float32Array][]} pcmFrames
147
- * @param {number} [channelCount=1]
147
+ * @param {i32} [channelCount=1]
148
148
  * @param {number} [sampleRate=SAMPLE_RATE]
149
149
  * @returns {Blob}
150
150
  */
@@ -173,7 +173,7 @@ export class AudioProcessor {
173
173
  * Preserve the supported WAVE facade name.
174
174
  *
175
175
  * @param {Float32Array[]|[Float32Array, Float32Array][]} pcmFrames
176
- * @param {number} [channelCount=1]
176
+ * @param {i32} [channelCount=1]
177
177
  * @param {number} [sampleRate=SAMPLE_RATE]
178
178
  * @returns {Blob}
179
179
  */
@@ -185,7 +185,7 @@ export class AudioProcessor {
185
185
  * Assemble PCM frames using the supported interleaved result shape.
186
186
  *
187
187
  * @param {Float32Array[]|[Float32Array, Float32Array][]} pcmFrames
188
- * @param {number} channelCount
188
+ * @param {i32} channelCount
189
189
  * @returns {Float32Array}
190
190
  */
191
191
  static assemblePcmFrames(pcmFrames, channelCount) {
@@ -48,8 +48,8 @@ export class AeaReader {
48
48
  for await (const chunk of stream) {
49
49
  buffer = Buffer.concat([buffer, chunk])
50
50
  while (buffer.length >= SOUND_UNIT_SIZE) {
51
- const frameData = buffer.slice(0, SOUND_UNIT_SIZE)
52
- buffer = buffer.slice(SOUND_UNIT_SIZE)
51
+ const frameData = buffer.subarray(0, SOUND_UNIT_SIZE)
52
+ buffer = buffer.subarray(SOUND_UNIT_SIZE)
53
53
  yield deserializeFrame(frameData)
54
54
  }
55
55
  }
@@ -19,7 +19,7 @@ import { frameBufferToFrames, joinChannelFrames } from './pcm.js'
19
19
  /**
20
20
  * Validate a supported channel mode.
21
21
  *
22
- * @param {number} channelCount
22
+ * @param {i32} channelCount
23
23
  * @throws {Error} If the channel count is unsupported
24
24
  */
25
25
  function validateChannels(channelCount) {
@@ -32,7 +32,7 @@ function validateChannels(channelCount) {
32
32
  * Validate one PCM frame in the selected channel mode.
33
33
  *
34
34
  * @param {object} frame
35
- * @param {number} channelCount
35
+ * @param {i32} channelCount
36
36
  * @throws {TypeError} If the frame does not match the selected mode
37
37
  * @throws {RangeError} If a selected channel is not one complete frame
38
38
  */
@@ -72,6 +72,20 @@ function createDummyFrame() {
72
72
  }
73
73
  }
74
74
 
75
+ /**
76
+ * Collect an async iterable.
77
+ *
78
+ * @param {AsyncIterable} frames
79
+ * @returns {Promise<Array>}
80
+ */
81
+ async function collect(frames) {
82
+ const output = []
83
+ for await (const frame of frames) {
84
+ output.push(frame)
85
+ }
86
+ return output
87
+ }
88
+
75
89
  /**
76
90
  * Encode chronological PCM frames.
77
91
  */
@@ -101,21 +115,22 @@ export class AeaStreamingEncoder {
101
115
  if (this.finalized) {
102
116
  throw new Error('ATRAC1 encoder has already been finalized')
103
117
  }
104
- for await (const frame of frames) yield* this.push(frame)
105
- }
118
+ for await (const frame of frames) {
119
+ validateChunk(frame, this.channelCount)
120
+ if (this.channelCount === 1) {
121
+ yield this.leftEncoder(frame)
122
+ } else {
123
+ const [left, right] = frame
124
+ yield this.leftEncoder(left)
125
+ yield this.rightEncoder(right)
126
+ }
106
127
 
107
- /** Encode one chronological frame for either an async or synchronous host. */
108
- push(frame) {
109
- if (this.finalized)
110
- throw new Error('ATRAC1 encoder has already been finalized')
111
- validateChunk(frame, this.channelCount)
112
- const encoded =
113
- this.channelCount === 1
114
- ? [this.leftEncoder(frame)]
115
- : [this.leftEncoder(frame[0]), this.rightEncoder(frame[1])]
116
- this.sampleCount += SAMPLES_PER_FRAME
117
- if (this.onProgress) this.onProgress(this.frameIndex++)
118
- return encoded
128
+ this.sampleCount += SAMPLES_PER_FRAME
129
+
130
+ if (this.onProgress) {
131
+ this.onProgress(this.frameIndex++)
132
+ }
133
+ }
119
134
  }
120
135
 
121
136
  /**
@@ -169,29 +184,22 @@ export class AeaStreamingDecoder {
169
184
  */
170
185
  async *frames(frames) {
171
186
  for await (const frame of frames) {
172
- const decoded = this.push(frame)
173
- if (decoded !== null) yield decoded
187
+ if (this.channelCount === 1) {
188
+ yield this.trim(this.leftDecoder(frame))
189
+ this.reportProgress()
190
+ } else if (this.leftFrame === null) {
191
+ this.leftFrame = frame
192
+ } else {
193
+ yield this.trim([
194
+ this.leftDecoder(this.leftFrame),
195
+ this.rightDecoder(frame),
196
+ ])
197
+ this.leftFrame = null
198
+ this.reportProgress()
199
+ }
174
200
  }
175
201
  }
176
202
 
177
- /** Decode one sound unit, returning null until a stereo pair is complete. */
178
- push(frame) {
179
- let decoded
180
- if (this.channelCount === 1) decoded = this.trim(this.leftDecoder(frame))
181
- else if (this.leftFrame === null) {
182
- this.leftFrame = frame
183
- return null
184
- } else {
185
- decoded = this.trim([
186
- this.leftDecoder(this.leftFrame),
187
- this.rightDecoder(frame),
188
- ])
189
- this.leftFrame = null
190
- }
191
- this.reportProgress()
192
- return decoded
193
- }
194
-
195
203
  /**
196
204
  * Complete an unmatched stereo pair.
197
205
  *
@@ -286,9 +294,8 @@ export async function encodeAeaPcm(channels, options = {}) {
286
294
  channelCount: channels.length,
287
295
  encoderOptions: new EncoderOptions(encoderValues),
288
296
  })
289
- const encoded = []
290
- for (const frame of frameBufferToFrames(channels))
291
- encoded.push(...encoder.push(frame))
297
+ const frames = encoder.frames(frameBufferToFrames(channels))
298
+ const encoded = await collect(frames)
292
299
  encoded.push(...encoder.finish())
293
300
 
294
301
  const header = AeaFile.createHeader(
@@ -332,17 +339,16 @@ export async function decodeAeaPcm(input) {
332
339
  primingSampleCount: info.primingSampleCount,
333
340
  sampleCount: info.sampleCount,
334
341
  })
335
- const decoded = []
336
- for (
337
- let offset = AEA_HEADER_SIZE;
338
- offset + SOUND_UNIT_SIZE <= bytes.length;
339
- offset += SOUND_UNIT_SIZE
340
- ) {
341
- const frame = decoder.push(
342
- deserializeFrame(bytes.subarray(offset, offset + SOUND_UNIT_SIZE))
343
- )
344
- if (frame !== null) decoded.push(frame)
345
- }
342
+ const frames = (async function* () {
343
+ for (
344
+ let offset = AEA_HEADER_SIZE;
345
+ offset + SOUND_UNIT_SIZE <= bytes.length;
346
+ offset += SOUND_UNIT_SIZE
347
+ ) {
348
+ yield deserializeFrame(bytes.subarray(offset, offset + SOUND_UNIT_SIZE))
349
+ }
350
+ })()
351
+ const decoded = await collect(decoder.frames(frames))
346
352
  decoded.push(...decoder.finish())
347
353
 
348
354
  if (info.channelCount === 1) {
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Calculate a band's offset in the 512-coefficient spectrum.
7
7
  *
8
- * @param {number} bandIndex
8
+ * @param {i32} bandIndex
9
9
  * @returns {number}
10
10
  */
11
11
  export function calculateBandOffset(bandIndex) {
@@ -16,7 +16,7 @@ export function calculateBandOffset(bandIndex) {
16
16
  * Extract one band from the full coefficient spectrum.
17
17
  *
18
18
  * @param {Float32Array} coefficients
19
- * @param {number} bandIndex
19
+ * @param {i32} bandIndex
20
20
  * @returns {Float32Array}
21
21
  */
22
22
  export function extractBandCoefficients(coefficients, bandIndex) {
@@ -16,8 +16,8 @@ import { SCALE_FACTORS } from '../core/tables.js'
16
16
  /**
17
17
  * Quantize coefficients.
18
18
  * @param {Float32Array} coefficients
19
- * @param {number} scaleFactorIndex
20
- * @param {number} bitsPerSample
19
+ * @param {i32} scaleFactorIndex
20
+ * @param {i32} bitsPerSample
21
21
  * @returns {Int32Array} out
22
22
  */
23
23
  export function quantize(coefficients, scaleFactorIndex, bitsPerSample) {
@@ -47,8 +47,8 @@ export function quantize(coefficients, scaleFactorIndex, bitsPerSample) {
47
47
  /**
48
48
  * Dequantize coefficients.
49
49
  * @param {Int32Array} quantized
50
- * @param {number} scaleFactorIndex
51
- * @param {number} bitsPerSample
50
+ * @param {i32} scaleFactorIndex
51
+ * @param {i32} bitsPerSample
52
52
  * @returns {Float32Array}
53
53
  */
54
54
  export function dequantize(quantized, scaleFactorIndex, bitsPerSample) {
@@ -6,6 +6,7 @@ export class FFT {
6
6
  *
7
7
  * @param {Float32Array} real Real input and output components.
8
8
  * @param {Float32Array} imaginary Imaginary input and output components.
9
+ * @nativeUnchecked Native callers supply frame-bounded buffers and indices.
9
10
  */
10
11
  static transform(real, imaginary) {
11
12
  const size = real.length