@torrent-tv/proxy 2.89.6 → 2.89.8

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 (92) hide show
  1. package/AGENTS.md +32 -12
  2. package/CHANGELOG.md +2340 -2330
  3. package/assets/calibration/audio/NOTICE.md +19 -19
  4. package/assets/calibration/audio/manifest.json +98 -98
  5. package/biome.json +412 -412
  6. package/docs/browser-proxy-contract.md +155 -155
  7. package/docs/container-architecture.md +273 -273
  8. package/docs/encode-run-state.md +1 -1
  9. package/docs/playback-start-forecast.md +113 -98
  10. package/package.json +51 -50
  11. package/routes/api/sources/files/get.js +106 -106
  12. package/scripts/build-audio-samples.mjs +31 -31
  13. package/services/encode/EncodeRun.js +67 -15
  14. package/services/encode/EncodeRuns.js +19 -7
  15. package/services/encode/OutputOpening.js +784 -784
  16. package/services/encode/audio-calibration.js +67 -67
  17. package/services/encode/audio-work-rate.js +15 -15
  18. package/services/encode/encode-exit.js +2 -0
  19. package/services/encode/hwaccel.js +1894 -1894
  20. package/services/encode/output/index.js +24 -24
  21. package/services/encode/piece-completeness.js +60 -2
  22. package/services/encode/run-command.js +757 -755
  23. package/services/encode/segment-formats/index.js +1 -0
  24. package/services/encode/segment-formats/mp4-boxes.js +8 -1
  25. package/services/media/ContainerOrchestrator.js +202 -202
  26. package/services/media/KeyframeTables.js +356 -356
  27. package/services/media/SubtitleCues.js +592 -592
  28. package/services/media/audio-inventory.js +299 -299
  29. package/services/media/container/AviContainer.js +268 -268
  30. package/services/media/container/Container.js +632 -632
  31. package/services/media/container/ContainerFactory.js +38 -38
  32. package/services/media/container/MatroskaContainer.js +1031 -1031
  33. package/services/media/container/Mp4Container.js +1354 -1354
  34. package/services/media/container/SubtitleFileContainer.js +339 -339
  35. package/services/media/container/ebml-stream.js +174 -174
  36. package/services/media/container/matroska-clusters.js +1165 -1165
  37. package/services/media/container/unavailable.js +77 -77
  38. package/services/media/tracks/ContainerTrack.js +84 -84
  39. package/services/media/tracks/TextSubtitleTrack.js +295 -295
  40. package/services/storage/piece-store/shared-piece-store.js +1937 -1937
  41. package/services/storage/segment-store/SegmentStore.js +1294 -1294
  42. package/services/torrent/Contents.js +382 -382
  43. package/services/torrent/episode-naming.js +182 -182
  44. package/services/torrent/torrent-pool.js +2688 -2688
  45. package/services/torrent/worker/client.js +836 -836
  46. package/services/torrent/worker/held-bytes.js +231 -231
  47. package/services/torrent/worker/worker.js +1137 -1137
  48. package/services/transport/data-channel-handler.js +1373 -1373
  49. package/services/viewer/PriorityMap.js +421 -421
  50. package/test/audio-calibration.test.js +23 -23
  51. package/test/auto-quality-step.test.js +762 -762
  52. package/test/coalesce.test.js +39 -39
  53. package/test/coverage-follows-the-disk.test.js +5 -0
  54. package/test/decode-cost.test.js +475 -475
  55. package/test/encode-run.test.js +58 -0
  56. package/test/episode-naming.test.js +131 -131
  57. package/test/failed-encoder-still-serves-what-exists.test.js +1 -1
  58. package/test/fixtures/audio-frame-boundary.json +1 -1
  59. package/test/fixtures/refused-audio-20261002.json +10 -0
  60. package/test/fmp4-presentation-clock.test.js +4 -2
  61. package/test/format-keyed-outputs.test.js +78 -78
  62. package/test/health-metrics.test.js +11 -13
  63. package/test/held-read-ownership.test.js +77 -77
  64. package/test/helpers/encode-run.js +14 -6
  65. package/test/helpers/held-file.js +77 -77
  66. package/test/helpers/manager.js +62 -62
  67. package/test/helpers/matroska-file.js +296 -296
  68. package/test/keyframe-table-budget.test.js +123 -123
  69. package/test/matroska-cluster-discovery.test.js +323 -323
  70. package/test/one-output-one-session.test.js +273 -273
  71. package/test/output-speed.test.js +6 -1
  72. package/test/piece-completeness.test.js +37 -1
  73. package/test/quality-variants.test.js +1274 -1270
  74. package/test/rate-control-in-the-output.test.js +4 -3
  75. package/test/reads-not-yet-arrived.test.js +218 -218
  76. package/test/seek-frees-the-viewers-requests.test.js +1 -1
  77. package/test/segment-closed-on-both-branches.test.js +114 -114
  78. package/test/segment-judged-by-its-own-header.test.js +222 -222
  79. package/test/segment-serve-wiring.test.js +481 -481
  80. package/test/serving-existing-output.test.js +111 -111
  81. package/test/source-files-route.test.js +113 -113
  82. package/test/subtitle-cue-walk.test.js +385 -385
  83. package/test/subtitle-metadata.test.js +15 -15
  84. package/test/subtitle-plan-waits.test.js +125 -125
  85. package/test/subtitle-track-numbering.test.js +391 -391
  86. package/test/two-viewers-one-picture.test.js +508 -508
  87. package/test/viewer-requests-admission.test.js +92 -92
  88. package/test/viewer-starts-on-map.test.js +27 -27
  89. package/test/viewer-states.test.js +5 -2
  90. package/test/viewing-generations.test.js +390 -390
  91. package/test/whole-file-held-read.test.js +30 -30
  92. package/utils/coalesce.js +41 -41
