carta1 1.7.0 → 1.9.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.
@@ -1,391 +1,320 @@
1
1
  /**
2
- * Carta1 Audio Codec - Bit Allocation Module
2
+ * Carta1 Sound-Unit bit allocation solver.
3
3
  *
4
- * This module implements the bit allocation system for the Carta1 audio codec,
5
- * responsible for distributing available bits across frequency bands to minimize
6
- * perceptual distortion while maintaining the target bitrate.
7
- *
8
- * The module uses Rate-Distortion Optimization (RDO) by searching over a
9
- * predefined set of valid Band Frequency Unit (BFU) counts. For each count,
10
- * it performs a greedy bit distribution to find the best allocation. This
11
- * approach optimally trades off the cost of encoding more frequency bands
12
- * (metadata overhead) against the benefit of reducing truncation distortion.
13
- *
14
- * Key components:
15
- * - RDO search over valid BFU counts to select the optimal number of bands.
16
- * - Greedy bit allocation for a fixed BFU count using a max-heap.
17
- * - Exponential distortion modeling based on scale factors.
18
- * - Support for variable word lengths per BFU.
19
- *
20
- * The algorithm ensures that the codec dynamically adapts the encoded bandwidth
21
- * to best match the signal characteristics for the given bitrate.
4
+ * Derives simultaneous masking thresholds and outer/middle-ear sensitivity
5
+ * weights per BFU, waterfill-tunes word lengths to the Sound-Unit payload
6
+ * budget, refines allocations with Pareto perceptual exchanges and greedy slack
7
+ * fill, selects the active BFU ceiling per ATRAC1 legal counts, and tightens
8
+ * scale factors where peak outer-bin rounding lowers reconstruction MSE.
22
9
  */
23
10
 
24
11
  import {
25
- NUM_BFUS,
12
+ BFU_DISTORTION_CACHE_STRIDE,
13
+ BITS_PER_BFU_METADATA,
26
14
  FRAME_BITS,
27
15
  FRAME_OVERHEAD_BITS,
28
- BITS_PER_BFU_METADATA,
29
- MAX_WORD_LENGTH_INDEX,
30
16
  } from '../core/constants.js'
17
+ import { BFU_AMOUNTS } from '../core/tables.js'
18
+ import { SoundUnitAllocationScratch } from '../state/encoder.js'
19
+ import { buildPerceptualMask, buildPerceptualWeights } from './distortion.js'
31
20
  import {
32
- WORD_LENGTH_BITS,
33
- INV_POWER_OF_TWO,
34
- SCALE_FACTORS,
35
- BFU_AMOUNTS,
36
- WORD_LENGTH_DELTA_BITS,
37
- DISTORTION_DELTA_FACTORS,
38
- } from '../core/tables.js'
39
-
40
- const biasedScaleFactorCache = new Map()
21
+ exchangePerceptualBits,
22
+ fillSlackBits,
23
+ refineScaleFactors,
24
+ tuneToBudget,
25
+ } from './refine.js'
41
26
 
42
27
  /**
43
- * Builds and returns a cached table of biased scale factors.
44
- *
45
- * @param {number} bias
46
- * @returns {Float64Array}
28
+ * @typedef {object} SoundUnitAllocationSolverScratch
29
+ * @property {Float64Array} energies
30
+ * @property {Float64Array} maxAmplitudes
31
+ * @property {Int32Array} initialScaleFactorIndices
32
+ * @property {Float64Array} maskThresholds
33
+ * @property {Float64Array} perceptualWeights
34
+ * @property {Float64Array} seedThresholds
35
+ * @property {Float64Array} distortionCache
36
+ * @property {Int32Array} candidateWordLengths
37
+ * @property {Int32Array} selectedWordLengths
38
+ * @property {Int32Array} refinedScaleFactorIndices
47
39
  */
