@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,79 @@
1
+ import { noSupport, badArg } from '../errors.js';
2
+ import { parseStreamInfo, buildStreamInfo, parseFrameHeader, utf8Number } from '../codec/flac.js';
3
+ import { crc8, crc16 } from '../crc.js';
4
+ import { buildVorbisComment } from '../tags.js';
5
+
6
+ class FlacMuxer {
7
+ constructor(sink, options) {
8
+ this.sink = sink;
9
+ this.tags = options.tags || {};
10
+ this.info = null;
11
+ this.samples = 0;
12
+ this.frames = 0;
13
+ this.minFrame = 0;
14
+ this.maxFrame = 0;
15
+ }
16
+
17
+ static accepts(stream) {
18
+ return stream.type === 'audio' && stream.codec === 'flac';
19
+ }
20
+
21
+ async open(streams) {
22
+ if (streams.length !== 1 || !FlacMuxer.accepts(streams[0])) throw noSupport('flac output needs exactly one flac audio stream');
23
+ const s = streams[0];
24
+ this.info = parseStreamInfo(s.extradata);
25
+ this.variable = this.info.minBlockSize !== this.info.maxBlockSize;
26
+ const hasTags = Object.keys(this.tags).length > 0;
27
+ const parts = [Buffer.from('fLaC', 'latin1')];
28
+ const head = Buffer.alloc(4);
29
+ head[0] = hasTags ? 0 : 0x80;
30
+ head.writeUIntBE(34, 1, 3);
31
+ parts.push(head, buildStreamInfo(this.info));
32
+ if (hasTags) {
33
+ const body = buildVorbisComment(this.tags);
34
+ const h = Buffer.alloc(4);
35
+ h[0] = 0x84;
36
+ h.writeUIntBE(body.length, 1, 3);
37
+ parts.push(h, body);
38
+ }
39
+ await this.sink.write(Buffer.concat(parts));
40
+ }
41
+
42
+ async writePacket(index, packet) {
43
+ if (index !== 0) throw badArg('flac: invalid stream index');
44
+ let data = packet.data;
45
+ const hdr = parseFrameHeader(data, 0, data.length, this.info);
46
+ if (hdr) {
47
+ const expected = this.variable ? this.samples : this.frames;
48
+ if (hdr.number !== expected) data = this.renumber(data, hdr, expected);
49
+ }
50
+ const dur = hdr ? hdr.blockSize : packet.duration;
51
+ this.samples += dur;
52
+ this.frames++;
53
+ if (this.minFrame === 0 || data.length < this.minFrame) this.minFrame = data.length;
54
+ if (data.length > this.maxFrame) this.maxFrame = data.length;
55
+ await this.sink.write(data);
56
+ }
57
+
58
+ renumber(data, hdr, number) {
59
+ const oldNum = utf8Number(hdr.number).length;
60
+ const extras = data.subarray(4 + oldNum, hdr.headerLen - 1);
61
+ const head = Buffer.concat([data.subarray(0, 4), utf8Number(number), extras]);
62
+ const out = Buffer.concat([head, Buffer.from([crc8(head, 0, head.length)]), data.subarray(hdr.headerLen, data.length - 2), Buffer.alloc(2)]);
63
+ out.writeUInt16BE(crc16(out, 0, out.length - 2), out.length - 2);
64
+ return out;
65
+ }
66
+
67
+ async finish() {
68
+ const info = Object.assign({}, this.info, {
69
+ minFrameSize: this.minFrame,
70
+ maxFrameSize: this.maxFrame,
71
+ totalSamples: this.samples,
72
+ });
73
+ await this.sink.writeAt(8, buildStreamInfo(info));
74
+ }
75
+ }
76
+
77
+ export {
78
+ FlacMuxer,
79
+ };
@@ -0,0 +1,85 @@
1
+ import { noSupport, badArg } from '../errors.js';
2
+ import { parseMpaHeader, sideInfoSize } from '../codec/mpa.js';
3
+ import { buildId3 } from '../tags.js';
4
+
5
+ class Mp3Muxer {
6
+ constructor(sink, options) {
7
+ this.sink = sink;
8
+ this.tags = options.tags || {};
9
+ this.frames = 0;
10
+ this.bytes = 0;
11
+ this.first = null;
12
+ this.infoPos = -1;
13
+ this.infoOffset = 0;
14
+ this.infoLen = 0;
15
+ this.vbr = false;
16
+ this.started = false;
17
+ this.delay = 0;
18
+ this.padding = 0;
19
+ }
20
+
21
+ static accepts(stream) {
22
+ return stream.type === 'audio' && stream.codec === 'mp3';
23
+ }
24
+
25
+ async open(streams) {
26
+ if (streams.length !== 1 || !Mp3Muxer.accepts(streams[0])) throw noSupport('mp3 output needs exactly one mp3 audio stream');
27
+ this.delay = streams[0].encoderDelay || 0;
28
+ this.padding = streams[0].encoderPadding || 0;
29
+ const id3 = buildId3(this.tags);
30
+ if (id3) await this.sink.write(id3);
31
+ }
32
+
33
+ async writeInfo(h, data) {
34
+ if (h.layer !== 3) return;
35
+ const offset = 4 + sideInfoSize(h);
36
+ let len = h.frameLen - h.padding;
37
+ if (len < offset + 16) return;
38
+ if (this.delay || this.padding) len = Math.max(len, offset + 40);
39
+ if (len > h.frameLen) return;
40
+ const frame = Buffer.alloc(len);
41
+ data.copy(frame, 0, 0, 4);
42
+ frame[1] |= 1;
43
+ frame[2] &= ~2;
44
+ this.infoPos = this.sink.pos;
45
+ this.infoOffset = offset;
46
+ this.infoLen = len;
47
+ await this.sink.write(frame);
48
+ }
49
+
50
+ async writePacket(index, packet) {
51
+ if (index !== 0) throw badArg('mp3: invalid stream index');
52
+ const data = packet.data;
53
+ const h = parseMpaHeader(data, 0);
54
+ if (!this.started) {
55
+ this.started = true;
56
+ this.first = h;
57
+ if (h) await this.writeInfo(h, data);
58
+ }
59
+ if (h && this.first && h.bitrate !== this.first.bitrate) this.vbr = true;
60
+ this.frames++;
61
+ this.bytes += data.length;
62
+ await this.sink.write(data);
63
+ }
64
+
65
+ async finish() {
66
+ if (this.infoPos < 0) return;
67
+ const lame = (this.delay || this.padding) && this.infoLen >= this.infoOffset + 40;
68
+ const body = Buffer.alloc(lame ? 40 : 16);
69
+ body.write(this.vbr ? 'Xing' : 'Info', 0, 'latin1');
70
+ body.writeUInt32BE(3, 4);
71
+ body.writeUInt32BE(this.frames, 8);
72
+ body.writeUInt32BE(this.bytes + this.infoLen, 12);
73
+ if (lame) {
74
+ body.write('LAME3.100', 16, 'latin1');
75
+ body[16 + 21] = (this.delay >> 4) & 0xff;
76
+ body[16 + 22] = ((this.delay & 15) << 4) | ((this.padding >> 8) & 15);
77
+ body[16 + 23] = this.padding & 0xff;
78
+ }
79
+ await this.sink.writeAt(this.infoPos + this.infoOffset, body);
80
+ }
81
+ }
82
+
83
+ export {
84
+ Mp3Muxer,
85
+ };
@@ -0,0 +1,450 @@
1
+ import { noSupport, badArg } from '../errors.js';
2
+ import { Vec } from '../util.js';
3
+ import { buildMp4Meta } from '../tags.js';
4
+ import { parseOpusHead } from '../codec/opus.js';
5
+
6
+ const macEpoch = 2082844800;
7
+ const chunkBytes = 1 << 20;
8
+
9
+ function box(type, ...parts) {
10
+ let len = 8;
11
+ for (const p of parts) len += p.length;
12
+ const out = Buffer.allocUnsafe(len);
13
+ out.writeUInt32BE(len, 0);
14
+ out.write(type, 4, 'latin1');
15
+ let o = 8;
16
+ for (const p of parts) {
17
+ p.copy(out, o);
18
+ o += p.length;
19
+ }
20
+ return out;
21
+ }
22
+
23
+ function fullBox(type, version, flags, ...parts) {
24
+ return box(type, Buffer.from([version, (flags >> 16) & 255, (flags >> 8) & 255, flags & 255]), ...parts);
25
+ }
26
+
27
+ function u32(n) {
28
+ const b = Buffer.alloc(4);
29
+ b.writeUInt32BE(n >>> 0, 0);
30
+ return b;
31
+ }
32
+
33
+ function u16(n) {
34
+ const b = Buffer.alloc(2);
35
+ b.writeUInt16BE(n, 0);
36
+ return b;
37
+ }
38
+
39
+ function descr(tag, payload) {
40
+ const len = payload.length;
41
+ const head = len < 128 ? Buffer.from([tag, len]) : Buffer.from([tag, 0x80 | (len >> 7), len & 0x7f]);
42
+ return Buffer.concat([head, payload]);
43
+ }
44
+
45
+ function esds(oti, dsi, maxRate, avgRate) {
46
+ const dsiDescr = dsi && dsi.length ? descr(0x05, dsi) : Buffer.alloc(0);
47
+ const config = descr(0x04, Buffer.concat([Buffer.from([oti, 0x15, 0, 0, 0]), u32(maxRate), u32(avgRate), dsiDescr]));
48
+ const sl = descr(0x06, Buffer.from([2]));
49
+ return fullBox('esds', 0, 0, descr(0x03, Buffer.concat([u16(0), Buffer.from([0]), config, sl])));
50
+ }
51
+
52
+ function audioHeader(channels, bits, rate) {
53
+ const b = Buffer.alloc(28);
54
+ b.writeUInt16BE(1, 6);
55
+ b.writeUInt16BE(channels, 16);
56
+ b.writeUInt16BE(bits, 18);
57
+ b.writeUInt32BE(rate <= 65535 ? rate * 65536 : 0, 24);
58
+ return b;
59
+ }
60
+
61
+ function sampleEntry(stream) {
62
+ if (stream.mp4Entry) return stream.mp4Entry;
63
+ const rate = stream.sampleRate;
64
+ const bitRate = stream.bitRate || 0;
65
+ if (stream.codec === 'aac') return box('mp4a', audioHeader(stream.channels, 16, rate), esds(0x40, stream.extradata, bitRate, bitRate));
66
+ if (stream.codec === 'mp3') return box('mp4a', audioHeader(stream.channels, 16, rate), esds(0x6b, null, bitRate, bitRate));
67
+ if (stream.codec === 'opus') {
68
+ const head = parseOpusHead(stream.extradata);
69
+ const dops = Buffer.alloc(11);
70
+ dops[1] = head.channels;
71
+ dops.writeUInt16BE(head.preSkip, 2);
72
+ dops.writeUInt32BE(head.inputRate, 4);
73
+ dops.writeInt16BE(head.gain, 8);
74
+ dops[10] = head.family;
75
+ const extra = head.family ? stream.extradata.subarray(19) : Buffer.alloc(0);
76
+ return box('Opus', audioHeader(head.channels, 16, 48000), box('dOps', dops, extra));
77
+ }
78
+ if (stream.codec === 'flac') {
79
+ return box('fLaC', audioHeader(stream.channels, stream.bitsPerSample || 16, rate), fullBox('dfLa', 0, 0, Buffer.from([0x80, 0, 0, 34]), stream.extradata));
80
+ }
81
+ throw noSupport('mp4: cannot write codec ' + stream.codec);
82
+ }
83
+
84
+ class MuxTrack {
85
+ constructor(stream, id) {
86
+ this.stream = stream;
87
+ this.id = id;
88
+ this.timescale = stream.timeScale;
89
+ this.video = stream.type === 'video';
90
+ this.sizes = new Vec(Uint32Array, 1024);
91
+ this.dts = new Vec(Float64Array, 1024);
92
+ this.cto = new Vec(Int32Array, 1024);
93
+ this.sync = new Vec(Uint8Array, 1024);
94
+ this.chunkOffsets = new Vec(Float64Array, 256);
95
+ this.chunkCounts = new Vec(Uint32Array, 256);
96
+ this.hasCto = false;
97
+ this.negCto = false;
98
+ this.allSync = true;
99
+ this.count = 0;
100
+ this.firstDts = 0;
101
+ this.lastDur = 0;
102
+ this.minPts = Infinity;
103
+ this.maxPtsEnd = -Infinity;
104
+ this.pending = [];
105
+ this.pendingBytes = 0;
106
+ this.pendingDur = 0;
107
+ }
108
+ }
109
+
110
+ class Mp4Muxer {
111
+ constructor(sink, options) {
112
+ this.sink = sink;
113
+ this.tags = options.tags || {};
114
+ this.faststart = Boolean(options.faststart);
115
+ this.brand = options.brand || 'mp4';
116
+ this.tracks = [];
117
+ this.mdatStart = 0;
118
+ }
119
+
120
+ static accepts(stream) {
121
+ if (stream.type !== 'audio' && stream.type !== 'video') return false;
122
+ if (stream.mp4Entry) return true;
123
+ return stream.type === 'audio' && ['aac', 'mp3', 'opus', 'flac'].includes(stream.codec);
124
+ }
125
+
126
+ async open(streams) {
127
+ if (!streams.length) throw badArg('mp4: no streams to write');
128
+ for (const s of streams) if (!Mp4Muxer.accepts(s)) throw noSupport('mp4: unsupported stream codec ' + s.codec);
129
+ this.tracks = streams.map((s, i) => new MuxTrack(s, i + 1));
130
+ let major = 'isom';
131
+ let minor = 512;
132
+ let compat = ['isom', 'iso2', 'mp41'];
133
+ if (streams.some((s) => s.codec === 'h264')) compat.splice(2, 0, 'avc1');
134
+ if (this.brand === 'm4a') {
135
+ major = 'M4A ';
136
+ minor = 0;
137
+ compat = ['M4A ', 'mp42', 'isom', '\0\0\0\0'];
138
+ } else if (this.brand === 'mov') {
139
+ major = 'qt ';
140
+ minor = 0;
141
+ compat = ['qt '];
142
+ }
143
+ const ftyp = box('ftyp', Buffer.from(major, 'latin1'), u32(minor), ...compat.map((c) => Buffer.from(c, 'latin1')));
144
+ this.mdatStart = ftyp.length;
145
+ const free = Buffer.alloc(16);
146
+ free.writeUInt32BE(8, 0);
147
+ free.write('free', 4, 'latin1');
148
+ free.writeUInt32BE(8, 8);
149
+ free.write('mdat', 12, 'latin1');
150
+ await this.sink.write(ftyp);
151
+ await this.sink.write(free);
152
+ }
153
+
154
+ async flushChunk(t) {
155
+ if (!t.pending.length) return;
156
+ t.chunkOffsets.push(this.sink.pos);
157
+ t.chunkCounts.push(t.pending.length);
158
+ for (const b of t.pending) await this.sink.write(b);
159
+ t.pending = [];
160
+ t.pendingBytes = 0;
161
+ t.pendingDur = 0;
162
+ }
163
+
164
+ async writePacket(index, packet) {
165
+ const t = this.tracks[index];
166
+ if (!t) throw badArg('mp4: invalid stream index');
167
+ const dts = packet.dts === undefined ? packet.pts : packet.dts;
168
+ const pts = packet.pts === undefined ? dts : packet.pts;
169
+ if (t.count === 0) t.firstDts = dts;
170
+ if (pts < t.minPts) t.minPts = pts;
171
+ if (pts + (packet.duration || 0) > t.maxPtsEnd) t.maxPtsEnd = pts + (packet.duration || 0);
172
+ t.dts.push(dts - t.firstDts);
173
+ const cto = pts - dts;
174
+ t.cto.push(cto);
175
+ if (cto !== 0) t.hasCto = true;
176
+ if (cto < 0) t.negCto = true;
177
+ t.sync.push(packet.key ? 1 : 0);
178
+ if (!packet.key) t.allSync = false;
179
+ t.sizes.push(packet.data.length);
180
+ t.count++;
181
+ t.lastDur = packet.duration || 0;
182
+ t.pending.push(packet.data);
183
+ t.pendingBytes += packet.data.length;
184
+ t.pendingDur += packet.duration || 0;
185
+ if (t.pendingDur >= t.timescale || t.pendingBytes >= chunkBytes) await this.flushChunk(t);
186
+ }
187
+
188
+ trackDuration(t) {
189
+ if (t.count === 0) return 0;
190
+ return t.dts.get(t.count - 1) + t.lastDur;
191
+ }
192
+
193
+ buildTrak(t, delta, use64) {
194
+ const toMovie = (ticks) => Math.round((ticks * 1000) / t.timescale);
195
+ const media = this.trackDuration(t);
196
+ const d0 = t.firstDts;
197
+ const p0 = t.count ? t.minPts : 0;
198
+ const end = t.count ? t.maxPtsEnd : 0;
199
+ let edit = null;
200
+ if (p0 > 0) edit = [[toMovie(p0), -1], [toMovie(end - p0), p0 - d0]];
201
+ else if (d0 !== 0) edit = [[toMovie(end), -d0]];
202
+ const duration = toMovie(Math.max(end, 0));
203
+ const now = Math.floor(Date.now() / 1000) + macEpoch;
204
+ const matrix = Buffer.alloc(36);
205
+ matrix.writeUInt32BE(0x00010000, 0);
206
+ matrix.writeUInt32BE(0x00010000, 16);
207
+ matrix.writeUInt32BE(0x40000000, 32);
208
+ const tkhd = Buffer.alloc(84);
209
+ tkhd[3] = 3;
210
+ tkhd.writeUInt32BE(now, 4);
211
+ tkhd.writeUInt32BE(now, 8);
212
+ tkhd.writeUInt32BE(t.id, 12);
213
+ tkhd.writeUInt32BE(Math.min(duration, 0xffffffff), 20);
214
+ if (!t.video) tkhd.writeUInt16BE(0x0100, 36);
215
+ matrix.copy(tkhd, 40);
216
+ if (t.video) {
217
+ tkhd.writeUInt32BE((t.stream.width || 0) * 65536, 76);
218
+ tkhd.writeUInt32BE((t.stream.height || 0) * 65536, 80);
219
+ }
220
+ const parts = [box('tkhd', tkhd)];
221
+ if (edit) {
222
+ const wide = edit.some((e) => e[0] > 0x7fffffff || e[1] > 0x7fffffff);
223
+ const body = Buffer.alloc(4 + edit.length * (wide ? 20 : 12));
224
+ body.writeUInt32BE(edit.length, 0);
225
+ let p = 4;
226
+ for (const [seg, mt] of edit) {
227
+ if (wide) {
228
+ body.writeUInt32BE(Math.floor(seg / 4294967296), p);
229
+ body.writeUInt32BE(seg >>> 0, p + 4);
230
+ body.writeBigInt64BE(BigInt(mt), p + 8);
231
+ body.writeInt16BE(1, p + 16);
232
+ p += 20;
233
+ } else {
234
+ body.writeUInt32BE(seg, p);
235
+ body.writeInt32BE(mt, p + 4);
236
+ body.writeInt16BE(1, p + 8);
237
+ p += 12;
238
+ }
239
+ }
240
+ parts.push(box('edts', fullBox('elst', wide ? 1 : 0, 0, body)));
241
+ }
242
+ const mdhdWide = media > 0xffffffff;
243
+ const mdhdBody = Buffer.alloc(mdhdWide ? 36 : 20);
244
+ if (mdhdWide) {
245
+ mdhdBody.writeUInt32BE(now, 4);
246
+ mdhdBody.writeUInt32BE(now, 12);
247
+ mdhdBody.writeUInt32BE(t.timescale, 16);
248
+ mdhdBody.writeUInt32BE(Math.floor(media / 4294967296), 20);
249
+ mdhdBody.writeUInt32BE(media >>> 0, 24);
250
+ mdhdBody.writeUInt16BE(0x55c4, 28);
251
+ } else {
252
+ mdhdBody.writeUInt32BE(now, 0);
253
+ mdhdBody.writeUInt32BE(now, 4);
254
+ mdhdBody.writeUInt32BE(t.timescale, 8);
255
+ mdhdBody.writeUInt32BE(media, 12);
256
+ mdhdBody.writeUInt16BE(0x55c4, 16);
257
+ }
258
+ const name = Buffer.from(t.video ? 'VideoHandler\0' : 'SoundHandler\0', 'latin1');
259
+ const hdlr = fullBox('hdlr', 0, 0, Buffer.alloc(4), Buffer.from(t.video ? 'vide' : 'soun', 'latin1'), Buffer.alloc(12), name);
260
+ const dinf = box('dinf', fullBox('dref', 0, 0, u32(1), fullBox('url ', 0, 1)));
261
+ const mediaHeader = t.video ? fullBox('vmhd', 0, 1, Buffer.alloc(8)) : fullBox('smhd', 0, 0, Buffer.alloc(4));
262
+ const n = t.count;
263
+ const dts = t.dts.view();
264
+ const stts = [];
265
+ for (let i = 0; i < n; i++) {
266
+ const d = i + 1 < n ? dts[i + 1] - dts[i] : t.lastDur;
267
+ const last = stts[stts.length - 1];
268
+ if (last && last[1] === d) last[0]++;
269
+ else stts.push([1, d]);
270
+ }
271
+ const sttsBuf = Buffer.alloc(4 + stts.length * 8);
272
+ sttsBuf.writeUInt32BE(stts.length, 0);
273
+ stts.forEach((e, i) => {
274
+ sttsBuf.writeUInt32BE(e[0], 4 + i * 8);
275
+ sttsBuf.writeUInt32BE(e[1] >>> 0, 8 + i * 8);
276
+ });
277
+ const stblParts = [fullBox('stsd', 0, 0, u32(1), sampleEntry(t.stream)), fullBox('stts', 0, 0, sttsBuf)];
278
+ if (t.hasCto) {
279
+ const cto = t.cto.view();
280
+ const runs = [];
281
+ for (let i = 0; i < n; i++) {
282
+ const last = runs[runs.length - 1];
283
+ if (last && last[1] === cto[i]) last[0]++;
284
+ else runs.push([1, cto[i]]);
285
+ }
286
+ const buf = Buffer.alloc(4 + runs.length * 8);
287
+ buf.writeUInt32BE(runs.length, 0);
288
+ runs.forEach((e, i) => {
289
+ buf.writeUInt32BE(e[0], 4 + i * 8);
290
+ buf.writeInt32BE(e[1], 8 + i * 8);
291
+ });
292
+ stblParts.push(fullBox('ctts', t.negCto ? 1 : 0, 0, buf));
293
+ }
294
+ if (!t.allSync) {
295
+ const sync = t.sync.view();
296
+ let c = 0;
297
+ for (let i = 0; i < n; i++) if (sync[i]) c++;
298
+ const buf = Buffer.alloc(4 + c * 4);
299
+ buf.writeUInt32BE(c, 0);
300
+ let p = 4;
301
+ for (let i = 0; i < n; i++) if (sync[i]) {
302
+ buf.writeUInt32BE(i + 1, p);
303
+ p += 4;
304
+ }
305
+ stblParts.push(fullBox('stss', 0, 0, buf));
306
+ }
307
+ const counts = t.chunkCounts.view();
308
+ const stsc = [];
309
+ for (let i = 0; i < counts.length; i++) {
310
+ const last = stsc[stsc.length - 1];
311
+ if (!last || last[1] !== counts[i]) stsc.push([i + 1, counts[i]]);
312
+ }
313
+ const stscBuf = Buffer.alloc(4 + stsc.length * 12);
314
+ stscBuf.writeUInt32BE(stsc.length, 0);
315
+ stsc.forEach((e, i) => {
316
+ stscBuf.writeUInt32BE(e[0], 4 + i * 12);
317
+ stscBuf.writeUInt32BE(e[1], 8 + i * 12);
318
+ stscBuf.writeUInt32BE(1, 12 + i * 12);
319
+ });
320
+ stblParts.push(fullBox('stsc', 0, 0, stscBuf));
321
+ const sizes = t.sizes.view();
322
+ let uniform = n > 0;
323
+ for (let i = 1; i < n && uniform; i++) if (sizes[i] !== sizes[0]) uniform = false;
324
+ let stszBuf;
325
+ if (uniform) {
326
+ stszBuf = Buffer.alloc(8);
327
+ stszBuf.writeUInt32BE(sizes[0], 0);
328
+ stszBuf.writeUInt32BE(n, 4);
329
+ } else {
330
+ stszBuf = Buffer.alloc(8 + n * 4);
331
+ stszBuf.writeUInt32BE(n, 4);
332
+ for (let i = 0; i < n; i++) stszBuf.writeUInt32BE(sizes[i], 8 + i * 4);
333
+ }
334
+ stblParts.push(fullBox('stsz', 0, 0, stszBuf));
335
+ const offs = t.chunkOffsets.view();
336
+ if (use64) {
337
+ const buf = Buffer.alloc(4 + offs.length * 8);
338
+ buf.writeUInt32BE(offs.length, 0);
339
+ for (let i = 0; i < offs.length; i++) {
340
+ const v = offs[i] + delta;
341
+ buf.writeUInt32BE(Math.floor(v / 4294967296), 4 + i * 8);
342
+ buf.writeUInt32BE(v >>> 0, 8 + i * 8);
343
+ }
344
+ stblParts.push(fullBox('co64', 0, 0, buf));
345
+ } else {
346
+ const buf = Buffer.alloc(4 + offs.length * 4);
347
+ buf.writeUInt32BE(offs.length, 0);
348
+ for (let i = 0; i < offs.length; i++) buf.writeUInt32BE(offs[i] + delta, 4 + i * 4);
349
+ stblParts.push(fullBox('stco', 0, 0, buf));
350
+ }
351
+ const minf = box('minf', mediaHeader, dinf, box('stbl', ...stblParts));
352
+ parts.push(box('mdia', fullBox('mdhd', mdhdWide ? 1 : 0, 0, mdhdBody), hdlr, minf));
353
+ return { trak: box('trak', ...parts), duration };
354
+ }
355
+
356
+ buildMoov(delta, use64) {
357
+ const traks = [];
358
+ let movieDuration = 0;
359
+ for (const t of this.tracks) {
360
+ const r = this.buildTrak(t, delta, use64);
361
+ traks.push(r.trak);
362
+ if (r.duration > movieDuration) movieDuration = r.duration;
363
+ }
364
+ const now = Math.floor(Date.now() / 1000) + macEpoch;
365
+ const mvhd = Buffer.alloc(96);
366
+ mvhd.writeUInt32BE(now, 0);
367
+ mvhd.writeUInt32BE(now, 4);
368
+ mvhd.writeUInt32BE(1000, 8);
369
+ mvhd.writeUInt32BE(Math.min(movieDuration, 0xffffffff), 12);
370
+ mvhd.writeUInt32BE(0x00010000, 16);
371
+ mvhd.writeUInt16BE(0x0100, 20);
372
+ mvhd.writeUInt32BE(0x00010000, 32);
373
+ mvhd.writeUInt32BE(0x00010000, 48);
374
+ mvhd.writeUInt32BE(0x40000000, 64);
375
+ mvhd.writeUInt32BE(this.tracks.length + 1, 92);
376
+ const udta = buildMp4Meta(this.tags);
377
+ const parts = [fullBox('mvhd', 0, 0, mvhd), ...traks];
378
+ if (udta) parts.push(udta);
379
+ return box('moov', ...parts);
380
+ }
381
+
382
+ maxOffset() {
383
+ let max = 0;
384
+ for (const t of this.tracks) {
385
+ const offs = t.chunkOffsets.view();
386
+ for (let i = 0; i < offs.length; i++) if (offs[i] > max) max = offs[i];
387
+ }
388
+ return max;
389
+ }
390
+
391
+ async finish() {
392
+ for (const t of this.tracks) await this.flushChunk(t);
393
+ const sink = this.sink;
394
+ const dataStart = this.mdatStart + 16;
395
+ const dataLen = sink.pos - dataStart;
396
+ const large = dataLen + 8 > 0xffffffff;
397
+ if (large) {
398
+ const head = Buffer.alloc(16);
399
+ head.writeUInt32BE(1, 0);
400
+ head.write('mdat', 4, 'latin1');
401
+ head.writeUInt32BE(Math.floor((dataLen + 16) / 4294967296), 8);
402
+ head.writeUInt32BE((dataLen + 16) >>> 0, 12);
403
+ await sink.writeAt(this.mdatStart, head);
404
+ } else {
405
+ const head = Buffer.alloc(8);
406
+ head.writeUInt32BE(dataLen + 8, 0);
407
+ head.write('mdat', 4, 'latin1');
408
+ await sink.writeAt(this.mdatStart + 8, head);
409
+ }
410
+ const maxOff = this.maxOffset();
411
+ if (!this.faststart) {
412
+ const use64 = maxOff > 0xffffffff;
413
+ await sink.write(this.buildMoov(0, use64));
414
+ return;
415
+ }
416
+ const oldStart = large ? this.mdatStart : this.mdatStart + 8;
417
+ const regionLen = sink.pos - oldStart;
418
+ let use64 = false;
419
+ let moov = this.buildMoov(0, use64);
420
+ for (let guard = 0; guard < 4; guard++) {
421
+ const delta = moov.length - (large ? 0 : 8);
422
+ const need64 = maxOff + delta > 0xffffffff;
423
+ const next = this.buildMoov(delta, use64 || need64);
424
+ const stable = next.length === moov.length && (use64 || need64) === use64;
425
+ use64 = use64 || need64;
426
+ moov = next;
427
+ if (stable) break;
428
+ }
429
+ const shift = moov.length - (large ? 0 : 8);
430
+ const buf = Buffer.allocUnsafe(chunkBytes);
431
+ let end = oldStart + regionLen;
432
+ while (end > oldStart) {
433
+ const start = Math.max(oldStart, end - buf.length);
434
+ const len = end - start;
435
+ let got = 0;
436
+ while (got < len) {
437
+ const n = await sink.readAt(buf, got, len - got, start + got);
438
+ if (n <= 0) break;
439
+ got += n;
440
+ }
441
+ await sink.writeAt(start + shift, buf.subarray(0, len));
442
+ end = start;
443
+ }
444
+ await sink.writeAt(this.mdatStart, moov);
445
+ }
446
+ }
447
+
448
+ export {
449
+ Mp4Muxer,
450
+ };