@torrent-tv/proxy 2.74.0 → 2.75.0

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.
@@ -1,192 +1,192 @@
1
- /**
2
- * @file The container's table names a track, and only the picture's entries are
3
- * cut points.
4
- *
5
- * Measured 2026-08-18 on the two files the field sessions were recorded from:
6
- * `Minions.and.Monsters.1080p.mkv` carries 2778 cue entries for its video track
7
- * — one every 2.002 s — and 4669 more across four subtitle tracks;
8
- * `Moana.2 … MegaPeer.mkv` carries 1055 for video and 5007 across five subtitle
9
- * tracks. Read without the track, both sets went into the cut list together,
10
- * and ffmpeg — which can only cut a copied picture at a real keyframe at or
11
- * after the time it is asked for — moved every such cut forward to the next
12
- * keyframe. That is the whole of the disagreement the field reported: 2.002 s
13
- * on the first file, a median of 6.3 s and a worst case of 21 s on the second,
14
- * and never once negative.
15
- */
16
-
17
- import test from "node:test";
18
- import assert from "node:assert/strict";
19
- import { readMatroskaKeyframeTimes } from "../services/container-index/matroska.js";
20
-
21
- const ID_EBML = 0x1a45dfa3;
22
- const ID_SEGMENT = 0x18538067;
23
- const ID_SEEK_HEAD = 0x114d9b74;
24
- const ID_SEEK = 0x4dbb;
25
- const ID_SEEK_ID = 0x53ab;
26
- const ID_SEEK_POSITION = 0x53ac;
27
- const ID_INFO = 0x1549a966;
28
- const ID_TIMESTAMP_SCALE = 0x2ad7b1;
29
- const ID_TRACKS = 0x1654ae6b;
30
- const ID_TRACK_ENTRY = 0xae;
31
- const ID_TRACK_NUMBER = 0xd7;
32
- const ID_TRACK_TYPE = 0x83;
33
- const ID_CUES = 0x1c53bb6b;
34
- const ID_CUE_POINT = 0xbb;
35
- const ID_CUE_TIME = 0xb3;
36
- const ID_CUE_TRACK_POSITIONS = 0xb7;
37
- const ID_CUE_TRACK = 0xf7;
38
- const ID_CUE_CLUSTER_POSITION = 0xf1;
39
-
40
- /** An element id, as the bytes the specification gives it. */
41
- function idBytes(id) {
42
- const bytes = [];
43
- let rest = id;
44
- while (rest > 0) {
45
- bytes.unshift(rest & 0xff);
46
- rest = Math.floor(rest / 256);
47
- }
48
- return Buffer.from(bytes);
49
- }
50
-
51
- /** A size, as a four-byte EBML variable-length integer. */
52
- function sizeBytes(size) {
53
- const buffer = Buffer.alloc(4);
54
- buffer.writeUInt32BE(size, 0);
55
- buffer[0] |= 0x10;
56
- return buffer;
57
- }
58
-
59
- function element(id, payload) {
60
- return Buffer.concat([idBytes(id), sizeBytes(payload.length), payload]);
61
- }
62
-
63
- /** An unsigned value, in as few bytes as it needs. */
64
- function uintElement(id, value) {
65
- const bytes = [];
66
- let rest = value;
67
- do {
68
- bytes.unshift(rest & 0xff);
69
- rest = Math.floor(rest / 256);
70
- } while (rest > 0);
71
- return element(id, Buffer.from(bytes));
72
- }
73
-
74
- function cuePoint(timeMs, tracks) {
75
- return element(ID_CUE_POINT, Buffer.concat([
76
- uintElement(ID_CUE_TIME, timeMs),
77
- ...tracks.map((track) => element(ID_CUE_TRACK_POSITIONS, Buffer.concat([
78
- uintElement(ID_CUE_TRACK, track),
79
- uintElement(ID_CUE_CLUSTER_POSITION, 4096)
80
- ])))
81
- ]));
82
- }
83
-
84
- /**
85
- * A file with the shape the field files have: one picture, one set of subtitles,
86
- * and a table that indexes both.
87
- *
88
- * @param {{ withTracks?: boolean }} [options]
89
- * @returns {Buffer}
90
- */
91
- function buildFile({ withTracks = true, cueTrack = null } = {}) {
92
- const info = element(ID_INFO, uintElement(ID_TIMESTAMP_SCALE, 1_000_000));
93
- const tracks = element(ID_TRACKS, Buffer.concat([
94
- element(ID_TRACK_ENTRY, Buffer.concat([
95
- uintElement(ID_TRACK_NUMBER, 1),
96
- uintElement(ID_TRACK_TYPE, 1) // video
97
- ])),
98
- element(ID_TRACK_ENTRY, Buffer.concat([
99
- uintElement(ID_TRACK_NUMBER, 2),
100
- uintElement(ID_TRACK_TYPE, 17) // subtitles
101
- ]))
102
- ]));
103
- const forPicture = cueTrack ?? 1;
104
- const forSubtitles = cueTrack ?? 2;
105
- const cues = element(ID_CUES, Buffer.concat([
106
- cuePoint(0, [forPicture]),
107
- cuePoint(1070, [forSubtitles]),
108
- cuePoint(2002, [forPicture]),
109
- cuePoint(3141, [forSubtitles]),
110
- cuePoint(4004, [forPicture])
111
- ]));
112
-
113
- const seekEntry = (targetId, position) => element(ID_SEEK, Buffer.concat([
114
- element(ID_SEEK_ID, idBytes(targetId)),
115
- element(ID_SEEK_POSITION, (() => {
116
- const buffer = Buffer.alloc(4);
117
- buffer.writeUInt32BE(position, 0);
118
- return buffer;
119
- })())
120
- ]));
121
- // Positions are relative to the Segment's payload, so the SeekHead has to be
122
- // measured before they can be stated. Its own length does not change when the
123
- // placeholders become real values: every size and position here is written at
124
- // a fixed width.
125
- const draft = element(ID_SEEK_HEAD, Buffer.concat([
126
- seekEntry(ID_INFO, 0),
127
- ...(withTracks ? [seekEntry(ID_TRACKS, 0)] : []),
128
- seekEntry(ID_CUES, 0)
129
- ]));
130
- const infoAt = draft.length;
131
- const tracksAt = infoAt + info.length;
132
- const cuesAt = withTracks ? tracksAt + tracks.length : infoAt + info.length;
133
- const seekHead = element(ID_SEEK_HEAD, Buffer.concat([
134
- seekEntry(ID_INFO, infoAt),
135
- ...(withTracks ? [seekEntry(ID_TRACKS, tracksAt)] : []),
136
- seekEntry(ID_CUES, cuesAt)
137
- ]));
138
-
139
- const segmentPayload = Buffer.concat(
140
- withTracks ? [seekHead, info, tracks, cues] : [seekHead, info, cues]
141
- );
142
- return Buffer.concat([
143
- element(ID_EBML, Buffer.from([0x42, 0x86, 0x81, 0x01])),
144
- element(ID_SEGMENT, segmentPayload)
145
- ]);
146
- }
147
-
148
- function readerOver(file) {
149
- return async (start, end) => {
150
- const last = Math.min(end, file.length - 1);
151
- return start > last ? null : file.subarray(start, last + 1);
152
- };
153
- }
154
-
155
- test("only the picture's entries become cut times", async () => {
156
- const file = buildFile();
157
-
158
- const times = await readMatroskaKeyframeTimes(readerOver(file), file.length);
159
-
160
- assert.deepEqual(
161
- times.map((time) => Number(time.toFixed(3))),
162
- [0, 2.002, 4.004],
163
- "the subtitle entries at 1.070 and 3.141 are not keyframes, and a cut asked for there lands late"
164
- );
165
- });
166
-
167
- test("a table whose entries name no known track is still used", async () => {
168
- // The cue points reference track 9, which Tracks never declares. Filtering
169
- // leaves nothing — and returning nothing would put an even grid on a copied
170
- // picture, the failure this reader exists to prevent.
171
- const file = buildFile({ cueTrack: 9 });
172
-
173
- const times = await readMatroskaKeyframeTimes(readerOver(file), file.length);
174
-
175
- assert.deepEqual(
176
- times.map((time) => Number(time.toFixed(3))),
177
- [0, 1.07, 2.002, 3.141, 4.004],
178
- "an unrecognised table beats no table at all"
179
- );
180
- });
181
-
182
- test("a file whose tracks cannot be read keeps every entry", async () => {
183
- const file = buildFile({ withTracks: false });
184
-
185
- const times = await readMatroskaKeyframeTimes(readerOver(file), file.length);
186
-
187
- assert.deepEqual(
188
- times.map((time) => Number(time.toFixed(3))),
189
- [0, 1.07, 2.002, 3.141, 4.004],
190
- "with nothing to tell the tracks apart, the old behaviour is the only one available"
191
- );
192
- });
1
+ /**
2
+ * @file The container's table names a track, and only the picture's entries are
3
+ * cut points.
4
+ *
5
+ * Measured 2026-08-18 on the two files the field sessions were recorded from:
6
+ * `Minions.and.Monsters.1080p.mkv` carries 2778 cue entries for its video track
7
+ * — one every 2.002 s — and 4669 more across four subtitle tracks;
8
+ * `Moana.2 … MegaPeer.mkv` carries 1055 for video and 5007 across five subtitle
9
+ * tracks. Read without the track, both sets went into the cut list together,
10
+ * and ffmpeg — which can only cut a copied picture at a real keyframe at or
11
+ * after the time it is asked for — moved every such cut forward to the next
12
+ * keyframe. That is the whole of the disagreement the field reported: 2.002 s
13
+ * on the first file, a median of 6.3 s and a worst case of 21 s on the second,
14
+ * and never once negative.
15
+ */
16
+
17
+ import test from "node:test";
18
+ import assert from "node:assert/strict";
19
+ import { MatroskaContainer } from "../services/container/MatroskaContainer.js";
20
+
21
+ const ID_EBML = 0x1a45dfa3;
22
+ const ID_SEGMENT = 0x18538067;
23
+ const ID_SEEK_HEAD = 0x114d9b74;
24
+ const ID_SEEK = 0x4dbb;
25
+ const ID_SEEK_ID = 0x53ab;
26
+ const ID_SEEK_POSITION = 0x53ac;
27
+ const ID_INFO = 0x1549a966;
28
+ const ID_TIMESTAMP_SCALE = 0x2ad7b1;
29
+ const ID_TRACKS = 0x1654ae6b;
30
+ const ID_TRACK_ENTRY = 0xae;
31
+ const ID_TRACK_NUMBER = 0xd7;
32
+ const ID_TRACK_TYPE = 0x83;
33
+ const ID_CUES = 0x1c53bb6b;
34
+ const ID_CUE_POINT = 0xbb;
35
+ const ID_CUE_TIME = 0xb3;
36
+ const ID_CUE_TRACK_POSITIONS = 0xb7;
37
+ const ID_CUE_TRACK = 0xf7;
38
+ const ID_CUE_CLUSTER_POSITION = 0xf1;
39
+
40
+ /** An element id, as the bytes the specification gives it. */
41
+ function idBytes(id) {
42
+ const bytes = [];
43
+ let rest = id;
44
+ while (rest > 0) {
45
+ bytes.unshift(rest & 0xff);
46
+ rest = Math.floor(rest / 256);
47
+ }
48
+ return Buffer.from(bytes);
49
+ }
50
+
51
+ /** A size, as a four-byte EBML variable-length integer. */
52
+ function sizeBytes(size) {
53
+ const buffer = Buffer.alloc(4);
54
+ buffer.writeUInt32BE(size, 0);
55
+ buffer[0] |= 0x10;
56
+ return buffer;
57
+ }
58
+
59
+ function element(id, payload) {
60
+ return Buffer.concat([idBytes(id), sizeBytes(payload.length), payload]);
61
+ }
62
+
63
+ /** An unsigned value, in as few bytes as it needs. */
64
+ function uintElement(id, value) {
65
+ const bytes = [];
66
+ let rest = value;
67
+ do {
68
+ bytes.unshift(rest & 0xff);
69
+ rest = Math.floor(rest / 256);
70
+ } while (rest > 0);
71
+ return element(id, Buffer.from(bytes));
72
+ }
73
+
74
+ function cuePoint(timeMs, tracks) {
75
+ return element(ID_CUE_POINT, Buffer.concat([
76
+ uintElement(ID_CUE_TIME, timeMs),
77
+ ...tracks.map((track) => element(ID_CUE_TRACK_POSITIONS, Buffer.concat([
78
+ uintElement(ID_CUE_TRACK, track),
79
+ uintElement(ID_CUE_CLUSTER_POSITION, 4096)
80
+ ])))
81
+ ]));
82
+ }
83
+
84
+ /**
85
+ * A file with the shape the field files have: one picture, one set of subtitles,
86
+ * and a table that indexes both.
87
+ *
88
+ * @param {{ withTracks?: boolean }} [options]
89
+ * @returns {Buffer}
90
+ */
91
+ function buildFile({ withTracks = true, cueTrack = null } = {}) {
92
+ const info = element(ID_INFO, uintElement(ID_TIMESTAMP_SCALE, 1_000_000));
93
+ const tracks = element(ID_TRACKS, Buffer.concat([
94
+ element(ID_TRACK_ENTRY, Buffer.concat([
95
+ uintElement(ID_TRACK_NUMBER, 1),
96
+ uintElement(ID_TRACK_TYPE, 1) // video
97
+ ])),
98
+ element(ID_TRACK_ENTRY, Buffer.concat([
99
+ uintElement(ID_TRACK_NUMBER, 2),
100
+ uintElement(ID_TRACK_TYPE, 17) // subtitles
101
+ ]))
102
+ ]));
103
+ const forPicture = cueTrack ?? 1;
104
+ const forSubtitles = cueTrack ?? 2;
105
+ const cues = element(ID_CUES, Buffer.concat([
106
+ cuePoint(0, [forPicture]),
107
+ cuePoint(1070, [forSubtitles]),
108
+ cuePoint(2002, [forPicture]),
109
+ cuePoint(3141, [forSubtitles]),
110
+ cuePoint(4004, [forPicture])
111
+ ]));
112
+
113
+ const seekEntry = (targetId, position) => element(ID_SEEK, Buffer.concat([
114
+ element(ID_SEEK_ID, idBytes(targetId)),
115
+ element(ID_SEEK_POSITION, (() => {
116
+ const buffer = Buffer.alloc(4);
117
+ buffer.writeUInt32BE(position, 0);
118
+ return buffer;
119
+ })())
120
+ ]));
121
+ // Positions are relative to the Segment's payload, so the SeekHead has to be
122
+ // measured before they can be stated. Its own length does not change when the
123
+ // placeholders become real values: every size and position here is written at
124
+ // a fixed width.
125
+ const draft = element(ID_SEEK_HEAD, Buffer.concat([
126
+ seekEntry(ID_INFO, 0),
127
+ ...(withTracks ? [seekEntry(ID_TRACKS, 0)] : []),
128
+ seekEntry(ID_CUES, 0)
129
+ ]));
130
+ const infoAt = draft.length;
131
+ const tracksAt = infoAt + info.length;
132
+ const cuesAt = withTracks ? tracksAt + tracks.length : infoAt + info.length;
133
+ const seekHead = element(ID_SEEK_HEAD, Buffer.concat([
134
+ seekEntry(ID_INFO, infoAt),
135
+ ...(withTracks ? [seekEntry(ID_TRACKS, tracksAt)] : []),
136
+ seekEntry(ID_CUES, cuesAt)
137
+ ]));
138
+
139
+ const segmentPayload = Buffer.concat(
140
+ withTracks ? [seekHead, info, tracks, cues] : [seekHead, info, cues]
141
+ );
142
+ return Buffer.concat([
143
+ element(ID_EBML, Buffer.from([0x42, 0x86, 0x81, 0x01])),
144
+ element(ID_SEGMENT, segmentPayload)
145
+ ]);
146
+ }
147
+
148
+ function readerOver(file) {
149
+ return async (start, end) => {
150
+ const last = Math.min(end, file.length - 1);
151
+ return start > last ? null : file.subarray(start, last + 1);
152
+ };
153
+ }
154
+
155
+ test("only the picture's entries become cut times", async () => {
156
+ const file = buildFile();
157
+
158
+ const times = await MatroskaContainer.readKeyframeTimes(readerOver(file), file.length);
159
+
160
+ assert.deepEqual(
161
+ times.map((time) => Number(time.toFixed(3))),
162
+ [0, 2.002, 4.004],
163
+ "the subtitle entries at 1.070 and 3.141 are not keyframes, and a cut asked for there lands late"
164
+ );
165
+ });
166
+
167
+ test("a table whose entries name no known track is still used", async () => {
168
+ // The cue points reference track 9, which Tracks never declares. Filtering
169
+ // leaves nothing — and returning nothing would put an even grid on a copied
170
+ // picture, the failure this reader exists to prevent.
171
+ const file = buildFile({ cueTrack: 9 });
172
+
173
+ const times = await MatroskaContainer.readKeyframeTimes(readerOver(file), file.length);
174
+
175
+ assert.deepEqual(
176
+ times.map((time) => Number(time.toFixed(3))),
177
+ [0, 1.07, 2.002, 3.141, 4.004],
178
+ "an unrecognised table beats no table at all"
179
+ );
180
+ });
181
+
182
+ test("a file whose tracks cannot be read keeps every entry", async () => {
183
+ const file = buildFile({ withTracks: false });
184
+
185
+ const times = await MatroskaContainer.readKeyframeTimes(readerOver(file), file.length);
186
+
187
+ assert.deepEqual(
188
+ times.map((time) => Number(time.toFixed(3))),
189
+ [0, 1.07, 2.002, 3.141, 4.004],
190
+ "with nothing to tell the tracks apart, the old behaviour is the only one available"
191
+ );
192
+ });
Binary file
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @file The picture's facts, from the two readings that state them.
3
+ *
4
+ * Audio and subtitles have had this reconciliation since their flags were first
5
+ * read from the file. Video never did: every figure the encode is planned from
6
+ * came from ffmpeg's `-i` banner alone, and the `VideoTrack` the container
7
+ * declares was read and then used for nothing but a line in the log — so a file
8
+ * that states its bit depth or its HDR signalling, against a probe that does
9
+ * not print them, disagreed with nobody watching.
10
+ *
11
+ * What each check pins is WHICH reading answers, and why: the size and the
12
+ * frame rate are what the decoder will produce, so the probe answers; the bit
13
+ * depth and the HDR signalling are the file saying how its samples are to be
14
+ * read, so the container answers.
15
+ */
16
+
17
+ import test from "node:test";
18
+ import assert from "node:assert/strict";
19
+
20
+ import { Container } from "../services/container/Container.js";
21
+
22
+ const banner = (fields) => ({ width: null, height: null, fps: null, isHdr: false, bitDepth: null, ...fields });
23
+
24
+ test("with no container reading the probe answers for everything", () => {
25
+ const facts = Container.mergeVideoFacts(
26
+ banner({ width: 1920, height: 1080, fps: 23.976, isHdr: true, bitDepth: 10 }),
27
+ null
28
+ );
29
+ assert.equal(facts.width, 1920);
30
+ assert.equal(facts.height, 1080);
31
+ assert.equal(facts.fps, 23.976);
32
+ assert.equal(facts.isHdr, true);
33
+ assert.equal(facts.bitDepth, 10);
34
+ assert.deepEqual(facts.disagreements, []);
35
+ });
36
+
37
+ test("the size and the frame rate are the probe's, because that is what will be decoded", () => {
38
+ const facts = Container.mergeVideoFacts(
39
+ banner({ width: 1920, height: 1080, fps: 24 }),
40
+ { width: 1440, height: 1080, fps: 25, displayWidth: 1920, displayHeight: 1080 }
41
+ );
42
+ assert.equal(facts.width, 1920, "the ladder and the scale filter are sized to the decoded frame");
43
+ assert.equal(facts.height, 1080);
44
+ assert.equal(facts.fps, 24);
45
+ });
46
+
47
+ test("the bit depth and the HDR signalling are the file's, because the file states them", () => {
48
+ // A ten-bit HEVC whose probe printed neither: this is the case that decides
49
+ // whether tone mapping runs and how the decode cost is priced.
50
+ const facts = Container.mergeVideoFacts(
51
+ banner({ width: 3840, height: 2160, fps: 24 }),
52
+ { width: 3840, height: 2160, bitDepth: 10, isHdr: true }
53
+ );
54
+ assert.equal(facts.bitDepth, 10);
55
+ assert.equal(facts.isHdr, true);
56
+ assert.deepEqual(facts.disagreements, [], "one side saying nothing is not a disagreement");
57
+ });
58
+
59
+ test("a field only the probe states is still answered", () => {
60
+ const facts = Container.mergeVideoFacts(
61
+ banner({ width: 1280, height: 720, fps: 30, bitDepth: 8 }),
62
+ { width: null, height: null, fps: null, bitDepth: null }
63
+ );
64
+ assert.equal(facts.width, 1280);
65
+ assert.equal(facts.bitDepth, 8);
66
+ });
67
+
68
+ test("a real disagreement is reported, with both values and which is which", () => {
69
+ const facts = Container.mergeVideoFacts(
70
+ banner({ width: 1920, height: 1080, bitDepth: 8, isHdr: false }),
71
+ { width: 1280, height: 720, bitDepth: 10, isHdr: true }
72
+ );
73
+ assert.equal(facts.disagreements.length, 3);
74
+ assert.ok(facts.disagreements.some((line) => /width 1280 in the container against 1920 in the probe/.test(line)));
75
+ assert.ok(facts.disagreements.some((line) => /bit depth 10 in the container against 8 in the probe/.test(line)));
76
+ // HDR is not among them, and cannot be: see `mergeVideoFacts`.
77
+ assert.ok(!facts.disagreements.some((line) => /HDR/.test(line)));
78
+ // And the rule still decides: the probe for the size, the file for the rest.
79
+ assert.equal(facts.width, 1920);
80
+ assert.equal(facts.bitDepth, 10);
81
+ assert.equal(facts.isHdr, true);
82
+ });
83
+
84
+ test("the display size is the container's alone — the probe has no such field", () => {
85
+ const facts = Container.mergeVideoFacts(
86
+ banner({ width: 1440, height: 1080 }),
87
+ { width: 1440, height: 1080, displayWidth: 1920, displayHeight: 1080 }
88
+ );
89
+ assert.equal(facts.displayWidth, 1920);
90
+ assert.equal(facts.displayHeight, 1080);
91
+ });
92
+
93
+ test("zero and nonsense are not values", () => {
94
+ const facts = Container.mergeVideoFacts(
95
+ banner({ width: 0, height: 0, fps: 0, bitDepth: 0 }),
96
+ { width: 1920, height: 1080, fps: 24, bitDepth: 8 }
97
+ );
98
+ assert.equal(facts.width, 1920, "a probe that printed nothing does not outrank a file that speaks");
99
+ assert.equal(facts.fps, 24);
100
+ assert.equal(facts.bitDepth, 8);
101
+ assert.deepEqual(facts.disagreements, []);
102
+ });
@@ -1,167 +0,0 @@
1
- /**
2
- * @file Keyframe index for AVI, read without downloading the file.
3
- *
4
- * AVI ends with an `idx1` chunk: one fixed-size entry per stream chunk, each
5
- * carrying a flags word whose keyframe bit says whether that chunk starts a
6
- * keyframe. Frame number times the video stream's frame duration gives the
7
- * time, so the index alone is enough — no media has to be read.
8
- *
9
- * `idx1` lives at the end of the file and the top-level chunk headers state
10
- * their sizes, so it is reached by stepping over headers (typically two hops:
11
- * `LIST hdrl`, `LIST movi`), not by scanning.
12
- *
13
- * Still relevant despite the format's age: older releases are largely XviD in
14
- * AVI, and those are exactly the files that get copied rather than re-encoded.
15
- */
16
-
17
- const HEADER_BYTES = 8;
18
- const PROBE_BYTES = 4096;
19
- // Keyframe flag in an idx1 entry's flags word (AVIIF_KEYFRAME).
20
- const KEYFRAME_FLAG = 0x10;
21
- const IDX1_ENTRY_BYTES = 16;
22
- // Cap on the idx1 read. One entry per chunk, 16 bytes each — a long film runs
23
- // to a few MB; beyond this is not a normal index.
24
- const MAX_IDX1_BYTES = 64 * 1024 * 1024;
25
-
26
- /**
27
- * Whether this looks like AVI: a RIFF container whose form type is `AVI `.
28
- *
29
- * @param {Buffer} head
30
- * @returns {boolean}
31
- */
32
- export function isAvi(head) {
33
- return (
34
- head.length >= 12 &&
35
- head.toString("latin1", 0, 4) === "RIFF" &&
36
- head.toString("latin1", 8, 12) === "AVI "
37
- );
38
- }
39
-
40
- /**
41
- * Microseconds per frame and the video stream's chunk id prefix, from the main
42
- * header. Both live in the `hdrl` list near the file start.
43
- *
44
- * @param {Buffer} head
45
- * @returns {{ microsecondsPerFrame: number } | null}
46
- */
47
- function readMainHeader(head) {
48
- // Top-level: "RIFF" size "AVI " then chunks. `avih` sits inside `LIST hdrl`.
49
- let offset = 12;
50
- while (offset + HEADER_BYTES <= head.length) {
51
- const id = head.toString("latin1", offset, offset + 4);
52
- const size = head.readUInt32LE(offset + 4);
53
- if (size <= 0) {
54
- return null;
55
- }
56
- if (id === "LIST") {
57
- // Descend: list type follows the header, then its own chunks.
58
- const listType = head.toString("latin1", offset + 8, offset + 12);
59
- if (listType === "hdrl") {
60
- let inner = offset + 12;
61
- while (inner + HEADER_BYTES <= Math.min(head.length, offset + 8 + size)) {
62
- const innerId = head.toString("latin1", inner, inner + 4);
63
- const innerSize = head.readUInt32LE(inner + 4);
64
- if (innerSize <= 0) {
65
- return null;
66
- }
67
- if (innerId === "avih" && inner + 8 + 4 <= head.length) {
68
- return { microsecondsPerFrame: head.readUInt32LE(inner + 8) };
69
- }
70
- inner += HEADER_BYTES + innerSize + (innerSize % 2);
71
- }
72
- }
73
- offset += HEADER_BYTES + 4 + (size - 4) + ((size - 4) % 2);
74
- continue;
75
- }
76
- offset += HEADER_BYTES + size + (size % 2);
77
- }
78
- return null;
79
- }
80
-
81
- /**
82
- * Step over top-level chunks to find `idx1`.
83
- *
84
- * @param {(start: number, end: number) => Promise<Buffer | null>} readRange
85
- * @param {number} fileSize
86
- * @returns {Promise<{ offset: number, size: number } | null>}
87
- */
88
- async function findIdx1(readRange, fileSize) {
89
- let offset = 12; // Past "RIFF" size "AVI ".
90
- while (offset + HEADER_BYTES < fileSize) {
91
- const probe = await readRange(offset, Math.min(fileSize - 1, offset + HEADER_BYTES - 1));
92
- if (!probe || probe.length < HEADER_BYTES) {
93
- return null;
94
- }
95
- const id = probe.toString("latin1", 0, 4);
96
- const size = probe.readUInt32LE(4);
97
- if (size <= 0) {
98
- return null;
99
- }
100
- if (id === "idx1") {
101
- return { offset: offset + HEADER_BYTES, size };
102
- }
103
- // Chunks are word-aligned; a LIST carries its type inside the payload, so
104
- // the same size arithmetic covers both cases.
105
- offset += HEADER_BYTES + size + (size % 2);
106
- }
107
- return null;
108
- }
109
-
110
- /**
111
- * Read the keyframe times of an AVI file.
112
- *
113
- * @param {(start: number, end: number) => Promise<Buffer | null>} readRange
114
- * @param {number} fileSize
115
- * @returns {Promise<number[] | null>} Ascending seconds, or null when the file
116
- * has no `idx1` (OpenDML-only index, interrupted write, damaged upload).
117
- */
118
- export async function readAviKeyframeTimes(readRange, fileSize) {
119
- const head = await readRange(0, Math.min(PROBE_BYTES - 1, fileSize - 1));
120
- if (!head || !isAvi(head)) {
121
- return null;
122
- }
123
- const mainHeader = readMainHeader(head);
124
- if (!mainHeader || !mainHeader.microsecondsPerFrame) {
125
- return null;
126
- }
127
-
128
- const idx1 = await findIdx1(readRange, fileSize);
129
- if (!idx1 || idx1.size > MAX_IDX1_BYTES) {
130
- return null;
131
- }
132
-
133
- const table = await readRange(idx1.offset, Math.min(fileSize - 1, idx1.offset + idx1.size - 1));
134
- if (!table || table.length < IDX1_ENTRY_BYTES) {
135
- return null;
136
- }
137
-
138
- const secondsPerFrame = mainHeader.microsecondsPerFrame / 1e6;
139
- const times = [];
140
- let videoFrame = 0;
141
- for (let at = 0; at + IDX1_ENTRY_BYTES <= table.length; at += IDX1_ENTRY_BYTES) {
142
- const chunkId = table.toString("latin1", at, at + 4);
143
- // Video chunks are "##db" (uncompressed) or "##dc" (compressed); audio is
144
- // "##wb" and must not advance the frame counter.
145
- const isVideo = chunkId.endsWith("db") || chunkId.endsWith("dc");
146
- if (!isVideo) {
147
- continue;
148
- }
149
- const flags = table.readUInt32LE(at + 4);
150
- if ((flags & KEYFRAME_FLAG) !== 0) {
151
- times.push(videoFrame * secondsPerFrame);
152
- }
153
- videoFrame += 1;
154
- }
155
- if (times.length === 0) {
156
- return null;
157
- }
158
- // AVI names a keyframe by its FRAME NUMBER, and the time above is that number
159
- // multiplied by the frame duration the header declares. The frames are the
160
- // right ones — measured 2026-08-21 against the files themselves, 1196 index
161
- // entries against 1196 real keyframes and 901 against 901, exactly — but the
162
- // names are 10-44 ms away from the presentation times the demuxer computes,
163
- // always under one frame. So the caller is told how far a time here may be
164
- // from the instant it refers to, and can ask for a seek late enough that it
165
- // still lands on the frame rather than on the one before it.
166
- return { times, tolerance: secondsPerFrame };
167
- }