48
- function buildBiasedScaleFactorTable(bias) {
49
- if (biasedScaleFactorCache.has(bias)) {
50
- return biasedScaleFactorCache.get(bias)
51
- }
52
40
 
53
- const out = new Float64Array(64)
54
- if (bias === 1) {
55
- out.set(SCALE_FACTORS)
56
- } else {
57
- for (let i = 0; i < 64; i++) {
58
- out[i] = Math.pow(SCALE_FACTORS[i], bias)
59
- }
60
- }
61
- biasedScaleFactorCache.set(bias, out)
62
- return out
63
- }
41
+ /** @type {SoundUnitAllocationSolverScratch} */
42
+ const defaultScratch = new SoundUnitAllocationScratch()
64
43
 
65
44
  /**
66
- * Evaluate one legal active-BFU count.
45
+ * Solve word-length allocation for one legal BFU count ceiling.
67
46
  *
68
- * @param {i32} activeBfuCount
69
- * @param {i32} maxBfuCount
47
+ * @param {i32} candidateBfuCount
48
+ * @param {Array<Float32Array>} bfuData
70
49
  * @param {Array<number>} bfuSizes
71
- * @param {i32} remainingBits
72
- * @param {Float64Array} biasedScaleFactors
73
- * @param {Int32Array} allScaleFactorIndices
74
- * @param {Float32Array} zeroBitDistortions
75
- * @returns {object} Allocation result.
50
+ * @param {Int32Array} initialScaleFactorIndices
51
+ * @param {Float64Array} maxAmplitudes
52
+ * @param {Float64Array} energies
53
+ * @param {Float64Array} perceptualWeights
54
+ * @param {Float64Array} seedThresholds
55
+ * @param {Float64Array} distortionCache
56
+ * @param {Int32Array} candidateWordLengths
57
+ * @returns {void}
58
+ * @nativeUnchecked Native callers supply frame-bounded buffers and indices.
76
59
  */
