MCPcopy Create free account
hub / github.com/CoderLine/alphaTab / _buildLength

Method _buildLength

packages/alphatab/src/zip/DeflaterHuffman.ts:217–292  ·  view source on GitHub ↗
(childs: Int32Array)

Source from the content-addressed store, hash-verified

215 }
216
217 private _buildLength(childs: Int32Array) {
218 this.length = new Uint8Array(this.freqs.length);
219 const numNodes = Math.floor(childs.length / 2);
220 const numLeafs = Math.floor((numNodes + 1) / 2);
221 let overflow = 0;
222
223 for (let i = 0; i < this._maxLength; i++) {
224 this._bitLengthCounts[i] = 0;
225 }
226
227 // First calculate optimal bit lengths
228 const lengths = new Int32Array(numNodes);
229 lengths[numNodes - 1] = 0;
230
231 for (let i = numNodes - 1; i >= 0; i--) {
232 if (childs[2 * i + 1] !== -1) {
233 let bitLength = lengths[i] + 1;
234 if (bitLength > this._maxLength) {
235 bitLength = this._maxLength;
236 overflow++;
237 }
238 lengths[childs[2 * i]] = bitLength;
239 lengths[childs[2 * i + 1]] = bitLength;
240 } else {
241 // A leaf node
242 const bitLength = lengths[i];
243 this._bitLengthCounts[bitLength - 1]++;
244 this.length[childs[2 * i]] = lengths[i];
245 }
246 }
247
248 if (overflow === 0) {
249 return;
250 }
251
252 let incrBitLen = this._maxLength - 1;
253 do {
254 // Find the first bit length which could increase:
255 while (this._bitLengthCounts[--incrBitLen] === 0) {}
256
257 // Move this node one down and remove a corresponding
258 // number of overflow nodes.
259 do {
260 this._bitLengthCounts[incrBitLen]--;
261 this._bitLengthCounts[++incrBitLen]++;
262 overflow -= 1 << (this._maxLength - 1 - incrBitLen);
263 } while (overflow > 0 && incrBitLen < this._maxLength - 1);
264 } while (overflow > 0);
265
266 /* We may have overshot above. Move some nodes from maxLength to
267 * maxLength-1 in that case.
268 */
269 this._bitLengthCounts[this._maxLength - 1] += overflow;
270 this._bitLengthCounts[this._maxLength - 2] -= overflow;
271
272 /* Now recompute all bit lengths, scanning in increasing
273 * frequency. It is simpler to reconstruct all lengths instead of
274 * fixing only the wrong ones. This idea is taken from 'ar'

Callers 1

buildTreeMethod · 0.95

Calls 1

floorMethod · 0.80

Tested by

no test coverage detected