@hiroosy/baileys-lite 0.4.3 → 0.4.4

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.
Files changed (57) hide show
  1. package/README.md +8 -17
  2. package/package.json +1 -1
  3. package/src/ffmpeg/LICENSE +502 -0
  4. package/src/ffmpeg/index.js +64 -0
  5. package/src/ffmpeg/lib/bits.js +150 -0
  6. package/src/ffmpeg/lib/bsf.js +242 -0
  7. package/src/ffmpeg/lib/codec/flac.js +801 -0
  8. package/src/ffmpeg/lib/codec/index.js +108 -0
  9. package/src/ffmpeg/lib/codec/mp3.js +768 -0
  10. package/src/ffmpeg/lib/codec/mpa.js +65 -0
  11. package/src/ffmpeg/lib/codec/mpa_tables.js +27 -0
  12. package/src/ffmpeg/lib/codec/opus.js +140 -0
  13. package/src/ffmpeg/lib/codec/pcm.js +198 -0
  14. package/src/ffmpeg/lib/compat.js +42 -0
  15. package/src/ffmpeg/lib/crc.js +60 -0
  16. package/src/ffmpeg/lib/demux/adts.js +151 -0
  17. package/src/ffmpeg/lib/demux/flac.js +150 -0
  18. package/src/ffmpeg/lib/demux/image.js +47 -0
  19. package/src/ffmpeg/lib/demux/index.js +60 -0
  20. package/src/ffmpeg/lib/demux/matroska.js +525 -0
  21. package/src/ffmpeg/lib/demux/merge.js +106 -0
  22. package/src/ffmpeg/lib/demux/mp3.js +199 -0
  23. package/src/ffmpeg/lib/demux/mp4.js +622 -0
  24. package/src/ffmpeg/lib/demux/ogg.js +250 -0
  25. package/src/ffmpeg/lib/demux/ts.js +354 -0
  26. package/src/ffmpeg/lib/demux/wav.js +156 -0
  27. package/src/ffmpeg/lib/errors.js +27 -0
  28. package/src/ffmpeg/lib/filter/gain.js +69 -0
  29. package/src/ffmpeg/lib/filter/mix.js +95 -0
  30. package/src/ffmpeg/lib/filter/resample.js +187 -0
  31. package/src/ffmpeg/lib/filter/video.js +575 -0
  32. package/src/ffmpeg/lib/image/bmp.js +123 -0
  33. package/src/ffmpeg/lib/image/frame.js +216 -0
  34. package/src/ffmpeg/lib/image/gif.js +215 -0
  35. package/src/ffmpeg/lib/image/index.js +70 -0
  36. package/src/ffmpeg/lib/image/jpeg.js +964 -0
  37. package/src/ffmpeg/lib/image/png.js +256 -0
  38. package/src/ffmpeg/lib/image/run.js +67 -0
  39. package/src/ffmpeg/lib/io.js +298 -0
  40. package/src/ffmpeg/lib/mux/adts.js +75 -0
  41. package/src/ffmpeg/lib/mux/flac.js +79 -0
  42. package/src/ffmpeg/lib/mux/mp3.js +85 -0
  43. package/src/ffmpeg/lib/mux/mp4.js +450 -0
  44. package/src/ffmpeg/lib/mux/ogg.js +146 -0
  45. package/src/ffmpeg/lib/mux/wav.js +94 -0
  46. package/src/ffmpeg/lib/net.js +270 -0
  47. package/src/ffmpeg/lib/pipeline.js +579 -0
  48. package/src/ffmpeg/lib/probe.js +45 -0
  49. package/src/ffmpeg/lib/tags.js +307 -0
  50. package/src/ffmpeg/lib/util.js +104 -0
  51. package/src/foundation/image-thumb.js +4 -56
  52. package/src/socket/messages-recv.js +5 -6
  53. package/src/utils/media.js +8 -85
  54. package/src/utils/message-compose.js +19 -11
  55. package/src/voip/index.js +16 -50
  56. package/src/voip/media/WaAudioEngine.js +8 -216
  57. package/src/voip/media/WaVideoEngine.js +8 -237