77
- function search(
78
- activeBfuCount,
79
- maxBfuCount,
60
+ function solveForBfuCount(
61
+ candidateBfuCount,
62
+ bfuData,
80
63
  bfuSizes,
81
- remainingBits,
82
- biasedScaleFactors,
83
- allScaleFactorIndices,
84
- zeroBitDistortions
64
+ initialScaleFactorIndices,
65
+ maxAmplitudes,
66
+ energies,
67
+ perceptualWeights,
68
+ seedThresholds,
69
+ distortionCache,
70
+ candidateWordLengths
85
71
  ) {
86
- const allocation = distributeBits(
87
- activeBfuCount,
72
+ const bitBudget =
73
+ FRAME_BITS - FRAME_OVERHEAD_BITS - candidateBfuCount * BITS_PER_BFU_METADATA
74
+ /** @type {i32} */
75
+ let usedBits = tuneToBudget(
76
+ candidateBfuCount,
77
+ bitBudget,
88
78
  bfuSizes,
89
- remainingBits,
90
- biasedScaleFactors,
91
- allScaleFactorIndices,
92
- zeroBitDistortions
79
+ energies,
80
+ seedThresholds,
81
+ candidateWordLengths
93
82
  )
94
- const distortion = measureDistortion(
95
- activeBfuCount,
96
- maxBfuCount,
83
+ usedBits = exchangePerceptualBits(
84
+ candidateBfuCount,
85
+ bitBudget,
86
+ usedBits,
87
+ bfuData,
97
88
  bfuSizes,
98
- allocation.wordLengths,
99
- allocation.scaleFactorIndices,
100
- biasedScaleFactors,
101
- zeroBitDistortions
89
+ initialScaleFactorIndices,
90
+ maxAmplitudes,
91
+ energies,
92
+ perceptualWeights,
93
+ distortionCache,
94
+ candidateWordLengths
95
+ )
96
+ fillSlackBits(
97
+ candidateBfuCount,
98
+ bitBudget - usedBits,
99
+ bfuData,
100
+ bfuSizes,
101
+ initialScaleFactorIndices,
102
+ maxAmplitudes,
103
+ energies,
104
+ perceptualWeights,
105
+ distortionCache,
106
+ candidateWordLengths
102
107
  )
103
- return { distortion, ...allocation }
104
108
  }
105
109
 
106
110
  /**
107
- * Calculates the total distortion for a given allocation.
108
- * This includes quantization distortion for coded bands and truncation
109
- * distortion for uncoded bands.
110
- * @param {i32} activeBfuCount
111
- * @param {i32} maxBfuCount
111
+ * Allocate bits across BFUs for one transformed ATRAC1 channel frame.
112
+ *
113
+ * @param {Array<Float32Array>} bfuData
112
114
  * @param {Array<number>} bfuSizes
113
- * @param {Int32Array} wordLengths
114
- * @param {Int32Array} scaleFactorIndices
115
- * @param {Float64Array} biasedScaleFactors
116
- * @param {Float32Array} zeroBitDistortions
117
- * @returns {number}
118
- * @nativeUnchecked Native callers supply frame-bounded buffers and indices.
115
+ * @param {i32} maxBfuCount
116
+ * @param {f64} allocationBias
117
+ * @param {Array<number>} [blockModes]
118
+ * @param {SoundUnitAllocationSolverScratch} [scratch]
119
+ * @returns {{bfuCount:number, allocation:Int32Array, scaleFactorIndices:Int32Array}}
119
120
  */
120
- function measureDistortion(
121
- activeBfuCount,
122
- maxBfuCount,
121
+ export function solve(
122
+ bfuData,
123
123
  bfuSizes,
124
- wordLengths,
125
- scaleFactorIndices,
126
- biasedScaleFactors,
127
- zeroBitDistortions
124
+ maxBfuCount,
125
+ allocationBias,
126
+ blockModes = null,
127
+ scratch = null
128
128
  ) {
129
- let totalDistortion = 0.0
130
-
131
- for (let i = 0; i < activeBfuCount; i++) {
132
- const wl = wordLengths[i] | 0
133
- const bits = WORD_LENGTH_BITS[wl] | 0
134
- if (bits === 0) {
135
- totalDistortion += zeroBitDistortions[i]
129
+ /** @type {SoundUnitAllocationSolverScratch} */
130
+ const scratchBuffer = scratch ?? defaultScratch
131
+ const energies = scratchBuffer.energies
132
+ const maxAmplitudes = scratchBuffer.maxAmplitudes
133
+ const initialScaleFactorIndices = scratchBuffer.initialScaleFactorIndices
134
+ const maskThresholds = scratchBuffer.maskThresholds
135
+ const perceptualWeights = scratchBuffer.perceptualWeights
136
+ const seedThresholds = scratchBuffer.seedThresholds
137
+ const distortionCache = scratchBuffer.distortionCache
138
+ const candidateWordLengths = scratchBuffer.candidateWordLengths
139
+ const selectedWordLengths = scratchBuffer.selectedWordLengths
140
+ const refinedScaleFactorIndices = scratchBuffer.refinedScaleFactorIndices
141
+
142
+ /** @type {f64} */
143
+ let totalEnergy = 0.0
144
+ for (let unit = 0; unit < maxBfuCount; unit++) {
145
+ const size = bfuSizes[unit] | 0
146
+ if (size <= 0) {
147
+ energies[unit] = 0.0
148
+ maxAmplitudes[unit] = 0.0
149
+ initialScaleFactorIndices[unit] = 0
136
150
  continue
137
151
  }
138
152
 
139
- const sfi = scaleFactorIndices[i]
140
- const effectiveScaleFactor =
141
- sfi === 0
142
- ? zeroBitDistortions[i] / (2 * bfuSizes[i])
143
- : biasedScaleFactors[sfi]
144
- const distortionFactor = INV_POWER_OF_TWO[bits]
145
-
146
- totalDistortion += effectiveScaleFactor * distortionFactor * bfuSizes[i]
147
- }
148
-
149
- for (let i = activeBfuCount; i < maxBfuCount; i++) {
150
- totalDistortion += zeroBitDistortions[i]
151
- }
152
-
153
- return totalDistortion
154
- }
155
-
156
- /**
157
- * Distributes available bits across Band Frequency Units (BFUs) using Rate-Distortion Optimization.
158
- * (Modified to accept pre-calculated scale factors)
159
- *
160
- * @param {i32} activeBfuCount
161
- * @param {Array<number>} bfuSizes
162
- * @param {i32} remainingBits
163
- * @param {Float64Array} biasedScaleFactors
164
- * @param {Int32Array} allScaleFactorIndices
165
- * @param {Float32Array} zeroBitDistortions Nonzero for nonsilent BFUs.
166
- * @returns {object} Retained allocation decisions.
167
- * @nativeUnchecked Native callers supply frame-bounded buffers and indices.
168
- */
169
- function distributeBits(
170
- activeBfuCount,
171
- bfuSizes,
172
- remainingBits,
173
- biasedScaleFactors,
174
- allScaleFactorIndices,
175
- zeroBitDistortions
176
- ) {
177
- const wordLengths = new Int32Array(activeBfuCount)
178
-
179
- const heapIndices = new Int32Array(activeBfuCount)
180
- const heapPriorities = new Float32Array(activeBfuCount)
181
- let heapSize = 0
182
-
183
- for (let bfuIndex = 0; bfuIndex < activeBfuCount; bfuIndex++) {
184
- const sz = bfuSizes[bfuIndex] | 0
185
- if (sz === 0) continue
186
-
187
- const sfi = allScaleFactorIndices[bfuIndex]
188
- if (zeroBitDistortions[bfuIndex] === 0) continue
189
-
190
- const deltaBits = WORD_LENGTH_DELTA_BITS[0]
191
- if (deltaBits <= 0) continue
153
+ /** @type {Float32Array} */
154
+ const bfu = bfuData[unit]
155
+ /** @type {f64} */
156
+ let energy = 0.0
157
+ /** @type {f64} */
158
+ let maxAmplitude = 0.0
159
+ for (let index = 0; index < size; index++) {
160
+ const value = bfu[index]
161
+ energy += value * value
162
+ const absValue = value < 0.0 ? -value : value
163
+ if (absValue > maxAmplitude) maxAmplitude = absValue
164
+ }
192
165
 
193
- const effectiveScaleFactor =
194
- sfi === 0
195
- ? zeroBitDistortions[bfuIndex] / (2 * sz)
196
- : biasedScaleFactors[sfi]
197
- const distortionDelta = effectiveScaleFactor * DISTORTION_DELTA_FACTORS[0]
166
+ energies[unit] = energy
167
+ maxAmplitudes[unit] = maxAmplitude
168
+ totalEnergy += energy
198
169
 
199
- heapIndices[heapSize] = bfuIndex
200
- heapPriorities[heapSize] = distortionDelta / deltaBits
201
- heapSize++
170
+ if (maxAmplitude === 0.0) {
171
+ initialScaleFactorIndices[unit] = 0
172
+ } else {
173
+ const scaleIndex = Math.ceil(3.0 * (Math.log2(maxAmplitude) + 21.0)) | 0
174
+ initialScaleFactorIndices[unit] =
175
+ scaleIndex < 0 ? 0 : scaleIndex > 63 ? 63 : scaleIndex
176
+ }
202
177
  }
203
178
 
204
- if (heapSize === 0) {
205
- return { wordLengths, scaleFactorIndices: allScaleFactorIndices }
179
+ const cacheEntryCount = maxBfuCount * BFU_DISTORTION_CACHE_STRIDE
180
+ for (let index = 0; index < cacheEntryCount; index++) {
181
+ distortionCache[index] = -1.0
206
182
  }
207
183
 
208
- // Heapify
209
- for (let i = (heapSize >> 1) - 1; i >= 0; i--) {
210
- siftDown(heapIndices, heapPriorities, i, heapSize)
184
+ /** @type {i32} */
185
+ let maxLegalBfuCount = maxBfuCount
186
+ const firstLegalBfuCount = BFU_AMOUNTS[0]
187
+ if (firstLegalBfuCount < maxLegalBfuCount)
188
+ maxLegalBfuCount = firstLegalBfuCount
189
+ for (let index = 1; index < BFU_AMOUNTS.length; index++) {
190
+ const candidate = BFU_AMOUNTS[index]
191
+ if (candidate <= maxBfuCount) maxLegalBfuCount = candidate
211
192
  }
212
193
 
213
- // Greedy spending loop
214
- while (remainingBits > 0 && heapSize > 0) {
215
- const bfu = heapIndices[0]
216
- const cur = wordLengths[bfu] | 0
217
- const sz = bfuSizes[bfu] | 0
218
- const deltaBits = WORD_LENGTH_DELTA_BITS[cur]
219
- const cost = deltaBits * sz
220
-
221
- if (cost > remainingBits || cost <= 0) {
222
- const last = heapSize - 1
223
- heapIndices[0] = heapIndices[last]
224
- heapPriorities[0] = heapPriorities[last]
225
- heapSize--
226
- if (heapSize > 0) siftDown(heapIndices, heapPriorities, 0, heapSize)
227
- continue
228
- }
229
-
230
- remainingBits -= cost
231
- const nxt = cur + 1
232
- wordLengths[bfu] = nxt
233
-
234
- const deltaBitsNext = WORD_LENGTH_DELTA_BITS[nxt]
235
- if (nxt < MAX_WORD_LENGTH_INDEX && deltaBitsNext > 0) {
236
- const sfi = allScaleFactorIndices[bfu]
237
- const effectiveScaleFactor =
238
- sfi === 0 ? zeroBitDistortions[bfu] / (2 * sz) : biasedScaleFactors[sfi]
239
- const distortionDelta =
240
- effectiveScaleFactor * DISTORTION_DELTA_FACTORS[nxt]
241
- heapPriorities[0] = distortionDelta / deltaBitsNext
242
- siftDown(heapIndices, heapPriorities, 0, heapSize)
243
- } else {
244
- const last = heapSize - 1
245
- heapIndices[0] = heapIndices[last]
246
- heapPriorities[0] = heapPriorities[last]
247
- heapSize--
248
- if (heapSize > 0) siftDown(heapIndices, heapPriorities, 0, heapSize)
194
+ if (totalEnergy === 0.0 || maxLegalBfuCount <= 0) {
195
+ return {
196
+ bfuCount: maxLegalBfuCount,
197
+ allocation: new Int32Array(maxLegalBfuCount),
198
+ scaleFactorIndices: new Int32Array(maxBfuCount),
249
199
  }
250
200
  }
251
201
 
252
- return { wordLengths, scaleFactorIndices: allScaleFactorIndices }
253
- }
202
+ let lowBandMode = 0
203
+ let midBandMode = 0
204
+ let highBandMode = 0
205
+ if (blockModes) {
206
+ lowBandMode = blockModes[0] | 0
207
+ midBandMode = blockModes[1] | 0
208
+ highBandMode = blockModes[2] | 0
209
+ }
254
210
 
255
- /**
256
- * Restores max-heap property by sifting an element down from a given position.
257
- *
258
- * This function maintains the heap invariant where parent nodes have higher
259
- * priority values than their children. It compares the element at startIndex
260
- * with its children and swaps with the larger child until the heap property
261
- * is satisfied, or it reaches a leaf position.
262
- *
263
- * @param {Int32Array} heapIndices
264
- * @param {Float32Array} heapPriorities
265
- * @param {i32} startIndex
266
- * @param {i32} heapSize
267
- * @nativeUnchecked Native callers supply frame-bounded buffers and indices.
268
- */
269
- function siftDown(heapIndices, heapPriorities, startIndex, heapSize) {
270
- let i = startIndex
271
- const idxVal = heapIndices[i]
272
- const prVal = heapPriorities[i]
211
+ buildPerceptualMask(
212
+ energies,
213
+ maxAmplitudes,
214
+ bfuSizes,
215
+ maxBfuCount,
216
+ totalEnergy,
217
+ lowBandMode,
218
+ midBandMode,
219
+ highBandMode,
220
+ maskThresholds
221
+ )
222
+ buildPerceptualWeights(
223
+ energies,
224
+ maxAmplitudes,
225
+ initialScaleFactorIndices,
226
+ bfuSizes,
227
+ maxBfuCount,
228
+ allocationBias,
229
+ lowBandMode,
230
+ midBandMode,
231
+ highBandMode,
232
+ maskThresholds,
233
+ perceptualWeights,
234
+ seedThresholds
235
+ )
273
236
 
274
- while (true) {
275
- const l = (i << 1) + 1
276
- const r = l + 1
277
- let maxI = i
278
- let maxP = prVal
237
+ solveForBfuCount(
238
+ maxLegalBfuCount,
239
+ bfuData,
240
+ bfuSizes,
241
+ initialScaleFactorIndices,
242
+ maxAmplitudes,
243
+ energies,
244
+ perceptualWeights,
245
+ seedThresholds,
246
+ distortionCache,
247
+ candidateWordLengths
248
+ )
279
249
 
280
- if (l < heapSize && heapPriorities[l] > maxP) {
281
- maxI = l
282
- maxP = heapPriorities[l]
250
+ let lastActive = 0
251
+ for (let unit = maxLegalBfuCount - 1; unit >= 0; unit--) {
252
+ if (candidateWordLengths[unit] > 0) {
253
+ lastActive = unit + 1
254
+ break
283
255
  }
284
- if (r < heapSize && heapPriorities[r] > maxP) {
285
- maxI = r
286
- }
287
- if (maxI === i) break
288
-
289
- heapIndices[i] = heapIndices[maxI]
290
- heapPriorities[i] = heapPriorities[maxI]
291
- i = maxI
292
256
  }
293
257
 
294
- heapIndices[i] = idxVal
295
- heapPriorities[i] = prVal
296
- }
297
-
298
- /**
299
- * Allocate bits by finding the optimal BFU count and distribution using RDO.
300
- * This function searches through the valid BFU counts to find the one that
301
- * minimizes the total perceptual distortion.
302
- *
303
- * @param {Array<Float32Array>} bfuData
304
- * @param {Array<number>} bfuSizes
305
- * @param {i32} maxBfuCount
306
- * @param {number} allocationBias
307
- * @returns {{bfuCount:number, allocation:Int32Array, scaleFactorIndices:Int32Array}}
308
- */
309
- export function solve(bfuData, bfuSizes, maxBfuCount, allocationBias) {
310
- const allScaleFactorIndices = new Int32Array(maxBfuCount)
311
- const zeroBitDistortions = new Float32Array(maxBfuCount)
312
- const biasedScaleFactors = buildBiasedScaleFactorTable(allocationBias)
313
-
314
- for (let i = 0; i < maxBfuCount; i++) {
315
- const sz = bfuSizes[i] | 0
316
- if (sz === 0) continue
317
-
318
- const sfi = findScaleFactor(bfuData[i], sz)
319
- allScaleFactorIndices[i] = sfi
320
- // Index zero covers both silence and all values below the smallest scale.
321
- // Use the actual peak there so tiny BFUs do not all receive equal priority.
322
- let effectiveScaleFactor = biasedScaleFactors[sfi]
323
- if (sfi === 0) {
324
- let peak = 0
325
- for (let j = 0; j < sz; j++)
326
- peak = Math.max(peak, Math.abs(bfuData[i][j]))
327
- effectiveScaleFactor = peak === 0 ? 0 : Math.pow(peak, allocationBias)
258
+ /** @type {i32} */
259
+ let bestBfuCount = maxLegalBfuCount
260
+ for (let index = 0; index < BFU_AMOUNTS.length; index++) {
261
+ const candidate = BFU_AMOUNTS[index]
262
+ if (candidate <= maxLegalBfuCount && candidate >= lastActive) {
263
+ bestBfuCount = candidate
264
+ break
328
265
  }
329
- zeroBitDistortions[i] = effectiveScaleFactor * 2.0 * sz
330
266
  }
331
267
 
332
- let bestResult = null
333
- let minTotalDistortion = Infinity
334
-
335
- for (const candidateBfuCount of BFU_AMOUNTS) {
336
- if (candidateBfuCount > maxBfuCount) continue
337
-
338
- const availableBits =
339
- FRAME_BITS -
340
- FRAME_OVERHEAD_BITS -
341
- candidateBfuCount * BITS_PER_BFU_METADATA
342
-
343
- if (availableBits < 0) continue
344
-
345
- const result = search(
346
- candidateBfuCount,
347
- maxBfuCount,
268
+ if (bestBfuCount < maxLegalBfuCount) {
269
+ solveForBfuCount(
270
+ bestBfuCount,
271
+ bfuData,
348
272
  bfuSizes,
349
- availableBits,
350
- biasedScaleFactors,
351
- allScaleFactorIndices,
352
- zeroBitDistortions
273
+ initialScaleFactorIndices,
274
+ maxAmplitudes,
275
+ energies,
276
+ perceptualWeights,
277
+ seedThresholds,
278
+ distortionCache,
279
+ candidateWordLengths
353
280
  )
354
-
355
- if (result.distortion < minTotalDistortion) {
356
- minTotalDistortion = result.distortion
357
- bestResult = {
358
- bfuCount: candidateBfuCount,
359
- allocation: result.wordLengths,
360
- scaleFactorIndices: result.scaleFactorIndices,
361
- }
362
- }
363
281
  }
364
282
 
365
- if (!bestResult) {
366
- const fallbackBfuCount = BFU_AMOUNTS[0]
367
- return {
368
- bfuCount: fallbackBfuCount,
369
- allocation: new Int32Array(fallbackBfuCount),
370
- scaleFactorIndices: new Int32Array(NUM_BFUS),
371
- }
283
+ for (let unit = 0; unit < bestBfuCount; unit++) {
284
+ selectedWordLengths[unit] = candidateWordLengths[unit]
372
285
  }
373
286
 
374
- return bestResult
287
+ refineScaleFactors(
288
+ bestBfuCount,
289
+ maxBfuCount,
290
+ bfuData,
291
+ bfuSizes,
292
+ energies,
293
+ initialScaleFactorIndices,
294
+ selectedWordLengths,
295
+ refinedScaleFactorIndices
296
+ )
297
+
298
+ return {
299
+ bfuCount: bestBfuCount,
300
+ allocation: selectedWordLengths.slice(0, bestBfuCount),
301
+ scaleFactorIndices: refinedScaleFactorIndices.slice(0, maxBfuCount),
302
+ }
375
303
  }
376
304
 
377
305
  /**
378
306
  * Find the optimal scale factor index for a set of coefficients.
379
307
  * Same semantics as the original.
308
+ *
380
309
  * @param {Float32Array} coefficients
381
310
  * @param {i32} length
382
- * @returns {number}
311
+ * @returns {i32}
383
312
  */
384
313
  export function findScaleFactor(coefficients, length) {
385
314
  let maxAmplitude = 0.0
386
- for (let i = 0; i < length; i++) {
387
- const a = Math.abs(coefficients[i])
388
- if (a > maxAmplitude) maxAmplitude = a
315
+ for (let index = 0; index < length; index++) {
316
+ const amplitude = Math.abs(coefficients[index])
317
+ if (amplitude > maxAmplitude) maxAmplitude = amplitude
389
318
  }
390
319
  if (maxAmplitude === 0) return 0
391
320
  const index = Math.ceil(3 * (Math.log2(maxAmplitude) + 21))