mirror of
https://github.com/arcodange-org/mediabunny.git
synced 2026-10-01 04:43:51 +02:00
Add @mediabunny/aac-encoder extension package
This commit is contained in:
+2
-79
@@ -6,6 +6,8 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { Bitstream } from '../shared/bitstream';
|
||||
|
||||
export function assert(x: unknown): asserts x {
|
||||
if (!x) {
|
||||
throw new Error('Assertion failed.');
|
||||
@@ -39,85 +41,6 @@ export const isU32 = (value: number) => {
|
||||
return value >= 0 && value < 2 ** 32;
|
||||
};
|
||||
|
||||
export class Bitstream {
|
||||
/** Current offset in bits. */
|
||||
pos = 0;
|
||||
|
||||
constructor(public bytes: Uint8Array) {}
|
||||
|
||||
seekToByte(byteOffset: number) {
|
||||
this.pos = 8 * byteOffset;
|
||||
}
|
||||
|
||||
private readBit() {
|
||||
const byteIndex = Math.floor(this.pos / 8);
|
||||
const byte = this.bytes[byteIndex] ?? 0;
|
||||
const bitIndex = 0b111 - (this.pos & 0b111);
|
||||
const bit = (byte & (1 << bitIndex)) >> bitIndex;
|
||||
|
||||
this.pos++;
|
||||
return bit;
|
||||
}
|
||||
|
||||
readBits(n: number) {
|
||||
if (n === 1) {
|
||||
return this.readBit();
|
||||
}
|
||||
|
||||
let result = 0;
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
result <<= 1;
|
||||
result |= this.readBit();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
writeBits(n: number, value: number) {
|
||||
const end = this.pos + n;
|
||||
|
||||
for (let i = this.pos; i < end; i++) {
|
||||
const byteIndex = Math.floor(i / 8);
|
||||
let byte = this.bytes[byteIndex]!;
|
||||
const bitIndex = 0b111 - (i & 0b111);
|
||||
|
||||
byte &= ~(1 << bitIndex);
|
||||
byte |= ((value & (1 << (end - i - 1))) >> (end - i - 1)) << bitIndex;
|
||||
this.bytes[byteIndex] = byte;
|
||||
}
|
||||
|
||||
this.pos = end;
|
||||
};
|
||||
|
||||
readAlignedByte() {
|
||||
// Ensure we're byte-aligned
|
||||
if (this.pos % 8 !== 0) {
|
||||
throw new Error('Bitstream is not byte-aligned.');
|
||||
}
|
||||
|
||||
const byteIndex = this.pos / 8;
|
||||
const byte = this.bytes[byteIndex] ?? 0;
|
||||
|
||||
this.pos += 8;
|
||||
return byte;
|
||||
}
|
||||
|
||||
skipBits(n: number) {
|
||||
this.pos += n;
|
||||
}
|
||||
|
||||
getBitsLeft() {
|
||||
return this.bytes.length * 8 - this.pos;
|
||||
}
|
||||
|
||||
clone() {
|
||||
const clone = new Bitstream(this.bytes);
|
||||
clone.pos = this.pos;
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads an exponential-Golomb universal code from a Bitstream. */
|
||||
export const readExpGolomb = (bitstream: Bitstream) => {
|
||||
let leadingZeroBits = 0;
|
||||
|
||||
Reference in New Issue
Block a user