@@ -0,0 +1,256 @@
1
+ import zlib from 'node:zlib';
2
+ import { badData, noSupport } from '../errors.js';
3
+ import { createRgba, createGray, toRgba, hasAlpha } from './frame.js';
4
+
5
+ const signature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
6
+ const channelsByType = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
7
+
8
+ const crcTable = (() => {
9
+ const t = new Uint32Array(256);
10
+ for (let n = 0; n < 256; n++) {
11
+ let c = n;
12
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
13
+ t[n] = c >>> 0;
14
+ }
15
+ return t;
16
+ })();
17
+
18
+ function crc32(buf, start, end) {
19
+ let c = 0xffffffff;
20
+ for (let i = start; i < end; i++) c = crcTable[(c ^ buf[i]) & 255] ^ (c >>> 8);
21
+ return (c ^ 0xffffffff) >>> 0;
22
+ }
23
+
24
+ function isPng(buf) {
25
+ return buf.length >= 8 && buf.compare(signature, 0, 8, 0, 8) === 0;
26
+ }
27
+
28
+ function readHeader(buf) {
29
+ if (!isPng(buf) || buf.length < 33 || buf.toString('latin1', 12, 16) !== 'IHDR') throw badData('not a png');
30
+ return {
31
+ width: buf.readUInt32BE(16),
32
+ height: buf.readUInt32BE(20),
33
+ depth: buf[24],
34
+ colorType: buf[25],
35
+ interlace: buf[28],
36
+ };
37
+ }
38
+
39
+ function probePng(buf) {
40
+ if (!isPng(buf) || buf.length < 33) return null;
41
+ const h = readHeader(buf);
42
+ return { width: h.width, height: h.height, colorType: h.colorType, depth: h.depth };
43
+ }
44
+
45
+ function paeth(a, b, c) {
46
+ const p = a + b - c;
47
+ const pa = Math.abs(p - a);
48
+ const pb = Math.abs(p - b);
49
+ const pc = Math.abs(p - c);
50
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
51
+ }
52
+
53
+ function unfilter(data, offset, width, height, bpp, rowBytes) {
54
+ const out = new Uint8Array(rowBytes * height);
55
+ let pos = offset;
56
+ for (let y = 0; y < height; y++) {
57
+ const ft = data[pos++];
58
+ const row = y * rowBytes;
59
+ const prev = row - rowBytes;
60
+ if (ft > 4) throw badData('invalid png filter');
61
+ for (let x = 0; x < rowBytes; x++) {
62
+ const raw = data[pos++];
63
+ const a = x >= bpp ? out[row + x - bpp] : 0;
64
+ const b = y > 0 ? out[prev + x] : 0;
65
+ let v;
66
+ if (ft === 0) v = raw;
67
+ else if (ft === 1) v = raw + a;
68
+ else if (ft === 2) v = raw + b;
69
+ else if (ft === 3) v = raw + ((a + b) >> 1);
70
+ else v = raw + paeth(a, b, x >= bpp && y > 0 ? out[prev + x - bpp] : 0);
71
+ out[row + x] = v & 255;
72
+ }
73
+ }
74
+ return { out, end: pos };
75
+ }
76
+
77
+ function decodePng(buf) {
78
+ const hdr = readHeader(buf);
79
+ const { width, height, depth, colorType, interlace } = hdr;
80
+ if (!(width > 0 && height > 0) || width * height > 268435456) throw badData('invalid png size');
81
+ const ch = channelsByType[colorType];
82
+ if (!ch) throw badData('invalid png color type');
83
+ if (![1, 2, 4, 8, 16].includes(depth)) throw badData('invalid png bit depth');
84
+ let palette = null;
85
+ let trns = null;
86
+ const idat = [];
87
+ let pos = 8;
88
+ while (pos + 12 <= buf.length) {
89
+ const len = buf.readUInt32BE(pos);
90
+ const type = buf.toString('latin1', pos + 4, pos + 8);
91
+ const body = pos + 8;
92
+ if (body + len > buf.length) throw badData('truncated png chunk');
93
+ if (type === 'PLTE') palette = buf.subarray(body, body + len);
94
+ else if (type === 'tRNS') trns = buf.subarray(body, body + len);
95
+ else if (type === 'IDAT') idat.push(buf.subarray(body, body + len));
96
+ else if (type === 'IEND') break;
97
+ pos = body + len + 4;
98
+ }
99
+ if (!idat.length) throw badData('png has no image data');
100
+ if (colorType === 3 && !palette) throw badData('png palette missing');
101
+ const raw = zlib.inflateSync(Buffer.concat(idat));
102
+ const bitsPerPixel = ch * depth;
103
+ const bpp = Math.max(1, bitsPerPixel >> 3);
104
+ const sample = (row, rowOff, x, c) => {
105
+ if (depth === 8) return row[rowOff + x * ch + c];
106
+ if (depth === 16) return (row[rowOff + (x * ch + c) * 2] << 8) | row[rowOff + (x * ch + c) * 2 + 1];
107
+ const bitPos = (x * ch + c) * depth;
108
+ const byte = row[rowOff + (bitPos >> 3)];
109
+ return (byte >> (8 - depth - (bitPos & 7))) & ((1 << depth) - 1);
110
+ };
111
+ const maxv = (1 << depth) - 1;
112
+ const scale8 = (v) => (depth === 16 ? v >> 8 : depth === 8 ? v : Math.round((v * 255) / maxv));
113
+ const keyed = trns && (colorType === 0 || colorType === 2);
114
+ const plain = colorType === 0 && !trns;
115
+ const out = plain ? createGray(width, height) : createRgba(width, height);
116
+ const dst = out.planes[0].data;
117
+ const put = (row, rowOff, sx, dx, dy) => {
118
+ if (plain) {
119
+ dst[dy * width + dx] = scale8(sample(row, rowOff, sx, 0));
120
+ return;
121
+ }
122
+ const o = (dy * width + dx) * 4;
123
+ if (colorType === 0) {
124
+ const g = sample(row, rowOff, sx, 0);
125
+ dst[o] = dst[o + 1] = dst[o + 2] = scale8(g);
126
+ dst[o + 3] = keyed && g === ((trns[0] << 8) | trns[1]) ? 0 : 255;
127
+ } else if (colorType === 2) {
128
+ const r = sample(row, rowOff, sx, 0);
129
+ const g = sample(row, rowOff, sx, 1);
130
+ const b = sample(row, rowOff, sx, 2);
131
+ dst[o] = scale8(r);
132
+ dst[o + 1] = scale8(g);
133
+ dst[o + 2] = scale8(b);
134
+ dst[o + 3] = keyed && r === ((trns[0] << 8) | trns[1]) && g === ((trns[2] << 8) | trns[3]) && b === ((trns[4] << 8) | trns[5]) ? 0 : 255;
135
+ } else if (colorType === 3) {
136
+ const i = sample(row, rowOff, sx, 0);
137
+ dst[o] = palette[i * 3];
138
+ dst[o + 1] = palette[i * 3 + 1];
139
+ dst[o + 2] = palette[i * 3 + 2];
140
+ dst[o + 3] = trns && i < trns.length ? trns[i] : 255;
141
+ } else if (colorType === 4) {
142
+ const g = scale8(sample(row, rowOff, sx, 0));
143
+ dst[o] = dst[o + 1] = dst[o + 2] = g;
144
+ dst[o + 3] = scale8(sample(row, rowOff, sx, 1));
145
+ } else {
146
+ dst[o] = scale8(sample(row, rowOff, sx, 0));
147
+ dst[o + 1] = scale8(sample(row, rowOff, sx, 1));
148
+ dst[o + 2] = scale8(sample(row, rowOff, sx, 2));
149
+ dst[o + 3] = scale8(sample(row, rowOff, sx, 3));
150
+ }
151
+ };
152
+ if (!interlace) {
153
+ const rowBytes = Math.ceil((width * bitsPerPixel) / 8);
154
+ if (raw.length < (rowBytes + 1) * height) throw badData('truncated png data');
155
+ const { out: px } = unfilter(raw, 0, width, height, bpp, rowBytes);
156
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) put(px, y * rowBytes, x, x, y);
157
+ return out;
158
+ }
159
+ const passes = [
160
+ [0, 0, 8, 8],
161
+ [4, 0, 8, 8],
162
+ [0, 4, 4, 8],
163
+ [2, 0, 4, 4],
164
+ [0, 2, 2, 4],
165
+ [1, 0, 2, 2],
166
+ [0, 1, 1, 2],
167
+ ];
168
+ let off = 0;
169
+ for (const [x0, y0, dx, dy] of passes) {
170
+ const pw = Math.ceil((width - x0) / dx);
171
+ const ph = Math.ceil((height - y0) / dy);
172
+ if (pw <= 0 || ph <= 0) continue;
173
+ const rowBytes = Math.ceil((pw * bitsPerPixel) / 8);
174
+ if (raw.length < off + (rowBytes + 1) * ph) throw badData('truncated png data');
175
+ const { out: px, end } = unfilter(raw, off, pw, ph, bpp, rowBytes);
176
+ off = end;
177
+ for (let y = 0; y < ph; y++) for (let x = 0; x < pw; x++) put(px, y * rowBytes, x, x0 + x * dx, y0 + y * dy);
178
+ }
179
+ return out;
180
+ }
181
+
182
+ function chunk(type, data) {
183
+ const out = Buffer.alloc(data.length + 12);
184
+ out.writeUInt32BE(data.length, 0);
185
+ out.write(type, 4, 'latin1');
186
+ Buffer.from(data.buffer, data.byteOffset, data.length).copy(out, 8);
187
+ out.writeUInt32BE(crc32(out, 4, 8 + data.length), 8 + data.length);
188
+ return out;
189
+ }
190
+
191
+ function encodePng(frame, options = {}) {
192
+ let colorType;
193
+ let ch;
194
+ let src;
195
+ if (frame.format === 'gray') {
196
+ colorType = 0;
197
+ ch = 1;
198
+ src = frame.planes[0].data;
199
+ } else {
200
+ const rgba = toRgba(frame);
201
+ const alpha = hasAlpha(rgba);
202
+ colorType = alpha ? 6 : 2;
203
+ ch = alpha ? 4 : 3;
204
+ const d = rgba.planes[0].data;
205
+ if (alpha) src = d;
206
+ else {
207
+ src = new Uint8Array(rgba.width * rgba.height * 3);
208
+ for (let i = 0, j = 0; i < d.length; i += 4, j += 3) {
209
+ src[j] = d[i];
210
+ src[j + 1] = d[i + 1];
211
+ src[j + 2] = d[i + 2];
212
+ }
213
+ }
214
+ }
215
+ const { width, height } = frame;
216
+ const rowBytes = width * ch;
217
+ const raw = Buffer.alloc((rowBytes + 1) * height);
218
+ const cand = [new Uint8Array(rowBytes), new Uint8Array(rowBytes), new Uint8Array(rowBytes), new Uint8Array(rowBytes), new Uint8Array(rowBytes)];
219
+ for (let y = 0; y < height; y++) {
220
+ const row = y * rowBytes;
221
+ const prev = row - rowBytes;
222
+ for (let x = 0; x < rowBytes; x++) {
223
+ const v = src[row + x];
224
+ const a = x >= ch ? src[row + x - ch] : 0;
225
+ const b = y > 0 ? src[prev + x] : 0;
226
+ const c = x >= ch && y > 0 ? src[prev + x - ch] : 0;
227
+ cand[0][x] = v;
228
+ cand[1][x] = (v - a) & 255;
229
+ cand[2][x] = (v - b) & 255;
230
+ cand[3][x] = (v - ((a + b) >> 1)) & 255;
231
+ cand[4][x] = (v - paeth(a, b, c)) & 255;
232
+ }
233
+ let best = 0;
234
+ let bestSum = Infinity;
235
+ for (let f = 0; f < 5; f++) {
236
+ let sum = 0;
237
+ const c = cand[f];
238
+ for (let x = 0; x < rowBytes; x++) sum += c[x] < 128 ? c[x] : 256 - c[x];
239
+ if (sum < bestSum) {
240
+ bestSum = sum;
241
+ best = f;
242
+ }
243
+ }
244
+ raw[y * (rowBytes + 1)] = best;
245
+ raw.set(cand[best], y * (rowBytes + 1) + 1);
246
+ }
247
+ const level = options.level === undefined ? 6 : Math.min(9, Math.max(0, options.level));
248
+ const ihdr = Buffer.alloc(13);
249
+ ihdr.writeUInt32BE(width, 0);
250
+ ihdr.writeUInt32BE(height, 4);
251
+ ihdr[8] = 8;
252
+ ihdr[9] = colorType;
253
+ return Buffer.concat([signature, chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw, { level })), chunk('IEND', new Uint8Array(0))]);
254
+ }
255
+
256
+ export { isPng, probePng, decodePng, encodePng };
@@ -0,0 +1,67 @@
1
+ import fs from 'node:fs';
2
+ import pathMod from 'node:path';
3
+ import { badArg, noSupport } from '../errors.js';
4
+ import { detectImage, probeImage, decodeImage, decodeGifFrame, encodeImage, subsamplingOf, codecNames } from './index.js';
5
+ import { parseFilters, applyFilters } from '../filter/video.js';
6
+
7
+ const yieldLoop = () => new Promise((resolve) => setImmediate(resolve));
8
+
9
+ async function loadInput(src) {
10
+ if (Buffer.isBuffer(src)) return src;
11
+ if (src instanceof Uint8Array) return Buffer.from(src.buffer, src.byteOffset, src.length);
12
+ if (typeof src === 'string') return fs.promises.readFile(src);
13
+ throw badArg('invalid image input');
14
+ }
15
+
16
+ function pickFrame(buf, opts) {
17
+ if (detectImage(buf) === 'gif') return decodeGifFrame(buf, opts.startSec);
18
+ return decodeImage(buf);
19
+ }
20
+
21
+ async function runImage(opts, format) {
22
+ if (opts.inputs.length !== 1) throw badArg('image output accepts exactly one input');
23
+ const toFile = typeof opts.output === 'string';
24
+ const src = opts.inputs[0];
25
+ let abs = null;
26
+ if (toFile) {
27
+ abs = pathMod.resolve(opts.output);
28
+ if (typeof src === 'string' && pathMod.resolve(src) === abs) throw badArg('output must differ from input');
29
+ if (!opts.overwrite && fs.existsSync(abs)) throw badArg('output exists: ' + opts.output);
30
+ }
31
+ const buf = await loadInput(src);
32
+ const info = probeImage(buf);
33
+ if (!info) throw noSupport('unsupported image input');
34
+ if (opts.maxPixels && info.width * info.height > opts.maxPixels) throw noSupport('image is too large for native processing');
35
+ const filters = parseFilters(opts.videoFilter);
36
+ const hints = {};
37
+ await yieldLoop();
38
+ let frame = pickFrame(buf, opts);
39
+ await yieldLoop();
40
+ frame = applyFilters(frame, filters, hints);
41
+ await yieldLoop();
42
+ const sub = subsamplingOf(opts.pixFmt || hints.pixFmt);
43
+ const encodeOptions = {};
44
+ if (opts.qscale !== undefined) encodeOptions.qscale = opts.qscale;
45
+ if (opts.quality !== undefined) encodeOptions.quality = opts.quality;
46
+ if (opts.compressionLevel !== undefined) encodeOptions.level = opts.compressionLevel;
47
+ if (sub) Object.assign(encodeOptions, sub);
48
+ const out = encodeImage(frame, format, encodeOptions);
49
+ const result = { format, size: out.length, duration: 0, streams: [{ index: 0, type: 'video', codec: codecNames[format] }] };
50
+ if (toFile) {
51
+ try {
52
+ await fs.promises.writeFile(abs, out);
53
+ } catch (e) {
54
+ try {
55
+ await fs.promises.unlink(abs);
56
+ } catch (ignored) {
57
+ result.cleanup = false;
58
+ }
59
+ throw e;
60
+ }
61
+ delete result.cleanup;
62
+ result.output = opts.output;
63
+ } else result.output = out;
64
+ return result;
65
+ }
66
+
67
+ export { runImage };
@@ -0,0 +1,298 @@
1
+ import fs from 'node:fs';
2
+ import { badData } from './errors.js';
3
+
4
+ const emptyBuf = Buffer.alloc(0);
5
+
6
+ class FileSource {
7
+ constructor(handle, size) {
8
+ this.handle = handle;
9
+ this.size = size;
10
+ }
11
+
12
+ static async open(path) {
13
+ const handle = await fs.promises.open(path, 'r');
14
+ const stat = await handle.stat();
15
+ return new FileSource(handle, stat.size);
16
+ }
17
+
18
+ async readInto(buf, off, len, pos) {
19
+ const result = await this.handle.read(buf, off, len, pos);
20
+ return result.bytesRead;
21
+ }
22
+
23
+ async close() {
24
+ await this.handle.close();
25
+ }
26
+ }
27
+
28
+ class BufferSource {
29
+ constructor(buf) {
30
+ this.buf = buf;
31
+ this.size = buf.length;
32
+ }
33
+
34
+ async readInto(buf, off, len, pos) {
35
+ if (pos >= this.size) return 0;
36
+ const n = Math.min(len, this.size - pos);
37
+ this.buf.copy(buf, off, pos, pos + n);
38
+ return n;
39
+ }
40
+
41
+ async close() {}
42
+ }
43
+
44
+ class Reader {
45
+ constructor(source, windowSize = 262144) {
46
+ this.source = source;
47
+ this.size = source.size;
48
+ this.window = Buffer.allocUnsafe(Math.min(windowSize, Math.max(4096, source.size)));
49
+ this.winStart = 0;
50
+ this.winLen = 0;
51
+ this.pos = 0;
52
+ }
53
+
54
+ get eof() {
55
+ return this.pos >= this.size;
56
+ }
57
+
58
+ get remaining() {
59
+ return this.size - this.pos;
60
+ }
61
+
62
+ seek(pos) {
63
+ this.pos = pos;
64
+ }
65
+
66
+ skip(n) {
67
+ this.pos += n;
68
+ }
69
+
70
+ async fill(pos) {
71
+ const want = Math.min(this.window.length, this.size - pos);
72
+ let got = 0;
73
+ while (got < want) {
74
+ const n = await this.source.readInto(this.window, got, want - got, pos + got);
75
+ if (n <= 0) break;
76
+ got += n;
77
+ }
78
+ this.winStart = pos;
79
+ this.winLen = got;
80
+ }
81
+
82
+ async readInto(dst, off, want) {
83
+ want = Math.min(want, this.size - this.pos);
84
+ let done = 0;
85
+ while (done < want) {
86
+ const p = this.pos + done;
87
+ if (p >= this.winStart && p < this.winStart + this.winLen) {
88
+ const k = Math.min(want - done, this.winStart + this.winLen - p);
89
+ this.window.copy(dst, off + done, p - this.winStart, p - this.winStart + k);
90
+ done += k;
91
+ } else if (want - done >= this.window.length) {
92
+ const got = await this.source.readInto(dst, off + done, want - done, p);
93
+ if (got <= 0) break;
94
+ done += got;
95
+ } else {
96
+ await this.fill(p);
97
+ if (this.winLen === 0) break;
98
+ }
99
+ }
100
+ this.pos += done;
101
+ return done;
102
+ }
103
+
104
+ async read(n) {
105
+ n = Math.min(n, this.size - this.pos);
106
+ if (n <= 0) return emptyBuf;
107
+ const out = Buffer.allocUnsafe(n);
108
+ const got = await this.readInto(out, 0, n);
109
+ return got === n ? out : out.subarray(0, got);
110
+ }
111
+
112
+ async readExact(n) {
113
+ const buf = await this.read(n);
114
+ if (buf.length < n) throw badData('unexpected end of file');
115
+ return buf;
116
+ }
117
+
118
+ async peek(n) {
119
+ const p = this.pos;
120
+ const buf = await this.read(n);
121
+ this.pos = p;
122
+ return buf;
123
+ }
124
+
125
+ async u8() {
126
+ return (await this.readExact(1))[0];
127
+ }
128
+
129
+ async u16be() {
130
+ return (await this.readExact(2)).readUInt16BE(0);
131
+ }
132
+
133
+ async u16le() {
134
+ return (await this.readExact(2)).readUInt16LE(0);
135
+ }
136
+
137
+ async u32be() {
138
+ return (await this.readExact(4)).readUInt32BE(0);
139
+ }
140
+
141
+ async u32le() {
142
+ return (await this.readExact(4)).readUInt32LE(0);
143
+ }
144
+
145
+ async close() {
146
+ await this.source.close();
147
+ }
148
+ }
149
+
150
+ class FileSink {
151
+ constructor(handle, bufSize) {
152
+ this.handle = handle;
153
+ this.buf = Buffer.allocUnsafe(bufSize);
154
+ this.len = 0;
155
+ this.flushed = 0;
156
+ this.maxEnd = 0;
157
+ }
158
+
159
+ static async open(path, bufSize = 262144) {
160
+ const handle = await fs.promises.open(path, 'w+');
161
+ return new FileSink(handle, bufSize);
162
+ }
163
+
164
+ get pos() {
165
+ return this.flushed + this.len;
166
+ }
167
+
168
+ get length() {
169
+ return Math.max(this.maxEnd, this.pos);
170
+ }
171
+
172
+ async rawWrite(data, pos) {
173
+ if (pos + data.length > this.maxEnd) this.maxEnd = pos + data.length;
174
+ let off = 0;
175
+ while (off < data.length) {
176
+ const result = await this.handle.write(data, off, data.length - off, pos + off);
177
+ off += result.bytesWritten;
178
+ }
179
+ }
180
+
181
+ async write(data) {
182
+ if (data.length >= this.buf.length) {
183
+ await this.flush();
184
+ await this.rawWrite(data, this.flushed);
185
+ this.flushed += data.length;
186
+ return;
187
+ }
188
+ if (this.len + data.length > this.buf.length) await this.flush();
189
+ data.copy(this.buf, this.len);
190
+ this.len += data.length;
191
+ }
192
+
193
+ async flush() {
194
+ if (this.len > 0) {
195
+ await this.rawWrite(this.buf.subarray(0, this.len), this.flushed);
196
+ this.flushed += this.len;
197
+ this.len = 0;
198
+ }
199
+ }
200
+
201
+ async writeAt(pos, data) {
202
+ await this.flush();
203
+ await this.rawWrite(data, pos);
204
+ }
205
+
206
+ async readAt(buf, off, len, pos) {
207
+ await this.flush();
208
+ const result = await this.handle.read(buf, off, len, pos);
209
+ return result.bytesRead;
210
+ }
211
+
212
+ async truncate(length) {
213
+ await this.flush();
214
+ await this.handle.truncate(length);
215
+ this.flushed = length;
216
+ }
217
+
218
+ async close() {
219
+ await this.flush();
220
+ await this.handle.close();
221
+ }
222
+ }
223
+
224
+ class BufferSink {
225
+ constructor(capacity = 65536) {
226
+ this.buf = Buffer.allocUnsafe(Math.max(65536, capacity));
227
+ this.len = 0;
228
+ }
229
+
230
+ get pos() {
231
+ return this.len;
232
+ }
233
+
234
+ get length() {
235
+ return this.len;
236
+ }
237
+
238
+ async write(data) {
239
+ const need = this.len + data.length;
240
+ if (need > this.buf.length) {
241
+ let cap = this.buf.length;
242
+ while (cap < need) cap *= 2;
243
+ const next = Buffer.allocUnsafe(cap);
244
+ this.buf.copy(next, 0, 0, this.len);
245
+ this.buf = next;
246
+ }
247
+ data.copy(this.buf, this.len);
248
+ this.len += data.length;
249
+ }
250
+
251
+ async flush() {}
252
+
253
+ async writeAt(pos, data) {
254
+ const need = pos + data.length;
255
+ if (need > this.buf.length) {
256
+ let cap = this.buf.length;
257
+ while (cap < need) cap *= 2;
258
+ const next = Buffer.allocUnsafe(cap);
259
+ this.buf.copy(next, 0, 0, this.len);
260
+ this.buf = next;
261
+ }
262
+ data.copy(this.buf, pos);
263
+ if (need > this.len) this.len = need;
264
+ }
265
+
266
+ async readAt(buf, off, len, pos) {
267
+ const n = Math.max(0, Math.min(len, this.len - pos));
268
+ this.buf.copy(buf, off, pos, pos + n);
269
+ return n;
270
+ }
271
+
272
+ async truncate(length) {
273
+ this.len = length;
274
+ }
275
+
276
+ async close() {}
277
+
278
+ result() {
279
+ if (this.buf.length - this.len > Math.max(1048576, Math.floor(this.len / 8))) return Buffer.from(this.buf.subarray(0, this.len));
280
+ return this.buf.subarray(0, this.len);
281
+ }
282
+ }
283
+
284
+ async function openReader(input, windowSize) {
285
+ if (Buffer.isBuffer(input)) return new Reader(new BufferSource(input), windowSize);
286
+ if (input instanceof Uint8Array) return new Reader(new BufferSource(Buffer.from(input.buffer, input.byteOffset, input.byteLength)), windowSize);
287
+ return new Reader(await FileSource.open(input), windowSize);
288
+ }
289
+
290
+ export {
291
+ FileSource,
292
+ BufferSource,
293
+ Reader,
294
+ FileSink,
295
+ BufferSink,
296
+ openReader,
297
+ emptyBuf,
298
+ };
@@ -0,0 +1,75 @@
1
+ import { noSupport, badArg } from '../errors.js';
2
+ import { adtsSampleRates } from '../demux/adts.js';
3
+
4
+ function parseAsc(asc) {
5
+ if (!asc || asc.length < 2) throw noSupport('adts: missing audio specific config');
6
+ let bits = 0;
7
+ let pos = 0;
8
+ const read = (n) => {
9
+ let v = 0;
10
+ for (let i = 0; i < n; i++) {
11
+ const byte = asc[pos >> 3] || 0;
12
+ v = v * 2 + ((byte >> (7 - (pos & 7))) & 1);
13
+ pos++;
14
+ }
15
+ return v;
16
+ };
17
+ let aot = read(5);
18
+ if (aot === 31) aot = 32 + read(6);
19
+ let sfi = read(4);
20
+ if (sfi === 15) {
21
+ const rate = read(24);
22
+ sfi = adtsSampleRates.indexOf(rate);
23
+ if (sfi < 0) throw noSupport('adts: unsupported sample rate');
24
+ }
25
+ const chan = read(4);
26
+ if (aot === 5 || aot === 29) {
27
+ let ext = read(4);
28
+ if (ext === 15) read(24);
29
+ aot = read(5);
30
+ if (aot === 31) aot = 32 + read(6);
31
+ }
32
+ bits = aot;
33
+ return { aot: bits, sfi, chan };
34
+ }
35
+
36
+ class AdtsMuxer {
37
+ constructor(sink, options) {
38
+ this.sink = sink;
39
+ this.cfg = null;
40
+ }
41
+
42
+ static accepts(stream) {
43
+ return stream.type === 'audio' && stream.codec === 'aac';
44
+ }
45
+
46
+ async open(streams) {
47
+ if (streams.length !== 1 || !AdtsMuxer.accepts(streams[0])) throw noSupport('adts output needs exactly one aac audio stream');
48
+ this.cfg = parseAsc(streams[0].extradata);
49
+ if (this.cfg.aot < 1 || this.cfg.aot > 4) throw noSupport('adts: unsupported audio object type ' + this.cfg.aot);
50
+ }
51
+
52
+ async writePacket(index, packet) {
53
+ if (index !== 0) throw badArg('adts: invalid stream index');
54
+ const len = packet.data.length + 7;
55
+ if (len > 0x1fff) throw noSupport('adts: frame too large');
56
+ const c = this.cfg;
57
+ const head = Buffer.alloc(7);
58
+ head[0] = 0xff;
59
+ head[1] = 0xf1;
60
+ head[2] = ((c.aot - 1) << 6) | (c.sfi << 2) | (c.chan >> 2);
61
+ head[3] = ((c.chan & 3) << 6) | ((len >> 11) & 3);
62
+ head[4] = (len >> 3) & 0xff;
63
+ head[5] = ((len & 7) << 5) | 0x1f;
64
+ head[6] = 0xfc;
65
+ await this.sink.write(head);
66
+ await this.sink.write(packet.data);
67
+ }
68
+
69
+ async finish() {}
70
+ }
71
+
72
+ export {
73
+ AdtsMuxer,
74
+ parseAsc,
75
+ };