@@ -1,421 +1,421 @@
1
- /**
2
- * @file THE PRIORITY MAP — what one viewer needs, what all of them need
3
- * together, and in what order the work should be taken.
4
- *
5
- * A layer of its own, below both orchestrators and depending on nothing. It
6
- * knows ONLY priorities: what is downloaded is the download orchestrator's own
7
- * knowledge, what is encoded is the encoding orchestrator's, and neither is
8
- * visible from here. Both read this and recompute their own on every change.
9
- *
10
- * The shape, stated by the user 2026-09-05:
11
- *
12
- * > Usually you make a map for each viewer, then merge the maps, then decide
13
- * > the best way of filling it given the encoders available, where they are now
14
- * > and how many there are.
15
- *
16
- * Three questions, and this file answers the first two. The third — the filling
17
- * — belongs to whoever holds the encoders, and it is handed the merged map
18
- * instead of a list of windows.
19
- *
20
- * **ONE PRIORITISATION, TWO CONSUMERS.** Downloading and encoding keep
21
- * different STATES — made / being made / free for one; downloaded / arriving,
22
- * and which peers hold it at what speed, for the other — but they must agree
23
- * about what matters first, or the swarm fetches what the encoder will not
24
- * reach for another twenty minutes. That agreement is this map.
25
- *
26
- * **THE UNIT IS SECONDS OF FILM.** A map is a set of stretches with sizes and a
27
- * length of its own, so it needs a unit, and seconds are the only one every
28
- * term of the arithmetic is already stated in: encode speed is a ratio of
29
- * seconds to seconds, the measured allowance below which an interruption
30
- * reaches a viewer is seconds, the viewer's position is seconds, the film's
31
- * length is seconds. Bytes cannot serve — how many a second costs is not known
32
- * when a file is opened and is not constant across it, and a soundtrack in a
33
- * file of its own has bytes of its own. Segment numbers cannot serve either:
34
- * they exist only once a cut grid is read, and two outputs of one film number
35
- * differently.
36
- *
37
- * **What this file must NOT know**, and the boundary is the point: nothing about
38
- * containers, cut grids, pieces or bytes. Turning a stretch of seconds into the
39
- * bytes of one track is the container's and the track's business, by whatever
40
- * means suit that file — a Cues table, a sample table, or a walk when the file
41
- * carries neither, which is the same answer they already give in order to play
42
- * it at all. Getting those bytes is the downloader's business; making segments
43
- * out of them is the encoder's.
44
- */
45
-
46
- /**
47
- * THE MAP ITSELF: one number per second of film.
48
- *
49
- * Literally an array as long as the film, where the value at second `x` says how
50
- * urgently that second is wanted. Stated by the user 2026-09-06, and it replaced
51
- * a list of stretches each carrying two numbers.
52
- *
53
- * Two arrays rather than one, because two different questions are asked of the
54
- * map and only one of them can be answered by a rank:
55
- *
56
- * - `priority` orders the work. Only the ORDER between values is meaningful;
57
- * the scale below says what the numbers separate;
58
- * - `secondsUntilPlayed` is a quantity, and it is what makes lateness
59
- * computable at all: whoever fills the map compares "when is this needed"
60
- * against "when would it arrive", and only the second half is theirs to work
61
- * out. `Infinity` where nobody is on their way.
62
- *
63
- * @typedef {object} PriorityMap
64
- * @property {number} durationSeconds - The film's length, in whole seconds.
65
- * @property {Uint8Array} priority - One entry per second. Zero means nothing is
66
- * wanted there, which happens only where nobody is watching at all.
67
- * @property {Float64Array} secondsUntilPlayed - One entry per second.
68
- * @property {Uint8Array} behind - One entry per second, 1 where the second lies
69
- * behind EVERY viewer. Stated rather than worked out from the other two,
70
- * because working it out means knowing this file's scale, and the consumers
71
- * are in other layers. Inferred from the absence of a time, as it was, it was
72
- * wrong for a stopped viewer: their whole film carries no time, so the film in
73
- * front of them counted as behind them and the encoders wandered to the start
74
- * of the file.
75
- */
76
-
77
- /**
78
- * A stretch of the map with one value throughout — the same facts said as a
79
- * range instead of as a run of equal entries.
80
- *
81
- * @typedef {object} DemandZone
82
- * @property {number} from - First second, inclusive.
83
- * @property {number} to - Last second, exclusive.
84
- * @property {number} priority
85
- * @property {number} withinSeconds
86
- * @property {boolean} behind - Whether this lies behind every viewer.
87
- */
88
-
89
- /**
90
- * THE SCALE. Three bands, and the order between them is the whole of what the
91
- * numbers claim.
92
- *
93
- * 1. IN FRONT OF SOMEBODY WHO IS WATCHING — the top value at the second they
94
- * are about to see, falling as the film gets further from them;
95
- * 2. IN FRONT OF SOMEBODY WHO HAS STOPPED — the same shape, and every value of
96
- * it below every value of band 1. A stopped viewer will watch this film when
97
- * they press play, so it is still in front of them; nobody is waiting for it
98
- * now, so it yields to anybody who is;
99
- * 3. BEHIND EVERYBODY — reachable only by a seek back, and nothing measures how
100
- * likely that is, so it is one value rather than a shape.
101
- *
102
- * IN FRONT ALWAYS OUTRANKS BEHIND, at any distance and whoever is stopped. The
103
- * bands make that true by construction rather than by a comparison somebody has
104
- * to remember to write.
105
- *
106
- * The values inside a band are AN ENCODING OF AN ORDER, not a measurement:
107
- * every consumer asks only which of two seconds comes first, so any strictly
108
- * decreasing shape does the same work, and none of these numbers claims
109
- * anything about the world.
110
- */
111
- export const AT_A_WATCHING_VIEWER = 100;
112
- const WATCHING_FLOOR = 70;
113
- const AT_A_STOPPED_VIEWER = 69;
114
- const STOPPED_FLOOR = 39;
115
-
116
- /** Behind everybody. */
117
- export const NOBODY_IS_COMING = 1;
118
-
119
- /** Nothing is wanted here at all. */
120
- const NOTHING = 0;
121
-
122
- /**
123
- * Does this value mean "behind every viewer"?
124
- *
125
- * A read of the scale, so that nobody has to infer the side from the absence of
126
- * a deadline. Inferred that way it was wrong for a stopped viewer, whose whole
127
- * film carries no deadline: the film in front of them then counted as behind
128
- * them, and the encoders were free to wander to the start of the file.
129
- *
130
- * @param {number} priority
131
- * @returns {boolean}
132
- */
133
- export function isBehindEverybody(priority) {
134
- return priority <= NOBODY_IS_COMING;
135
- }
136
-
137
- /**
138
- * Is this second the one a viewer is about to watch?
139
- *
140
- * The top step of the watching band: the film under their feet and the measured
141
- * allowance in front of it, which is the depth below which an interruption
142
- * reaches them.
143
- *
144
- * @param {number} priority
145
- * @returns {boolean}
146
- */
147
- export function isAtAWatchingViewer(priority) {
148
- return priority >= AT_A_WATCHING_VIEWER;
149
- }
150
-
151
- /**
152
- * Is this second in front of somebody who has STOPPED, and of nobody who is
153
- * watching?
154
- *
155
- * Wanted, and wanted after everything anybody is walking towards: they will see
156
- * it when they press play, and nothing here knows when that is.
157
- *
158
- * @param {number} priority
159
- * @returns {boolean}
160
- */
161
- export function isNobodyComingNow(priority) {
162
- return priority > NOBODY_IS_COMING && priority <= AT_A_STOPPED_VIEWER;
163
- }
164
-
165
- /**
166
- * How far into its band a second sits, given its distance from the viewer.
167
- *
168
- * The step doubles: near the viewer the difference between now and ten seconds
169
- * away decides what is made first, while twenty minutes out the difference
170
- * between twenty and twenty-one minutes changes nothing. The first step is the
171
- * MEASURED allowance for this file on this swarm — the depth below which an
172
- * interruption reaches the viewer — so how finely the map divides comes from a
173
- * measurement rather than from a number chosen here.
174
- *
175
- * @param {number} distanceSeconds
176
- * @param {number} allowanceSeconds
177
- * @returns {number} Zero at the viewer, growing with distance.
178
- */
179
- function stepsAway(distanceSeconds, allowanceSeconds) {
180
- if (!(distanceSeconds > 0)) {
181
- return 0;
182
- }
183
- return Math.floor(Math.log2(1 + distanceSeconds / allowanceSeconds));
184
- }
185
-
186
- /**
187
- * An empty map of the right length: nothing wanted anywhere.
188
- *
189
- * @param {number} durationSeconds
190
- * @returns {PriorityMap}
191
- */
192
- export function emptyMap(durationSeconds) {
193
- const seconds = Number.isFinite(durationSeconds) && durationSeconds > 0
194
- ? Math.ceil(durationSeconds)
195
- : 0;
196
- return {
197
- durationSeconds: seconds,
198
- priority: new Uint8Array(seconds),
199
- secondsUntilPlayed: new Float64Array(seconds).fill(Number.POSITIVE_INFINITY),
200
- behind: new Uint8Array(seconds).fill(1)
201
- };
202
- }
203
-
204
- /**
205
- * One viewer's map.
206
- *
207
- * **The number is a reading of how soon they will be there.** A viewer watching
208
- * forward reaches second `x` after `x - p` seconds of film. That distance — not
209
- * a clock time — is what the value is derived from, and it is why two viewers
210
- * can be compared at all: the nearer one wins the second they both want.
211
- *
212
- * **A pause removes the time, not the direction.** A stopped viewer is still
213
- * standing somewhere, and the film in front of them is still the film they will
214
- * watch, so their map keeps its shape and moves into the band below. Collapsed
215
- * to one flat value over the whole film, as it was, their position disappeared
216
- * entirely — and with it the rule that what is in front is made first.
217
- *
218
- * **What must NOT be here**, and the boundary is the point: how fast this
219
- * machine encodes, how many encoders that takes, what a second weighs in bytes,
220
- * where a piece boundary falls, and what has already been made. Those are
221
- * answers the encoding and the downloading work out for themselves, from this
222
- * map and from what each knows about itself.
223
- *
224
- * @param {object} params
225
- * @param {number} params.atSeconds - Where they are watching from.
226
- * @param {number} params.durationSeconds - How long the film is.
227
- * @param {number} params.allowanceSeconds - The measured depth below which an
228
- * interruption reaches this viewer. The width of the first step.
229
- * @param {boolean} [params.playing] - Whether the picture is moving.
230
- * @returns {PriorityMap}
231
- */
232
- export function mapForViewer({ atSeconds, durationSeconds, allowanceSeconds, playing = true }) {
233
- const map = emptyMap(durationSeconds);
234
- if (map.durationSeconds === 0) {
235
- return map;
236
- }
237
- const at = Number.isFinite(atSeconds) && atSeconds > 0 ? Math.floor(atSeconds) : 0;
238
- const allowance = Number.isFinite(allowanceSeconds) && allowanceSeconds > 0
239
- ? allowanceSeconds
240
- : 1;
241
- const watching = playing !== false;
242
- const top = watching ? AT_A_WATCHING_VIEWER : AT_A_STOPPED_VIEWER;
243
- const floor = watching ? WATCHING_FLOOR : STOPPED_FLOOR;
244
- for (let second = 0; second < map.durationSeconds; second += 1) {
245
- if (second < at) {
246
- map.priority[second] = NOBODY_IS_COMING;
247
- continue;
248
- }
249
- map.behind[second] = 0;
250
- const distance = second - at;
251
- map.priority[second] = Math.max(floor, top - stepsAway(distance, allowance));
252
- // A viewer who has stopped is on their way nowhere, so there is no second by
253
- // which any of this must exist. The direction survives the pause, in the
254
- // priority above; the time does not, because there is none to state.
255
- map.secondsUntilPlayed[second] = watching ? distance : Number.POSITIVE_INFINITY;
256
- }
257
- return map;
258
- }
259
-
260
- /**
261
- * Where viewers stand, read off a map: every second whose priority rises above
262
- * the second before it.
263
- *
264
- * A viewer's own map is highest where they stand and falls away in front of
265
- * them, so in a merged map each viewer's position is a step UP — the one place
266
- * a value is higher than the value just behind it. A viewer standing inside the
267
- * stretch somebody else is walking towards adds nothing that map does not
268
- * already ask for, and is not a step; neither is somebody behind everybody.
269
- *
270
- * Read by whoever orders work by where people are and must not know what a
271
- * viewer is — the subtitle walk reads the clusters at these times first.
272
- *
273
- * @param {PriorityMap | null | undefined} map
274
- * @returns {number[]} Seconds, ascending.
275
- */
276
- export function viewerStartsOn(map) {
277
- const starts = [];
278
- if (!map || !(map.durationSeconds > 0)) {
279
- return starts;
280
- }
281
- for (let second = 0; second < map.durationSeconds; second += 1) {
282
- const value = map.priority[second];
283
- const before = second === 0 ? NOBODY_IS_COMING : map.priority[second - 1];
284
- if (value > before && value > NOBODY_IS_COMING) {
285
- starts.push(second);
286
- }
287
- }
288
- return starts;
289
- }
290
-
291
- /**
292
- * Every viewer's map as one.
293
- *
294
- * The highest priority per second wins, and the soonest time: film two people
295
- * want is as urgent as the more urgent of them, and making it once serves both.
296
- * The two are taken separately on purpose — the priority is coarse, so two
297
- * viewers can tie on it while one is genuinely nearer, and whoever schedules
298
- * against the time must be given the nearer one.
299
- *
300
- * In front of ANYBODY is in front, and the third array says so directly.
301
- *
302
- * @param {PriorityMap[]} maps
303
- * @returns {PriorityMap}
304
- */
305
- export function mergeMaps(maps) {
306
- const all = (maps ?? []).filter((map) => map && map.durationSeconds > 0);
307
- if (all.length === 0) {
308
- return emptyMap(0);
309
- }
310
- const merged = emptyMap(Math.max(...all.map((map) => map.durationSeconds)));
311
- for (const map of all) {
312
- for (let second = 0; second < map.durationSeconds; second += 1) {
313
- if (map.priority[second] > merged.priority[second]) {
314
- merged.priority[second] = map.priority[second];
315
- }
316
- if (map.secondsUntilPlayed[second] < merged.secondsUntilPlayed[second]) {
317
- merged.secondsUntilPlayed[second] = map.secondsUntilPlayed[second];
318
- }
319
- // In front of ANYBODY is in front: a stretch one viewer has passed is
320
- // still the film another is walking towards.
321
- if (map.behind[second] === 0) {
322
- merged.behind[second] = 0;
323
- }
324
- }
325
- }
326
- return merged;
327
- }
328
-
329
- /**
330
- * The map as stretches: runs of seconds that agree on both numbers.
331
- *
332
- * A VIEW of the map, never a second copy of it. Consumers that work in ranges —
333
- * the swarm is asked for byte ranges, an encoder is given a stretch of pieces —
334
- * would otherwise each write this walk for themselves.
335
- *
336
- * @param {PriorityMap} map
337
- * @returns {DemandZone[]} Ascending, without gaps or overlaps. Seconds nobody
338
- * wants are left out.
339
- */
340
- export function runsOf(map) {
341
- /** @type {DemandZone[]} */
342
- const runs = [];
343
- if (!map || !(map.durationSeconds > 0)) {
344
- return runs;
345
- }
346
- for (let second = 0; second < map.durationSeconds; second += 1) {
347
- const priority = map.priority[second];
348
- if (priority === NOTHING) {
349
- continue;
350
- }
351
- const behind = map.behind[second] === 1;
352
- const previous = runs[runs.length - 1];
353
- if (
354
- previous
355
- && previous.to === second
356
- && previous.priority === priority
357
- && previous.behind === behind
358
- ) {
359
- previous.to = second + 1;
360
- continue;
361
- }
362
- // THE TIME OF A STRETCH IS THE TIME OF ITS NEAR EDGE. A stretch is met at
363
- // its beginning, so its beginning is when it must exist; whoever needs the
364
- // time of a second inside it walks forward from there, at a second of film
365
- // per second, which is the same arithmetic that put the number here.
366
- //
367
- // Merging on the exact time as well would merge nothing at all: the time is
368
- // the distance, so it differs at every second, and the map came back as one
369
- // stretch per second of film.
370
- const withinSeconds = map.secondsUntilPlayed[second];
371
- runs.push({
372
- from: second,
373
- to: second + 1,
374
- priority,
375
- withinSeconds,
376
- behind
377
- });
378
- }
379
- return runs;
380
- }
381
-
382
- /**
383
- * The map in the order the work is taken: most urgent first, and within one
384
- * priority the earliest film first — that is where somebody is stopped.
385
- *
386
- * @param {DemandZone[]} runs
387
- * @returns {DemandZone[]}
388
- */
389
- export function inWorkingOrder(runs) {
390
- return [...(runs ?? [])].sort(
391
- (left, right) => right.priority - left.priority || left.from - right.from
392
- );
393
- }
394
-
395
- /**
396
- * The earliest second of film anybody is waiting on, or null when nobody is.
397
- *
398
- * WHY A SOUNDTRACK ASKS THE MAP AND NOT A VIEWER. Sound is produced for the
399
- * same reason a picture is — somebody is about to reach it — and the map is
400
- * where that is already stated, in seconds of film, merged over everybody
401
- * watching. Reading it from a viewer instead means the encoding layer holds a
402
- * person, and then every question about which person it is (the earliest of
403
- * two, the one on this rung, the one who has not reported yet) has to be
404
- * answered again in a second place. The map answers it once.
405
- *
406
- * The EARLIEST among the most urgent, because a track started at the leader's
407
- * position has nothing to give the viewer behind them, and the map's own order
408
- * — most urgent first, earliest film first within a priority — already says
409
- * which that is.
410
- *
411
- * @param {DemandZone[]} runs - From {@link runsOf}.
412
- * @returns {number | null} Seconds.
413
- */
414
- export function earliestUrgentSecond(runs) {
415
- const wanted = (runs ?? []).filter((zone) => zone && !zone.behind);
416
- if (wanted.length === 0) {
417
- return null;
418
- }
419
- const top = Math.max(...wanted.map((zone) => Number(zone.priority) || 0));
420
- return Math.min(...wanted.filter((zone) => (Number(zone.priority) || 0) === top).map((zone) => zone.from));
421
- }
1
+ /**
2
+ * @file THE PRIORITY MAP — what one viewer needs, what all of them need
3
+ * together, and in what order the work should be taken.
4
+ *
5
+ * A layer of its own, below both orchestrators and depending on nothing. It
6
+ * knows ONLY priorities: what is downloaded is the download orchestrator's own
7
+ * knowledge, what is encoded is the encoding orchestrator's, and neither is
8
+ * visible from here. Both read this and recompute their own on every change.
9
+ *
10
+ * The shape, stated by the user 2026-09-05:
11
+ *
12
+ * > Usually you make a map for each viewer, then merge the maps, then decide
13
+ * > the best way of filling it given the encoders available, where they are now
14
+ * > and how many there are.
15
+ *
16
+ * Three questions, and this file answers the first two. The third — the filling
17
+ * — belongs to whoever holds the encoders, and it is handed the merged map
18
+ * instead of a list of windows.
19
+ *
20
+ * **ONE PRIORITISATION, TWO CONSUMERS.** Downloading and encoding keep
21
+ * different STATES — made / being made / free for one; downloaded / arriving,
22
+ * and which peers hold it at what speed, for the other — but they must agree
23
+ * about what matters first, or the swarm fetches what the encoder will not
24
+ * reach for another twenty minutes. That agreement is this map.
25
+ *
26
+ * **THE UNIT IS SECONDS OF FILM.** A map is a set of stretches with sizes and a
27
+ * length of its own, so it needs a unit, and seconds are the only one every
28
+ * term of the arithmetic is already stated in: encode speed is a ratio of
29
+ * seconds to seconds, the measured allowance below which an interruption
30
+ * reaches a viewer is seconds, the viewer's position is seconds, the film's
31
+ * length is seconds. Bytes cannot serve — how many a second costs is not known
32
+ * when a file is opened and is not constant across it, and a soundtrack in a
33
+ * file of its own has bytes of its own. Segment numbers cannot serve either:
34
+ * they exist only once a cut grid is read, and two outputs of one film number
35
+ * differently.
36
+ *
37
+ * **What this file must NOT know**, and the boundary is the point: nothing about
38
+ * containers, cut grids, pieces or bytes. Turning a stretch of seconds into the
39
+ * bytes of one track is the container's and the track's business, by whatever
40
+ * means suit that file — a Cues table, a sample table, or a walk when the file
41
+ * carries neither, which is the same answer they already give in order to play
42
+ * it at all. Getting those bytes is the downloader's business; making segments
43
+ * out of them is the encoder's.
44
+ */
45
+
46
+ /**
47
+ * THE MAP ITSELF: one number per second of film.
48
+ *
49
+ * Literally an array as long as the film, where the value at second `x` says how
50
+ * urgently that second is wanted. Stated by the user 2026-09-06, and it replaced
51
+ * a list of stretches each carrying two numbers.
52
+ *
53
+ * Two arrays rather than one, because two different questions are asked of the
54
+ * map and only one of them can be answered by a rank:
55
+ *
56
+ * - `priority` orders the work. Only the ORDER between values is meaningful;
57
+ * the scale below says what the numbers separate;
58
+ * - `secondsUntilPlayed` is a quantity, and it is what makes lateness
59
+ * computable at all: whoever fills the map compares "when is this needed"
60
+ * against "when would it arrive", and only the second half is theirs to work
61
+ * out. `Infinity` where nobody is on their way.
62
+ *
63
+ * @typedef {object} PriorityMap
64
+ * @property {number} durationSeconds - The film's length, in whole seconds.
65
+ * @property {Uint8Array} priority - One entry per second. Zero means nothing is
66
+ * wanted there, which happens only where nobody is watching at all.
67
+ * @property {Float64Array} secondsUntilPlayed - One entry per second.
68
+ * @property {Uint8Array} behind - One entry per second, 1 where the second lies
69
+ * behind EVERY viewer. Stated rather than worked out from the other two,
70
+ * because working it out means knowing this file's scale, and the consumers
71
+ * are in other layers. Inferred from the absence of a time, as it was, it was
72
+ * wrong for a stopped viewer: their whole film carries no time, so the film in
73
+ * front of them counted as behind them and the encoders wandered to the start
74
+ * of the file.
75
+ */
76
+
77
+ /**
78
+ * A stretch of the map with one value throughout — the same facts said as a
79
+ * range instead of as a run of equal entries.
80
+ *
81
+ * @typedef {object} DemandZone
82
+ * @property {number} from - First second, inclusive.
83
+ * @property {number} to - Last second, exclusive.
84
+ * @property {number} priority
85
+ * @property {number} withinSeconds
86
+ * @property {boolean} behind - Whether this lies behind every viewer.
87
+ */
88
+
89
+ /**
90
+ * THE SCALE. Three bands, and the order between them is the whole of what the
91
+ * numbers claim.
92
+ *
93
+ * 1. IN FRONT OF SOMEBODY WHO IS WATCHING — the top value at the second they
94
+ * are about to see, falling as the film gets further from them;
95
+ * 2. IN FRONT OF SOMEBODY WHO HAS STOPPED — the same shape, and every value of
96
+ * it below every value of band 1. A stopped viewer will watch this film when
97
+ * they press play, so it is still in front of them; nobody is waiting for it
98
+ * now, so it yields to anybody who is;
99
+ * 3. BEHIND EVERYBODY — reachable only by a seek back, and nothing measures how
100
+ * likely that is, so it is one value rather than a shape.
101
+ *
102
+ * IN FRONT ALWAYS OUTRANKS BEHIND, at any distance and whoever is stopped. The
103
+ * bands make that true by construction rather than by a comparison somebody has
104
+ * to remember to write.
105
+ *
106
+ * The values inside a band are AN ENCODING OF AN ORDER, not a measurement:
107
+ * every consumer asks only which of two seconds comes first, so any strictly
108
+ * decreasing shape does the same work, and none of these numbers claims
109
+ * anything about the world.
110
+ */
111
+ export const AT_A_WATCHING_VIEWER = 100;
112
+ const WATCHING_FLOOR = 70;
113
+ const AT_A_STOPPED_VIEWER = 69;
114
+ const STOPPED_FLOOR = 39;
115
+
116
+ /** Behind everybody. */
117
+ export const NOBODY_IS_COMING = 1;
118
+
119
+ /** Nothing is wanted here at all. */
120
+ const NOTHING = 0;
121
+
122
+ /**
123
+ * Does this value mean "behind every viewer"?
124
+ *
125
+ * A read of the scale, so that nobody has to infer the side from the absence of
126
+ * a deadline. Inferred that way it was wrong for a stopped viewer, whose whole
127
+ * film carries no deadline: the film in front of them then counted as behind
128
+ * them, and the encoders were free to wander to the start of the file.
129
+ *
130
+ * @param {number} priority
131
+ * @returns {boolean}
132
+ */
133
+ export function isBehindEverybody(priority) {
134
+ return priority <= NOBODY_IS_COMING;
135
+ }
136
+
137
+ /**
138
+ * Is this second the one a viewer is about to watch?
139
+ *
140
+ * The top step of the watching band: the film under their feet and the measured
141
+ * allowance in front of it, which is the depth below which an interruption
142
+ * reaches them.
143
+ *
144
+ * @param {number} priority
145
+ * @returns {boolean}
146
+ */
147
+ export function isAtAWatchingViewer(priority) {
148
+ return priority >= AT_A_WATCHING_VIEWER;
149
+ }
150
+
151
+ /**
152
+ * Is this second in front of somebody who has STOPPED, and of nobody who is
153
+ * watching?
154
+ *
155
+ * Wanted, and wanted after everything anybody is walking towards: they will see
156
+ * it when they press play, and nothing here knows when that is.
157
+ *
158
+ * @param {number} priority
159
+ * @returns {boolean}
160
+ */
161
+ export function isNobodyComingNow(priority) {
162
+ return priority > NOBODY_IS_COMING && priority <= AT_A_STOPPED_VIEWER;
163
+ }
164
+
165
+ /**
166
+ * How far into its band a second sits, given its distance from the viewer.
167
+ *
168
+ * The step doubles: near the viewer the difference between now and ten seconds
169
+ * away decides what is made first, while twenty minutes out the difference
170
+ * between twenty and twenty-one minutes changes nothing. The first step is the
171
+ * MEASURED allowance for this file on this swarm — the depth below which an
172
+ * interruption reaches the viewer — so how finely the map divides comes from a
173
+ * measurement rather than from a number chosen here.
174
+ *
175
+ * @param {number} distanceSeconds
176
+ * @param {number} allowanceSeconds
177
+ * @returns {number} Zero at the viewer, growing with distance.
178
+ */
179
+ function stepsAway(distanceSeconds, allowanceSeconds) {
180
+ if (!(distanceSeconds > 0)) {
181
+ return 0;
182
+ }
183
+ return Math.floor(Math.log2(1 + distanceSeconds / allowanceSeconds));
184
+ }
185
+
186
+ /**
187
+ * An empty map of the right length: nothing wanted anywhere.
188
+ *
189
+ * @param {number} durationSeconds
190
+ * @returns {PriorityMap}
191
+ */
192
+ export function emptyMap(durationSeconds) {
193
+ const seconds = Number.isFinite(durationSeconds) && durationSeconds > 0
194
+ ? Math.ceil(durationSeconds)
195
+ : 0;
196
+ return {
197
+ durationSeconds: seconds,
198
+ priority: new Uint8Array(seconds),
199
+ secondsUntilPlayed: new Float64Array(seconds).fill(Number.POSITIVE_INFINITY),
200
+ behind: new Uint8Array(seconds).fill(1)
201
+ };
202
+ }
203
+
204
+ /**
205
+ * One viewer's map.
206
+ *
207
+ * **The number is a reading of how soon they will be there.** A viewer watching
208
+ * forward reaches second `x` after `x - p` seconds of film. That distance — not
209
+ * a clock time — is what the value is derived from, and it is why two viewers
210
+ * can be compared at all: the nearer one wins the second they both want.
211
+ *
212
+ * **A pause removes the time, not the direction.** A stopped viewer is still
213
+ * standing somewhere, and the film in front of them is still the film they will
214
+ * watch, so their map keeps its shape and moves into the band below. Collapsed
215
+ * to one flat value over the whole film, as it was, their position disappeared
216
+ * entirely — and with it the rule that what is in front is made first.
217
+ *
218
+ * **What must NOT be here**, and the boundary is the point: how fast this
219
+ * machine encodes, how many encoders that takes, what a second weighs in bytes,
220
+ * where a piece boundary falls, and what has already been made. Those are
221
+ * answers the encoding and the downloading work out for themselves, from this
222
+ * map and from what each knows about itself.
223
+ *
224
+ * @param {object} params
225
+ * @param {number} params.atSeconds - Where they are watching from.
226
+ * @param {number} params.durationSeconds - How long the film is.
227
+ * @param {number} params.allowanceSeconds - The measured depth below which an
228
+ * interruption reaches this viewer. The width of the first step.
229
+ * @param {boolean} [params.playing] - Whether the picture is moving.
230
+ * @returns {PriorityMap}
231
+ */
232
+ export function mapForViewer({ atSeconds, durationSeconds, allowanceSeconds, playing = true }) {
233
+ const map = emptyMap(durationSeconds);
234
+ if (map.durationSeconds === 0) {
235
+ return map;
236
+ }
237
+ const at = Number.isFinite(atSeconds) && atSeconds > 0 ? Math.floor(atSeconds) : 0;
238
+ const allowance = Number.isFinite(allowanceSeconds) && allowanceSeconds > 0
239
+ ? allowanceSeconds
240
+ : 1;
241
+ const watching = playing !== false;
242
+ const top = watching ? AT_A_WATCHING_VIEWER : AT_A_STOPPED_VIEWER;
243
+ const floor = watching ? WATCHING_FLOOR : STOPPED_FLOOR;
244
+ for (let second = 0; second < map.durationSeconds; second += 1) {
245
+ if (second < at) {
246
+ map.priority[second] = NOBODY_IS_COMING;
247
+ continue;
248
+ }
249
+ map.behind[second] = 0;
250
+ const distance = second - at;
251
+ map.priority[second] = Math.max(floor, top - stepsAway(distance, allowance));
252
+ // A viewer who has stopped is on their way nowhere, so there is no second by
253
+ // which any of this must exist. The direction survives the pause, in the
254
+ // priority above; the time does not, because there is none to state.
255
+ map.secondsUntilPlayed[second] = watching ? distance : Number.POSITIVE_INFINITY;
256
+ }
257
+ return map;
258
+ }
259
+
260
+ /**
261
+ * Where viewers stand, read off a map: every second whose priority rises above
262
+ * the second before it.
263
+ *
264
+ * A viewer's own map is highest where they stand and falls away in front of
265
+ * them, so in a merged map each viewer's position is a step UP — the one place
266
+ * a value is higher than the value just behind it. A viewer standing inside the
267
+ * stretch somebody else is walking towards adds nothing that map does not
268
+ * already ask for, and is not a step; neither is somebody behind everybody.
269
+ *
270
+ * Read by whoever orders work by where people are and must not know what a
271
+ * viewer is — the subtitle walk reads the clusters at these times first.
272
+ *
273
+ * @param {PriorityMap | null | undefined} map
274
+ * @returns {number[]} Seconds, ascending.
275
+ */
276
+ export function viewerStartsOn(map) {
277
+ const starts = [];
278
+ if (!map || !(map.durationSeconds > 0)) {
279
+ return starts;
280
+ }
281
+ for (let second = 0; second < map.durationSeconds; second += 1) {
282
+ const value = map.priority[second];
283
+ const before = second === 0 ? NOBODY_IS_COMING : map.priority[second - 1];
284
+ if (value > before && value > NOBODY_IS_COMING) {
285
+ starts.push(second);
286
+ }
287
+ }
288
+ return starts;
289
+ }
290
+
291
+ /**
292
+ * Every viewer's map as one.
293
+ *
294
+ * The highest priority per second wins, and the soonest time: film two people
295
+ * want is as urgent as the more urgent of them, and making it once serves both.
296
+ * The two are taken separately on purpose — the priority is coarse, so two
297
+ * viewers can tie on it while one is genuinely nearer, and whoever schedules
298
+ * against the time must be given the nearer one.
299
+ *
300
+ * In front of ANYBODY is in front, and the third array says so directly.
301
+ *
302
+ * @param {PriorityMap[]} maps
303
+ * @returns {PriorityMap}
304
+ */
305
+ export function mergeMaps(maps) {
306
+ const all = (maps ?? []).filter((map) => map && map.durationSeconds > 0);
307
+ if (all.length === 0) {
308
+ return emptyMap(0);
309
+ }
310
+ const merged = emptyMap(Math.max(...all.map((map) => map.durationSeconds)));
311
+ for (const map of all) {
312
+ for (let second = 0; second < map.durationSeconds; second += 1) {
313
+ if (map.priority[second] > merged.priority[second]) {
314
+ merged.priority[second] = map.priority[second];
315
+ }
316
+ if (map.secondsUntilPlayed[second] < merged.secondsUntilPlayed[second]) {
317
+ merged.secondsUntilPlayed[second] = map.secondsUntilPlayed[second];
318
+ }
319
+ // In front of ANYBODY is in front: a stretch one viewer has passed is
320
+ // still the film another is walking towards.
321
+ if (map.behind[second] === 0) {
322
+ merged.behind[second] = 0;
323
+ }
324
+ }
325
+ }
326
+ return merged;
327
+ }
328
+
329
+ /**
330
+ * The map as stretches: runs of seconds that agree on both numbers.
331
+ *
332
+ * A VIEW of the map, never a second copy of it. Consumers that work in ranges —
333
+ * the swarm is asked for byte ranges, an encoder is given a stretch of pieces —
334
+ * would otherwise each write this walk for themselves.
335
+ *
336
+ * @param {PriorityMap} map
337
+ * @returns {DemandZone[]} Ascending, without gaps or overlaps. Seconds nobody
338
+ * wants are left out.
339
+ */
340
+ export function runsOf(map) {
341
+ /** @type {DemandZone[]} */
342
+ const runs = [];
343
+ if (!map || !(map.durationSeconds > 0)) {
344
+ return runs;
345
+ }
346
+ for (let second = 0; second < map.durationSeconds; second += 1) {
347
+ const priority = map.priority[second];
348
+ if (priority === NOTHING) {
349
+ continue;
350
+ }
351
+ const behind = map.behind[second] === 1;
352
+ const previous = runs[runs.length - 1];
353
+ if (
354
+ previous
355
+ && previous.to === second
356
+ && previous.priority === priority
357
+ && previous.behind === behind
358
+ ) {
359
+ previous.to = second + 1;
360
+ continue;
361
+ }
362
+ // THE TIME OF A STRETCH IS THE TIME OF ITS NEAR EDGE. A stretch is met at
363
+ // its beginning, so its beginning is when it must exist; whoever needs the
364
+ // time of a second inside it walks forward from there, at a second of film
365
+ // per second, which is the same arithmetic that put the number here.
366
+ //
367
+ // Merging on the exact time as well would merge nothing at all: the time is
368
+ // the distance, so it differs at every second, and the map came back as one
369
+ // stretch per second of film.
370
+ const withinSeconds = map.secondsUntilPlayed[second];
371
+ runs.push({
372
+ from: second,
373
+ to: second + 1,
374
+ priority,
375
+ withinSeconds,
376
+ behind
377
+ });
378
+ }
379
+ return runs;
380
+ }
381
+
382
+ /**
383
+ * The map in the order the work is taken: most urgent first, and within one
384
+ * priority the earliest film first — that is where somebody is stopped.
385
+ *
386
+ * @param {DemandZone[]} runs
387
+ * @returns {DemandZone[]}
388
+ */
389
+ export function inWorkingOrder(runs) {
390
+ return [...(runs ?? [])].sort(
391
+ (left, right) => right.priority - left.priority || left.from - right.from
392
+ );
393
+ }
394
+
395
+ /**
396
+ * The earliest second of film anybody is waiting on, or null when nobody is.
397
+ *
398
+ * WHY A SOUNDTRACK ASKS THE MAP AND NOT A VIEWER. Sound is produced for the
399
+ * same reason a picture is — somebody is about to reach it — and the map is
400
+ * where that is already stated, in seconds of film, merged over everybody
401
+ * watching. Reading it from a viewer instead means the encoding layer holds a
402
+ * person, and then every question about which person it is (the earliest of
403
+ * two, the one on this rung, the one who has not reported yet) has to be
404
+ * answered again in a second place. The map answers it once.
405
+ *
406
+ * The EARLIEST among the most urgent, because a track started at the leader's
407
+ * position has nothing to give the viewer behind them, and the map's own order
408
+ * — most urgent first, earliest film first within a priority — already says
409
+ * which that is.
410
+ *
411
+ * @param {DemandZone[]} runs - From {@link runsOf}.
412
+ * @returns {number | null} Seconds.
413
+ */
414
+ export function earliestUrgentSecond(runs) {
415
+ const wanted = (runs ?? []).filter((zone) => zone && !zone.behind);
416
+ if (wanted.length === 0) {
417
+ return null;
418
+ }
419
+ const top = Math.max(...wanted.map((zone) => Number(zone.priority) || 0));
420
+ return Math.min(...wanted.filter((zone) => (Number(zone.priority) || 0) === top).map((zone) => zone.from));
421
+ }