@dcmjs-org/video 0.0.0-stage → 1.0.0-beta.3

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.
@@ -0,0 +1,231 @@
1
+ // test/eventStream/fromVideo.test.js
2
+ //
3
+ // createVideoEventSource: MP4 → event stream → Part 10 → back to the
4
+ // byte-identical MP4, driven directly against the contract sinks
5
+ // (StreamingPart10Writer) and generators (fromPart10/fromPart10Stream) —
6
+ // the DicomEventStream facade sugar lives with the media wave. Also pins
7
+ // the (7FE0,0003) UV element on the wire (the uint64 total length that
8
+ // makes pad-byte-exact extraction possible) and the streaming fragment
9
+ // layout StreamingPart10Writer produces.
10
+
11
+ import {
12
+ fromPart10,
13
+ fromPart10Stream,
14
+ EventStreamListener,
15
+ NaturalizedListener
16
+ } from "@dcmjs-org/parser";
17
+ import { StreamingPart10Writer } from "@dcmjs-org/generator";
18
+ import { createVideoEventSource } from "../../src/eventStream/fromVideo.js";
19
+ import { extractEncapsulatedVideo } from "../../src/encapsulated/encapsulatedVideo.js";
20
+ import { makeTinyMp4 } from "../utils/makeTinyMp4.js";
21
+
22
+ const H264_HIGH_42 = "1.2.840.10008.1.2.4.104.1";
23
+
24
+ /** MP4 → Part 10 bytes through the event stream (accumulate mode). */
25
+ async function videoToPart10(input, options) {
26
+ const source = await createVideoEventSource(input, options);
27
+ const writer = new StreamingPart10Writer();
28
+ await source.run(writer);
29
+ return writer.toArrayBuffer();
30
+ }
31
+
32
+ /** Part 10 bytes → naturalized dataset with _meta, ready for extraction. */
33
+ async function naturalizedRead(part10) {
34
+ const listener = new NaturalizedListener();
35
+ await fromPart10(part10, listener);
36
+ return { ...listener.result, _meta: listener.meta };
37
+ }
38
+
39
+ /** Find a byte pattern in a Uint8Array; -1 when absent. */
40
+ function indexOfBytes(haystack, needle, from = 0) {
41
+ outer: for (let i = from; i <= haystack.length - needle.length; i++) {
42
+ for (let j = 0; j < needle.length; j++) {
43
+ if (haystack[i + j] !== needle[j]) {
44
+ continue outer;
45
+ }
46
+ }
47
+ return i;
48
+ }
49
+ return -1;
50
+ }
51
+
52
+ describe("createVideoEventSource", () => {
53
+ it("round-trips MP4 → Part 10 → MP4 byte-identically", async () => {
54
+ const mp4 = makeTinyMp4(); // odd payload → exercises the pad byte
55
+ const part10 = await videoToPart10(mp4, {
56
+ overrides: {
57
+ PatientName: "DOE^JANE",
58
+ _meta: { ImplementationVersionName: { Value: ["X"] } }
59
+ },
60
+ fragmentBytes: 512
61
+ });
62
+
63
+ const dataset = await naturalizedRead(part10);
64
+ expect(dataset._meta.TransferSyntaxUID).toBe(H264_HIGH_42);
65
+ // API: the file meta keeps the other _meta keys (VID-USR-2).
66
+ expect(dataset._meta.ImplementationVersionName).toBe("X");
67
+ expect(dataset.Modality).toBe("XC");
68
+ expect([].concat(dataset.PatientName)[0]).toMatchObject({
69
+ Alphabetic: "DOE^JANE"
70
+ });
71
+
72
+ const { bytes, declaredLength } = extractEncapsulatedVideo(dataset);
73
+ expect(declaredLength).toBe(mp4.byteLength);
74
+ expect(Buffer.compare(Buffer.from(bytes), Buffer.from(mp4))).toBe(0);
75
+ });
76
+
77
+ it("round-trips through the streaming reader too", async () => {
78
+ const mp4 = makeTinyMp4();
79
+ const part10 = await videoToPart10(mp4, { fragmentBytes: 256 });
80
+ const listener = new NaturalizedListener();
81
+ await fromPart10Stream(new Uint8Array(part10), listener);
82
+ const { bytes } = extractEncapsulatedVideo({
83
+ ...listener.result,
84
+ _meta: listener.meta
85
+ });
86
+ expect(Buffer.compare(Buffer.from(bytes), Buffer.from(mp4))).toBe(0);
87
+ });
88
+
89
+ it("writes (7FE0,0003) as a UV uint64 carrying the exact stream length", async () => {
90
+ const mp4 = makeTinyMp4();
91
+ const part10 = new Uint8Array(await videoToPart10(mp4));
92
+
93
+ // Explicit VR long-form header: tag E0 7F 03 00, "UV", 2 reserved,
94
+ // 32-bit length 8.
95
+ const header = [
96
+ 0xe0, 0x7f, 0x03, 0x00, 0x55, 0x56, 0x00, 0x00, 8, 0, 0, 0
97
+ ];
98
+ const at = indexOfBytes(part10, header);
99
+ expect(at).toBeGreaterThan(-1);
100
+ const view = new DataView(
101
+ part10.buffer,
102
+ part10.byteOffset + at + header.length,
103
+ 8
104
+ );
105
+ expect(view.getBigUint64(0, true)).toBe(BigInt(mp4.byteLength));
106
+
107
+ // and the naturalized read surfaces the same value
108
+ const dataset = await naturalizedRead(part10);
109
+ const value = Array.isArray(
110
+ dataset.EncapsulatedPixelDataValueTotalLength
111
+ )
112
+ ? dataset.EncapsulatedPixelDataValueTotalLength[0]
113
+ : dataset.EncapsulatedPixelDataValueTotalLength;
114
+ expect(BigInt(value)).toBe(BigInt(mp4.byteLength));
115
+ });
116
+
117
+ it("streams fragments through StreamingPart10Writer with the Sup 225 layout", async () => {
118
+ const mp4 = makeTinyMp4({ mdatLength: 2001 });
119
+ const reader = {
120
+ size: mp4.byteLength,
121
+ read: (offset, length) =>
122
+ Promise.resolve(mp4.subarray(offset, offset + length))
123
+ };
124
+ const source = await createVideoEventSource(reader, {
125
+ fragmentBytes: 1024
126
+ });
127
+ const writer = new StreamingPart10Writer(); // accumulate mode
128
+ await source.run(writer);
129
+ const bytes = new Uint8Array(writer.toArrayBuffer());
130
+ // API: the file meta group does not replace the returned _meta
131
+ // (CORE-USR-13).
132
+ expect(source.dataset._meta).toEqual({
133
+ TransferSyntaxUID: { Value: [H264_HIGH_42] }
134
+ });
135
+
136
+ // Pixel Data header: (7FE0,0010) OB, undefined length.
137
+ const pixelHeader = [
138
+ 0xe0, 0x7f, 0x10, 0x00, 0x4f, 0x42, 0x00, 0x00, 0xff, 0xff, 0xff,
139
+ 0xff
140
+ ];
141
+ const at = indexOfBytes(bytes, pixelHeader);
142
+ expect(at).toBeGreaterThan(-1);
143
+ const view = new DataView(bytes.buffer, bytes.byteOffset);
144
+
145
+ // Empty Basic Offset Table item.
146
+ let cursor = at + pixelHeader.length;
147
+ expect(view.getUint16(cursor, true)).toBe(0xfffe);
148
+ expect(view.getUint16(cursor + 2, true)).toBe(0xe000);
149
+ expect(view.getUint32(cursor + 4, true)).toBe(0);
150
+ cursor += 8;
151
+
152
+ // Fragment items: even lengths, total = payload + 1 pad byte.
153
+ const fragmentLengths = [];
154
+ while (
155
+ view.getUint16(cursor, true) === 0xfffe &&
156
+ view.getUint16(cursor + 2, true) === 0xe000
157
+ ) {
158
+ const length = view.getUint32(cursor + 4, true);
159
+ fragmentLengths.push(length);
160
+ cursor += 8 + length;
161
+ }
162
+ expect(view.getUint16(cursor, true)).toBe(0xfffe);
163
+ expect(view.getUint16(cursor + 2, true)).toBe(0xe0dd);
164
+ expect(view.getUint32(cursor + 4, true)).toBe(0);
165
+
166
+ expect(fragmentLengths.length).toBe(Math.ceil(mp4.byteLength / 1024));
167
+ for (const length of fragmentLengths) {
168
+ expect(length % 2).toBe(0);
169
+ }
170
+ const totalWritten = fragmentLengths.reduce((n, l) => n + l, 0);
171
+ const pad = mp4.byteLength % 2;
172
+ expect(totalWritten).toBe(mp4.byteLength + pad);
173
+
174
+ // and the streamed file reads back to the identical MP4
175
+ const { bytes: recovered } = extractEncapsulatedVideo(
176
+ await naturalizedRead(bytes.buffer)
177
+ );
178
+ expect(Buffer.compare(Buffer.from(recovered), Buffer.from(mp4))).toBe(
179
+ 0
180
+ );
181
+ });
182
+
183
+ it("emits exactly one endDataSet, after the pixel data", async () => {
184
+ const events = [];
185
+ class RecordingListener extends EventStreamListener {
186
+ _baseEndDataSet() {
187
+ events.push(["endDataSet", []]);
188
+ }
189
+ _baseStartBinary(opts) {
190
+ events.push(["startBinary", [opts]]);
191
+ }
192
+ _baseEndBinary() {
193
+ events.push(["endBinary", []]);
194
+ }
195
+ }
196
+ const source = await createVideoEventSource(makeTinyMp4());
197
+ await source.run(new RecordingListener());
198
+
199
+ const ends = events.filter(([type]) => type === "endDataSet");
200
+ expect(ends.length).toBe(1);
201
+ expect(events[events.length - 1][0]).toBe("endDataSet");
202
+ // FileMetaInformationVersion emits a plain binary in the meta group;
203
+ // exactly one ENCAPSULATED binary follows — the pixel data.
204
+ const encapsulatedStarts = events.filter(
205
+ ([type, args]) => type === "startBinary" && args[0]?.encapsulated
206
+ );
207
+ expect(encapsulatedStarts.length).toBe(1);
208
+ });
209
+
210
+ it("honors backpressure between fragments", async () => {
211
+ const mp4 = makeTinyMp4({ mdatLength: 4096 });
212
+ let drains = 0;
213
+ const writer = new StreamingPart10Writer();
214
+ writer.setDrain(() => {
215
+ drains++;
216
+ return Promise.resolve();
217
+ });
218
+ const source = await createVideoEventSource(mp4, {
219
+ fragmentBytes: 1024
220
+ });
221
+ await source.run(writer);
222
+ // one drain checkpoint per fragment, plus the dataset-element ones
223
+ expect(drains).toBeGreaterThanOrEqual(Math.ceil(mp4.byteLength / 1024));
224
+ });
225
+
226
+ it("rejects unsupported codecs with the transcode corrective error", async () => {
227
+ await expect(
228
+ createVideoEventSource(makeTinyMp4({ levelIdc: 51 }))
229
+ ).rejects.toThrow(/ffmpeg/);
230
+ });
231
+ });
@@ -0,0 +1,115 @@
1
+ // test/mp4Info.test.js
2
+ //
3
+ // parseMp4Info: box-walk geometry/timing extraction over synthesized MP4s
4
+ // (makeTinyMp4), so no binary fixtures are committed. The H.264 → transfer
5
+ // syntax mapping parseMp4Info uses is tested in @dcmjs-org/imaging.
6
+
7
+ import { parseMp4Info } from "../src/image/mp4Info.js";
8
+ import { makeTinyMp4 } from "./utils/makeTinyMp4.js";
9
+
10
+ const H264_HIGH_42 = "1.2.840.10008.1.2.4.104.1";
11
+
12
+ describe("parseMp4Info", () => {
13
+ it("reads geometry, frame count, and frame rate (moov at end)", async () => {
14
+ const mp4 = makeTinyMp4();
15
+ const info = await parseMp4Info(mp4);
16
+ expect(info.columns).toBe(64);
17
+ expect(info.rows).toBe(48);
18
+ expect(info.numberOfFrames).toBe(12);
19
+ expect(info.frameRate).toBe(60);
20
+ expect(info.cineRate).toBe(60);
21
+ expect(info.frameTime).toBe("16.666667");
22
+ expect(info.codec).toBe("avc1");
23
+ expect(info.profileIdc).toBe(100);
24
+ expect(info.levelIdc).toBe(42);
25
+ expect(info.transferSyntaxUID).toBe(H264_HIGH_42);
26
+ expect(info.mp4ByteLength).toBe(mp4.byteLength);
27
+ });
28
+
29
+ it("parses the moov-first (web-optimized) layout identically", async () => {
30
+ const atEnd = await parseMp4Info(makeTinyMp4());
31
+ const first = await parseMp4Info(makeTinyMp4({ moovFirst: true }));
32
+ expect(first.rows).toBe(atEnd.rows);
33
+ expect(first.columns).toBe(atEnd.columns);
34
+ expect(first.numberOfFrames).toBe(atEnd.numberOfFrames);
35
+ expect(first.transferSyntaxUID).toBe(atEnd.transferSyntaxUID);
36
+ });
37
+
38
+ it("accepts a random-access reader and reads only what it needs", async () => {
39
+ const mp4 = makeTinyMp4({ mdatLength: 100001 });
40
+ const reads = [];
41
+ const reader = {
42
+ size: mp4.byteLength,
43
+ read: (offset, length) => {
44
+ reads.push(length);
45
+ return Promise.resolve(mp4.subarray(offset, offset + length));
46
+ }
47
+ };
48
+ const info = await parseMp4Info(reader);
49
+ expect(info.columns).toBe(64);
50
+ // Header probes plus one moov read — never the whole file.
51
+ const largest = Math.max(...reads);
52
+ expect(largest).toBeLessThan(mp4.byteLength / 10);
53
+ });
54
+
55
+ it("rejects non-MP4 input with a corrective error", async () => {
56
+ const notMp4 = new Uint8Array(64).fill(0x41);
57
+ await expect(parseMp4Info(notMp4)).rejects.toThrow(/not an MP4/);
58
+ });
59
+
60
+ it("rejects an MP4 with no moov box", async () => {
61
+ const mp4 = makeTinyMp4();
62
+ // ftyp + mdat only: cut the file before the trailing moov.
63
+ const mdatEnd = 24 + 8 + 1001; // ftyp(24) + mdat header + payload
64
+ await expect(parseMp4Info(mp4.subarray(0, mdatEnd))).rejects.toThrow(
65
+ /no moov/
66
+ );
67
+ });
68
+
69
+ it("maps unsupported codecs/levels to a null transfer syntax", async () => {
70
+ const level51 = await parseMp4Info(makeTinyMp4({ levelIdc: 51 }));
71
+ expect(level51.transferSyntaxUID).toBeNull();
72
+
73
+ const hevc = await parseMp4Info(makeTinyMp4({ codec: "hev1" }));
74
+ expect(hevc.transferSyntaxUID).toBeNull();
75
+ expect(hevc.profileIdc).toBeNull();
76
+ });
77
+
78
+ // Review finding 15: the stts fallback loop trusted the raw uint32
79
+ // entry_count. With stsz sample_count 0 and stts entry_count 0x00FFFFFF
80
+ // the unfixed parser spun 16.7 million iterations and fabricated
81
+ // numberOfFrames/frameRate from whatever moov bytes followed the box
82
+ // (at 0xFFFFFFFF, ~40 seconds of blocked thread). The entry count must
83
+ // be bounded by the stts box's own size, and the mismatch must throw.
84
+ it("throws fast on an stts entry_count beyond the box size (finding 15)", async () => {
85
+ const mp4 = makeTinyMp4();
86
+ const find4cc = cc => {
87
+ const target = Array.from(cc, c => c.charCodeAt(0));
88
+ for (let i = 0; i + 4 <= mp4.length; i++) {
89
+ if (
90
+ mp4[i] === target[0] &&
91
+ mp4[i + 1] === target[1] &&
92
+ mp4[i + 2] === target[2] &&
93
+ mp4[i + 3] === target[3]
94
+ ) {
95
+ return i - 4; // box offset (fourCC sits at offset + 4)
96
+ }
97
+ }
98
+ throw new Error(`no ${cc} box in the synthesized MP4`);
99
+ };
100
+ const writeU32 = (offset, value) => {
101
+ mp4[offset] = (value >>> 24) & 0xff;
102
+ mp4[offset + 1] = (value >>> 16) & 0xff;
103
+ mp4[offset + 2] = (value >>> 8) & 0xff;
104
+ mp4[offset + 3] = value & 0xff;
105
+ };
106
+ // stsz: header(8) + version/flags(4) + sample_size(4) → sample_count
107
+ writeU32(find4cc("stsz") + 16, 0);
108
+ // stts: header(8) + version/flags(4) → entry_count
109
+ writeU32(find4cc("stts") + 12, 0x00ffffff);
110
+
111
+ const started = Date.now();
112
+ await expect(parseMp4Info(mp4)).rejects.toThrow(/stts/);
113
+ expect(Date.now() - started).toBeLessThan(2000);
114
+ });
115
+ });
@@ -0,0 +1,240 @@
1
+ // test/utils/makeTinyMp4.js
2
+ //
3
+ // Synthesizes a minimal-but-valid MP4 (ISO BMFF) in memory so the video
4
+ // tests need no committed binary fixture. The moov box carries a real video
5
+ // trak (hdlr "vide", mdhd, stsd with an avc1 VisualSampleEntry + avcC,
6
+ // stts, stsz), which is everything parseMp4Info reads; the mdat payload is
7
+ // deterministic pseudo-random bytes, NOT a decodable H.264 stream — fine,
8
+ // because encapsulation carries the stream verbatim and never decodes it.
9
+ //
10
+ // The default TOTAL file length is guaranteed ODD (a trailing odd-sized
11
+ // `free` box is appended when needed) so the encapsulation pad-byte path is
12
+ // exercised by every round-trip test.
13
+
14
+ function ascii(str) {
15
+ return Array.from(str, c => c.charCodeAt(0));
16
+ }
17
+
18
+ function u16(value) {
19
+ return [(value >> 8) & 0xff, value & 0xff];
20
+ }
21
+
22
+ function u32(value) {
23
+ return [
24
+ (value >>> 24) & 0xff,
25
+ (value >>> 16) & 0xff,
26
+ (value >>> 8) & 0xff,
27
+ value & 0xff
28
+ ];
29
+ }
30
+
31
+ /** A box: 32-bit size + fourCC + payload bytes. */
32
+ function box(type, ...payloads) {
33
+ const payload = payloads.flat();
34
+ return [...u32(8 + payload.length), ...ascii(type), ...payload];
35
+ }
36
+
37
+ /** Deterministic pseudo-random payload (xorshift; no Math.random). */
38
+ function payloadBytes(length, seed = 0x2545f491) {
39
+ const bytes = new Uint8Array(length);
40
+ let state = seed >>> 0;
41
+ for (let i = 0; i < length; i++) {
42
+ state ^= state << 13;
43
+ state ^= state >>> 17;
44
+ state ^= state << 5;
45
+ state >>>= 0;
46
+ bytes[i] = state & 0xff;
47
+ }
48
+ return bytes;
49
+ }
50
+
51
+ /**
52
+ * @param {Object} [options]
53
+ * @param {number} [options.mdatLength=1001] - payload byte count (odd by
54
+ * default, to exercise the encapsulation pad byte)
55
+ * @param {number} [options.width=64]
56
+ * @param {number} [options.height=48]
57
+ * @param {number} [options.frames=12]
58
+ * @param {number} [options.timescale=600]
59
+ * @param {number} [options.sampleDelta=10] - 600/10 = 60 fps
60
+ * @param {number} [options.profileIdc=100] - High
61
+ * @param {number} [options.levelIdc=42] - Level 4.2 → 1.2.840.10008.1.2.4.104.1
62
+ * @param {string} [options.codec="avc1"]
63
+ * @param {boolean} [options.moovFirst=false] - moov before mdat (web-optimized
64
+ * layout) instead of the usual moov-at-end
65
+ * @returns {Uint8Array} the MP4 file bytes
66
+ */
67
+ export function makeTinyMp4(options = {}) {
68
+ const {
69
+ mdatLength = 1001,
70
+ width = 64,
71
+ height = 48,
72
+ frames = 12,
73
+ timescale = 600,
74
+ sampleDelta = 10,
75
+ profileIdc = 100,
76
+ levelIdc = 42,
77
+ codec = "avc1",
78
+ moovFirst = false
79
+ } = options;
80
+
81
+ const duration = frames * sampleDelta;
82
+
83
+ const ftyp = box("ftyp", ascii("isom"), u32(512), ascii("isomavc1"));
84
+
85
+ // avcC: AVCDecoderConfigurationRecord — version, profile, compat, level,
86
+ // then the NAL length-size byte and empty SPS/PPS counts.
87
+ const avcC = box("avcC", [1, profileIdc, 0, levelIdc, 0xff, 0xe0, 0]);
88
+
89
+ // avc1 VisualSampleEntry: 6 reserved + data_reference_index, 16
90
+ // pre_defined/reserved, width/height, resolutions, reserved,
91
+ // frame_count, 32-byte compressorname, depth, pre_defined; then avcC.
92
+ const avc1 = box(
93
+ codec,
94
+ [0, 0, 0, 0, 0, 0],
95
+ u16(1),
96
+ new Array(16).fill(0),
97
+ u16(width),
98
+ u16(height),
99
+ u32(0x00480000),
100
+ u32(0x00480000),
101
+ u32(0),
102
+ u16(1),
103
+ new Array(32).fill(0),
104
+ u16(0x0018),
105
+ u16(0xffff),
106
+ avcC
107
+ );
108
+
109
+ const stsd = box("stsd", u32(0), u32(1), avc1);
110
+ const stts = box("stts", u32(0), u32(1), u32(frames), u32(sampleDelta));
111
+ // stsz with per-sample sizes (sample_size 0 → table follows).
112
+ const sampleSize = Math.floor(mdatLength / frames) || 1;
113
+ const stsz = box(
114
+ "stsz",
115
+ u32(0),
116
+ u32(0),
117
+ u32(frames),
118
+ new Array(frames).fill(u32(sampleSize)).flat()
119
+ );
120
+ const stsc = box("stsc", u32(0), u32(1), u32(1), u32(frames), u32(1));
121
+ const stco = box("stco", u32(0), u32(1), u32(0));
122
+ const stbl = box("stbl", stsd, stts, stsc, stsz, stco);
123
+
124
+ const dref = box(
125
+ "dref",
126
+ u32(0),
127
+ u32(1),
128
+ box("url ", u32(1)) // self-contained
129
+ );
130
+ const dinf = box("dinf", dref);
131
+ const vmhd = box("vmhd", u32(1), new Array(8).fill(0));
132
+ const minf = box("minf", vmhd, dinf, stbl);
133
+
134
+ const hdlr = box(
135
+ "hdlr",
136
+ u32(0),
137
+ u32(0),
138
+ ascii("vide"),
139
+ new Array(12).fill(0),
140
+ ascii("Video\0")
141
+ );
142
+ const mdhd = box(
143
+ "mdhd",
144
+ u32(0), // version 0 + flags
145
+ u32(0), // creation
146
+ u32(0), // modification
147
+ u32(timescale),
148
+ u32(duration),
149
+ u16(0x55c4), // language "und"
150
+ u16(0)
151
+ );
152
+ const mdia = box("mdia", mdhd, hdlr, minf);
153
+
154
+ const tkhd = box(
155
+ "tkhd",
156
+ u32(7), // version 0, flags: enabled/in-movie/in-preview
157
+ u32(0),
158
+ u32(0),
159
+ u32(1), // track id
160
+ u32(0),
161
+ u32(duration),
162
+ new Array(8).fill(0),
163
+ u16(0),
164
+ u16(0),
165
+ u16(0),
166
+ u16(0),
167
+ // identity matrix
168
+ u32(0x00010000),
169
+ u32(0),
170
+ u32(0),
171
+ u32(0),
172
+ u32(0x00010000),
173
+ u32(0),
174
+ u32(0),
175
+ u32(0),
176
+ u32(0x40000000),
177
+ u32(width << 16),
178
+ u32(height << 16)
179
+ );
180
+ const trak = box("trak", tkhd, mdia);
181
+
182
+ const mvhd = box(
183
+ "mvhd",
184
+ u32(0),
185
+ u32(0),
186
+ u32(0),
187
+ u32(timescale),
188
+ u32(duration),
189
+ u32(0x00010000), // rate 1.0
190
+ u16(0x0100), // volume
191
+ u16(0),
192
+ u32(0),
193
+ u32(0),
194
+ // identity matrix
195
+ u32(0x00010000),
196
+ u32(0),
197
+ u32(0),
198
+ u32(0),
199
+ u32(0x00010000),
200
+ u32(0),
201
+ u32(0),
202
+ u32(0),
203
+ u32(0x40000000),
204
+ new Array(24).fill(0), // pre_defined
205
+ u32(2) // next track id
206
+ );
207
+ const moov = box("moov", mvhd, trak);
208
+
209
+ const payload = payloadBytes(mdatLength);
210
+ const mdatHeader = [...u32(8 + mdatLength), ...ascii("mdat")];
211
+
212
+ const parts = moovFirst
213
+ ? [ftyp, moov, mdatHeader, payload]
214
+ : [ftyp, mdatHeader, payload, moov];
215
+
216
+ // Guarantee an odd TOTAL length so encapsulation always needs the pad
217
+ // byte: append a minimal odd-sized free box when the sum lands even.
218
+ const sum = parts.reduce(
219
+ (n, part) => n + (part.length ?? part.byteLength),
220
+ 0
221
+ );
222
+ if (sum % 2 === 0) {
223
+ parts.push([...u32(9), ...ascii("free"), 0]);
224
+ }
225
+
226
+ const total = parts.reduce(
227
+ (n, part) => n + (part.length ?? part.byteLength),
228
+ 0
229
+ );
230
+ const out = new Uint8Array(total);
231
+ let offset = 0;
232
+ for (const part of parts) {
233
+ out.set(
234
+ part instanceof Uint8Array ? part : Uint8Array.from(part),
235
+ offset
236
+ );
237
+ offset += part.length ?? part.byteLength;
238
+ }
239
+ return out;
240
+ }