@torrent-tv/proxy 2.80.14 → 2.80.16

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,1101 +1,1274 @@
1
- /**
2
- * @file How many encoders there should be on one output, and where each of them
3
- * belongs — decided from numbers alone.
4
- *
5
- * The decision is separated from carrying it out on purpose. Every rule below
6
- * was previously a condition somewhere inside an eleven-thousand-line file,
7
- * reachable only by starting a real ffmpeg, and each of them was written for
8
- * one viewer:
9
- *
10
- * - a run was placed at the position of whoever asked, and never at the first
11
- * thing missing, so a viewer moving into a stretch already on disk restarted
12
- * an encoder to make it a second time;
13
- * - a run had no end at all — neither `-to` nor `-t` appeared anywhere — so it
14
- * ran until something killed it, and two runs on one output could not exist
15
- * without writing over each other;
16
- * - nothing stopped a run that had caught up with material somebody else had
17
- * already made.
18
- *
19
- * The rule this file exists to express, stated by the user 2026-09-04:
20
- *
21
- * > Viewers are always independent and always reuse what can be reused. The
22
- * > number of encoders is however many are needed; how many are needed follows
23
- * > from which sets of output parameters are wanted and where the viewers stand
24
- * > inside each. Segments produced by ANY encoder are available to ANY viewer,
25
- * > and which viewer asked never enters the question.
26
- *
27
- * So no name of a viewer reaches this file. It is given what is wanted, what
28
- * exists, what is being made, and what the machine can afford.
29
- *
30
- * **A viewer decides the ORDER the map is walked in and, through the budget, how
31
- * many processes walk it. Nothing else.** Stated by the user 2026-09-05, and it
32
- * is the rule the rest of this file now follows: while a file is being encoded
33
- * it is encoded WHOLE, in the order the map dictates. Who wants which segment
34
- * decides which gap is closed first, never whether a run may go on living.
35
- *
36
- * **A run is therefore never stopped for standing outside a viewer's window.**
37
- * It used to be, and the two decisions that produced that were in direct
38
- * contradiction — measured in the field 2026-09-05 on a viewer watching an
39
- * episode:
40
- *
41
- * 1. this file commanded a start inside the window, at #46;
42
- * 2. `planRunInterval` in the session manager moved the start to #78, because
43
- * it counted a suspended run's claim as reaching `head + look-ahead`;
44
- * 3. this file then saw a run at #78 against a window of [27, 57], found no
45
- * overlap, and killed it as "nothing it was given is wanted";
46
- * 4. neither coverage nor demand had changed, so the same start was commanded
47
- * again — 350-700ms per cycle, dozens of times, no segment ever produced,
48
- * the viewer's picture stopped for 125 seconds.
49
- *
50
- * Both of those other authorities are gone (roadmap item 76, step 5). What is
51
- * left is this file, and the only reasons it stops a run are: nobody is
52
- * watching the output at all; the machine affords fewer processes; or there is
53
- * nothing left unmade anywhere in the track.
54
- *
55
- * **A run's end comes from the coverage**, never from a window: it runs until
56
- * it meets material somebody else has made or is making, or until the end of
57
- * the film.
58
- */
59
-
60
- /**
61
- * One encoder that is running now.
62
- *
63
- * @typedef {object} LiveRun
64
- * @property {string} id
65
- * @property {number} from - The first number it was given.
66
- * @property {number} to - The last number it was given, inclusive.
67
- * @property {number} head - The next number it will produce. Its position.
68
- * @property {number} speedX - Measured encode speed against realtime, from
69
- * ffmpeg's own progress. Zero or less means nothing has measured it yet, and
70
- * then no comparison involving its speed can be made.
71
- */
72
-
73
- /**
74
- * What a viewer is waiting for. Which viewer is deliberately absent.
75
- *
76
- * @typedef {object} WantedSpan
77
- * @property {number} from
78
- * @property {number} to
79
- */
80
-
81
- /**
82
- * @typedef {{ type: "start", from: number, to: number, because: string }
83
- * | { type: "move", run: object, from: number, to: number, because: string }
84
- * | { type: "stop", run: object, because: string }
85
- * | { type: "keep", run: object, from: number, to: number }} PlanAction
86
- */
87
-
88
- /**
89
- * Decide what to do with the encoders on one output.
90
- *
91
- * @param {object} params
92
- * @param {import("./CoverageMap.js").CoverageMap} params.coverage - What has
93
- * been made and what is being made.
94
- * @param {WantedSpan[]} params.windows - What viewers are waiting for, one
95
- * window each. Empty means nobody is watching this output.
96
- * @param {LiveRun[]} params.runs - The encoders running on it now.
97
- * @param {number} params.maxRuns - How many encoders this machine can afford on
98
- * this output. Comes from the same arithmetic that decides the quality offer;
99
- * it is measured per host and never chosen here.
100
- * @param {number} params.segmentSeconds - How much film one segment holds.
101
- * @param {number} [params.killCostSec] - How long stopping an encoder takes,
102
- * measured on this host from its own runs. Zero until something has measured
103
- * it, which makes moving one look cheaper than it is and is said here so the
104
- * bias is known.
105
- * @param {number} [params.firstByteWaitSec] - How long a fresh encoder takes to
106
- * produce anything: process start, opening the input, and the first piece.
107
- * Measured the same way. It replaced a constant of 0.12 s taken from one
108
- * host and charged to every other.
109
- * @param {(others: number) => number} [params.contentionPenaltyFor] - How much
110
- * slower ONE encoder runs with that many others beside it, measured on this
111
- * host. Without it every extra process looks free, and the score then wants an
112
- * encoder per piece: at exactly realtime each next piece is marginally late
113
- * however many are running, so another one always seemed to help a little.
114
- * Unmeasured is 1, and then the budget is the only thing bounding the count.
115
- * @returns {PlanAction[]} Stops first, then moves, then starts, so that a plan
116
- * carried out in order never holds two encoders where it means to hold one.
117
- */
118
- export function planEncoders({
119
- coverage,
120
- windows,
121
- runs,
122
- maxRuns,
123
- segmentSeconds,
124
- killCostSec = 0,
125
- firstByteWaitSec = 0,
126
- refetchSecPerFilmSecond = 0,
127
- contentionPenaltyFor = () => 1,
128
- speedX = 0
129
- }) {
130
- /** @type {PlanAction[]} */
131
- const stops = [];
132
- /** @type {PlanAction[]} */
133
- const moves = [];
134
- /** @type {PlanAction[]} */
135
- const starts = [];
136
- /** @type {PlanAction[]} */
137
- const keeps = [];
138
-
139
- const wanted = Array.isArray(windows) ? windows : [];
140
- const live = Array.isArray(runs) ? runs : [];
141
-
142
- // Nobody is watching this output: every encoder on it is making segments for
143
- // no one. This is the case a look-ahead cannot answer, because look-ahead
144
- // asks how far AHEAD of a viewer a run is and there is no viewer.
145
- if (wanted.length === 0) {
146
- for (const run of live) {
147
- stops.push({ type: "stop", run, because: "nobody is watching this output" });
148
- }
149
- return stops;
150
- }
151
-
152
- const untilNeeded = deadlineReaderFor(wanted, segmentSeconds);
153
- // Segments produced per second, from the fastest measured encoder here.
154
- // Seconds of film per second, divided by the film one piece holds.
155
- //
156
- // A RUN WORKING ON THIS OUTPUT OUTRANKS THE BENCHMARK. The startup figure is
157
- // what this host does on reference clips; a run here is what it does on THIS
158
- // material, and that is the more specific statement. Taken as a floor instead
159
- // the larger of the two — an encoder reporting half realtime was scored as
160
- // though it ran at twice, and nothing was ever late.
161
- const working = live.reduce((best, run) => Math.max(best, run.speedX || 0), 0);
162
- const rate = segmentSeconds > 0 ? (working > 0 ? working : speedX) / segmentSeconds : 0;
163
- // What a body costs to take away from where it stands and put somewhere else:
164
- // its death, the start of another, and the wait for the first bytes there.
165
- // Taking an encoder somewhere else is stopping this one and waiting for the
166
- // next to produce. Both halves are measured on this host.
167
- const moveSec = killCostSec + firstByteWaitSec;
168
-
169
- // ------------------------------------------------------------------ WHERE
170
- //
171
- // A question about the FILM, and about nothing else: which numbers are
172
- // missing, when each is needed, how fast this machine encodes, how many
173
- // processes it can hold. No encoder that happens to be running enters it,
174
- // which is why it can be answered by arithmetic.
175
- const positions = placeEncoders({
176
- coverage,
177
- windows: wanted,
178
- howMany: maxRuns,
179
- // EVERY LIVE ENCODER IS PRE-PLACED, because that is what "somebody already
180
- // gets here in time" means. A number one of them reaches before it is
181
- // needed is not a position at all; a number none of them reaches is, and
182
- // needs a body brought to it. There is no third case, and in particular no
183
- // separate question of whether an encoder should drive on or be moved:
184
- // driving is simply its arrival, and its arrival is priced in one place.
185
- firstGap: gapFinderFor(coverage, new Set(live), rate, segmentSeconds * refetchSecPerFilmSecond),
186
- deadlineAt: untilNeeded
187
- });
188
-
189
- // -------------------------------------------------------------------- WHO
190
- //
191
- // ARGMIN OF THE OBJECTIVE, EVALUATED. Not a rule that approximates it.
192
- //
193
- // Every way of filling the positions is scored by `latenessOf` and the best is
194
- // taken. There are at most a handful of positions and a handful of bodies, so
195
- // the enumeration is exact: no local rule stands in for the objective, and
196
- // none can therefore disagree with another.
197
- //
198
- // Four such rules were written before this and all four had to go — "place
199
- // where a number is late", "take a body that serves nothing", "take one whose
200
- // work is needed later than this", "drive on or move, by cost". Each looked
201
- // like a consequence of the model and each approximated it from a different
202
- // side, so together they contradicted one another and the answer depended on
203
- // which ran first.
204
- /** One decision per live encoder, so none can be decided twice. @type {Map<object, PlanAction>} */
205
- const decided = new Map();
206
- const room = Math.max(0, maxRuns - live.length);
207
- const refetchPerSegment = segmentSeconds * refetchSecPerFilmSecond;
208
- const startSec = firstByteWaitSec;
209
-
210
- let arrangements = [{ fill: [], used: new Set(), fresh: 0 }];
211
- for (let index = 0; index < positions.length; index += 1) {
212
- const next = [];
213
- for (const arrangement of arrangements) {
214
- next.push({ fill: [...arrangement.fill, null], used: arrangement.used, fresh: arrangement.fresh });
215
- // A FRESH PROCESS IS OFFERED BEFORE ANY WORKING BODY, so that when the two
216
- // score the same the working one is left alone. Taking it is free in the
217
- // arithmetic — its output stays on disk — but it is not free in fact: the
218
- // run it belongs to has a position, a warm input and a measured speed, and
219
- // all three are thrown away for nothing.
220
- if (arrangement.fresh < room) {
221
- next.push({
222
- fill: [...arrangement.fill, "new"],
223
- used: arrangement.used,
224
- fresh: arrangement.fresh + 1
225
- });
226
- }
227
- for (const run of live) {
228
- if (arrangement.used.has(run)) {
229
- continue;
230
- }
231
- next.push({
232
- fill: [...arrangement.fill, run],
233
- used: new Set([...arrangement.used, run]),
234
- fresh: arrangement.fresh
235
- });
236
- }
237
- }
238
- arrangements = next;
239
- }
240
-
241
- let best = null;
242
- let bestScore = null;
243
- for (const arrangement of arrangements) {
244
- const bodies = [];
245
- for (let index = 0; index < positions.length; index += 1) {
246
- const filler = arrangement.fill[index];
247
- if (filler === null) {
248
- continue;
249
- }
250
- if (filler === "new") {
251
- bodies.push({ at: positions[index], delaySec: startSec });
252
- continue;
253
- }
254
- const head = Number(filler.head);
255
- bodies.push({
256
- at: positions[index],
257
- delaySec: head === positions[index] ? 0 : moveSec
258
- });
259
- }
260
- // Bodies nobody was given a position for go on working where they stand,
261
- // and their coverage counts: the file is encoded whole.
262
- //
263
- // A body given no end pays a restart the moment anybody is placed inside the
264
- // road it would drive: where a run stops is fixed when its process starts,
265
- // so it has to be cut and begun again at its own head. That price was
266
- // invisible here, and an arrangement was scored as free when it was not.
267
- for (const run of live) {
268
- if (arrangement.used.has(run)) {
269
- continue;
270
- }
271
- const head = Number(run.head);
272
- const endless = Number(run.to) < Number(run.from);
273
- const cutInFront = arrangement.fill.some((filler, index) =>
274
- filler !== null && positions[index] > head
275
- && (endless || positions[index] <= Number(run.to)));
276
- bodies.push({ at: head, delaySec: cutInFront ? moveSec : 0 });
277
- }
278
- const scored = latenessOf(bodies, coverage, wanted, untilNeeded, rate / contentionPenaltyFor(Math.max(0, bodies.length - 1)), refetchPerSegment, segmentSeconds);
279
- if (bestScore === null || cheaperThan(scored, bestScore)) {
280
- bestScore = scored;
281
- best = arrangement;
282
- }
283
- }
284
-
285
- // A BODY STANDING ON FILM THAT EXISTS is the one arrangement the enumeration
286
- // above cannot reach: the gap in front of it is nobody's deadline, so it is
287
- // never a position, and the body is left to make three hundred pieces a second
288
- // time. Each such body is offered its own first gap and the SAME score decides
289
- // moving costs a restart on everything downstream, staying costs the repeat.
290
- //
291
- // Offered one at a time rather than folded into the enumeration because the
292
- // enumeration is exponential in the number of positions, and this is called
293
- // again on every piece produced. One extra evaluation per body against
294
- // several thousand arrangements is the difference between arithmetic and a
295
- // stalled proxy.
296
- const placement = new Map();
297
- for (let index = 0; index < positions.length; index += 1) {
298
- const filler = best ? best.fill[index] : null;
299
- if (filler && filler !== "new") {
300
- placement.set(filler, positions[index]);
301
- }
302
- }
303
- const bodiesOf = (override) => {
304
- const bodies = [];
305
- for (const run of live) {
306
- if (override.has(run) && override.get(run) === null) {
307
- // Asked what the film looks like WITHOUT this one.
308
- continue;
309
- }
310
- const at = override.has(run) ? override.get(run) : (placement.get(run) ?? Number(run.head));
311
- const head = Number(run.head);
312
- bodies.push({ at, delaySec: at === head ? 0 : moveSec });
313
- }
314
- for (let index = 0; index < positions.length; index += 1) {
315
- if ((best ? best.fill[index] : null) === "new") {
316
- bodies.push({ at: positions[index], delaySec: startSec });
317
- }
318
- }
319
- return bodies;
320
- };
321
- const scoreOf = (override) => {
322
- const bodies = bodiesOf(override);
323
- return latenessOf(bodies, coverage, wanted, untilNeeded,
324
- rate / contentionPenaltyFor(Math.max(0, bodies.length - 1)), refetchPerSegment, segmentSeconds);
325
- };
326
- for (const run of live) {
327
- if (placement.has(run)) {
328
- continue;
329
- }
330
- const gap = coverage.firstGapFrom(run.head, undefined, run);
331
- if (gap === null || gap === Number(run.head)) {
332
- continue;
333
- }
334
- const asIs = scoreOf(new Map());
335
- const moved = scoreOf(new Map([[run, gap]]));
336
- if (cheaperThan(moved, asIs)) {
337
- placement.set(run, gap);
338
- }
339
- }
340
-
341
- /**
342
- * Would the film be worse off without this body? Asked of the same score.
343
- *
344
- * @param {object} run
345
- * @returns {boolean}
346
- */
347
- const worseWithout = (run) => {
348
- const kept = bodiesOf(new Map());
349
- const without = bodiesOf(new Map([[run, null]]));
350
- const scoreOf_ = (bodies) => latenessOf(bodies, coverage, wanted, untilNeeded,
351
- rate / contentionPenaltyFor(Math.max(0, bodies.length - 1)), refetchPerSegment, segmentSeconds);
352
- return cheaperThan(scoreOf_(kept), scoreOf_(without));
353
- };
354
-
355
- const stretchAt = (from) => endOfStretch(from, Math.min(
356
- coverage.unmadeRunFrom(from),
357
- coverage.freeRunFrom(from, new Set(live))
358
- ));
359
-
360
- for (let index = 0; index < positions.length; index += 1) {
361
- if ((best ? best.fill[index] : null) !== "new") {
362
- continue;
363
- }
364
- const at = positions[index];
365
- starts.push({
366
- type: "start",
367
- from: at,
368
- to: stretchAt(at),
369
- because: `#${at} is wanted and nobody reaches it in time`
370
- });
371
- }
372
-
373
- for (const run of live) {
374
- const head = Number(run.head);
375
- const at = placement.has(run) ? placement.get(run) : head;
376
- if (at !== head) {
377
- decided.set(run, {
378
- type: "move",
379
- run,
380
- from: at,
381
- to: stretchAt(at),
382
- because: `standing at #${head} scores worse than standing at #${at}, counting ` +
383
- "both how late the film would be and the work that would be done twice"
384
- });
385
- continue;
386
- }
387
- // It stays where it is unless holding it changes nothing.
388
- //
389
- // A body left over from where a viewer used to be goes on costing the
390
- // machine a process while another encoder already reaches everything it
391
- // would. The score says so directly: take it away and see. Removing it is
392
- // refused the moment it makes anything later or leaves film abandoned, so
393
- // this cannot quietly drop the encoder somebody is waiting on.
394
- if (!placement.has(run) && !worseWithout(run)) {
395
- stops.push({
396
- type: "stop",
397
- run,
398
- because: "the film is no worse off without it"
399
- });
400
- continue;
401
- }
402
- decided.set(run, { type: "keep", run, from: head, to: run.to });
403
- }
404
-
405
- // THE MACHINE'S LIMIT BINDS, whatever the map wants. It is measured — the
406
- // processor, the swarm and the piece store each give a figure and the smallest
407
- // wins — and an encoder over it is one the host cannot feed. Which of them
408
- // goes is the same question as any other here: the one the film misses least,
409
- // by the same score.
410
- while (decided.size + starts.length > maxRuns) {
411
- let cheapest = null;
412
- let cheapestScore = null;
413
- for (const [run, action] of decided) {
414
- if (action.type !== "keep") {
415
- continue;
416
- }
417
- const without = latenessOf(bodiesOf(new Map([[run, null]])), coverage, wanted, untilNeeded,
418
- rate / contentionPenaltyFor(Math.max(0, live.length - 2)), refetchPerSegment, segmentSeconds);
419
- if (cheapestScore === null || cheaperThan(without, cheapestScore)) {
420
- cheapestScore = without;
421
- cheapest = run;
422
- }
423
- }
424
- if (cheapest === null) {
425
- break;
426
- }
427
- decided.delete(cheapest);
428
- placement.delete(cheapest);
429
- stops.push({
430
- type: "stop",
431
- run: cheapest,
432
- because: `the machine holds ${maxRuns} encoder(s) on this output and this is the one ` +
433
- "the film misses least"
434
- });
435
- }
436
-
437
- for (const action of decided.values()) {
438
- if (action.type === "keep") {
439
- keeps.push(action);
440
- } else {
441
- moves.push(action);
442
- }
443
- }
444
-
445
- // ONE ENCODER'S WORK ENDS WHERE THE NEXT ONE'S BEGINS.
446
- //
447
- // A free stretch may run to the end of the track, and an encoder given all of
448
- // it stands in the road of every encoder placed behind it: they write the
449
- // same names, and each one's output is the other's "material somebody else
450
- // made", so they stop one another. Field 2026-09-05: three encoders started
451
- // on one track within 200 ms, each into the road another was already writing.
452
- // Fifteen readers on a piece store that holds sixteen pieces followed, half
453
- // of all evictions took a piece a reader had declared, and `/stream` began
454
- // handing out bytes that were not the file's.
455
- //
456
- // The bound is taken from the NEXT ENCODER'S START, not from a band edge: a
457
- // band edge travels with the viewer, so every step forward would leave a
458
- // sliver just past the previous encoder and buy an encoder for it.
459
- // A RUN THAT IS STAYING IS IN THE SORT TOO, because its road can be taken.
460
- //
461
- // It used to be left out, on the reading that a run staying put keeps what it
462
- // was given. That is true of the stretch it was GIVEN and false of the road it
463
- // will actually drive: a run with no end carries no `-to` and walks to the end
464
- // of the film, so an encoder placed in front of it writes the same names.
465
- const placed = [...moves, ...starts, ...keeps].sort(
466
- (left, right) => /** @type {any} */ (left).from - /** @type {any} */ (right).from
467
- );
468
- for (let index = 0; index < placed.length - 1; index += 1) {
469
- const here = /** @type {{ type: string, run?: object, from: number, to: number }} */ (placed[index]);
470
- const next = /** @type {{ from: number }} */ (placed[index + 1]);
471
- if (here.to >= 0 && here.to < next.from) {
472
- continue;
473
- }
474
- here.to = next.from - 1;
475
- if (here.type !== "keep") {
476
- continue;
477
- }
478
- // SHORTENING A LIVE RUN'S ROAD MEANS STOPPING IT, not merely writing a
479
- // smaller number down. Where a run's end goes is fixed when its process
480
- // starts, so one that was given none keeps producing past any bound decided
481
- // later and would write one piece into the new encoder's road — two
482
- // processes on one name, which is the collision this whole pass exists to
483
- // prevent. So it ends here and begins again at its own head with a real end;
484
- // the viewer in front pays a restart, which is a cost this file already
485
- // prices rather than a interruption nobody counted.
486
- keeps.splice(keeps.indexOf(here), 1);
487
- moves.push({
488
- type: "move",
489
- run: here.run,
490
- from: here.from,
491
- to: here.to,
492
- because:
493
- `an encoder is needed at #${next.from}, which this run would reach only by ` +
494
- "encoding through; it takes the road up to there and ends by itself"
495
- });
496
- }
497
-
498
- return [...stops, ...moves, ...starts, ...keeps];
499
- }
500
-
501
-
502
-
503
- /**
504
- * THE OBJECTIVE, as a value that can be compared.
505
- *
506
- * THREE COUNTS OF SECONDS, COMPARED IN ORDER. The order is the user's, stated
507
- * 2026-09-06, and a later count decides only where the earlier ones tie:
508
- *
509
- * 1. SECONDS ANYBODY SPENDS LOOKING AT A SPINNER. Nothing outranks it, at any
510
- * size. Walked forward in film order rather than summed piece by piece: a
511
- * viewer who is stopped is not watching, so a wait moves every deadline
512
- * behind it by its own length;
513
- *
514
- * 2. WHEN THE FILM IN FRONT OF THE VIEWERS IS FINISHED — the last piece of it to
515
- * be made, whichever encoder makes it. A stretch no encoder will ever reach
516
- * counts as never, which is what stops the front being abandoned;
517
- *
518
- * 3. WHEN THE WHOLE FILE IS FINISHED — the film behind the viewers included,
519
- * plus what the swarm pays to fetch anything a second time. Film nobody is
520
- * waiting for still has value: a viewer seeking back into a part that exists
521
- * starts playing at once, and seeking back is what people do in the first
522
- * minutes while they find their place. So spare capacity goes to finishing
523
- * the file. This is where "the file is encoded WHOLE" lives; it used to be a
524
- * penalty for film below the lowest encoder, which said the same thing as a
525
- * patch and said it about one edge of the track only.
526
- *
527
- * WHY AN ENCODER MAY STAND BEHIND A VIEWER while film in front is still unmade:
528
- * encoders work at the same time, so one in front and one behind can finish the
529
- * file sooner than two in front. Where nobody is stalled and the front is closed
530
- * just as fast, the file being done sooner is the answer — count 3 deciding a
531
- * tie in 1 and 2, which is exactly what the order is for.
532
- *
533
- * WHY THE COUNTS ARE COMPARED AND NOT ADDED: seconds of somebody waiting and
534
- * seconds until a distant stretch exists are not the same thing, and no measured
535
- * quantity says how many of one are worth one of the other. Adding them would
536
- * mean choosing that exchange rate, which is inventing a number.
537
- *
538
- * @param {{ at: number, delaySec: number }[]} bodies - Where each encoder would
539
- * stand, and how long before it produces anything there: nothing where it is
540
- * already standing, a move or a start otherwise.
541
- * @param {import("./CoverageMap.js").CoverageMap} coverage
542
- * @param {WantedSpan[]} wanted
543
- * @param {(index: number) => number} untilNeeded
544
- * @param {number} rate - Segments per second. Always a real figure: this host
545
- * measures what it encodes at on startup, before any viewer exists, and every
546
- * run that works then refines it. There is no "unmeasured" case to answer.
547
- * @param {number} refetchSecPerSegment
548
- * @param {number} segmentSeconds
549
- * @returns {{ stall: number, ahead: number, whole: number }} Three counts of
550
- * seconds, compared in that order by {@link cheaperThan}.
551
- */
552
- function latenessOf(bodies, coverage, wanted, untilNeeded, rate, refetchSecPerSegment, segmentSeconds) {
553
- const first = Math.min(...wanted.map((span) => span.from));
554
- const last = Math.max(...wanted.map((span) => span.to));
555
- // What a number nobody reaches at all counts as. The film's own length is the
556
- // honest bound nothing can be later than never and a finite figure is what
557
- // lets two hopeless arrangements still be told apart by the rest of the sum.
558
- const never = (last + 1) * segmentSeconds;
559
-
560
- // WHICH SIDE OF THE VIEWERS a piece is on. The map states it; nothing here
561
- // works it out from positions, and nothing here knows where a viewer stands.
562
- //
563
- // It was read off the deadline before no time stated meant behind and that
564
- // is true only of a viewer who is playing. A paused viewer has no times
565
- // anywhere, so their whole film read as behind them, "ahead before behind"
566
- // had nothing to compare, and the encoder was free to wander to the start of
567
- // the file. Which side a stretch is on and how soon it is wanted are two
568
- // different facts, and the map states both.
569
- const isBehind = (at) => {
570
- let behind = false;
571
- for (const span of wanted) {
572
- if (at < span.from || at > span.to) {
573
- continue;
574
- }
575
- if (span.behind !== true) {
576
- return false;
577
- }
578
- behind = true;
579
- }
580
- return behind;
581
- };
582
-
583
- // EVERY COUNT IS OVER THE FILM, NOT OVER THE ENCODERS. When a piece is made
584
- // depends on which encoder reaches it soonest, and the encoder that reaches
585
- // film in front of the viewers may well be standing behind them.
586
- //
587
- // Counted over the encoders instead — each charged to the side it stands on —
588
- // the score had a hole that swallowed everything: an arrangement with every
589
- // encoder BEHIND the viewers had nothing charged to the film in front, so its
590
- // second term was zero, which is the best value there is. The plan then
591
- // abandoned the film in front of a viewer and put both encoders at the start
592
- // of the file, which is the opposite of the rule it is supposed to obey.
593
- //
594
- // AND THE WAITING IS WALKED FORWARD, not summed piece by piece.
595
- //
596
- // Not a sum of each piece's own lateness. A viewer who is stopped is not
597
- // watching, so everything after the piece they are stopped on is needed that
598
- // much later too: one wait moves every deadline behind it by its own length.
599
- //
600
- // Summed independently instead, the far tail of a long file outvoted the film
601
- // under the viewer's feet — measured, and it placed the only encoder at #114
602
- // while the viewer stood at #100, because thirteen pieces of certain waiting
603
- // "cost" less than 886 distant pieces arriving a little later. Walking the
604
- // clock forward makes that trade impossible: abandoning the near film delays
605
- // the far film by at least as much.
606
- let stalled = 0;
607
- let tardiness = 0;
608
- let aheadDone = 0;
609
- let behindDone = 0;
610
- let wastedSwarm = 0;
611
- for (let index = first; index <= last; index += 1) {
612
- // Which encoder gets to this piece first, and when. One standing on it is
613
- // already there; one behind it must work its way up, re-making anything
614
- // already made on the way, which costs its own time and the swarm's.
615
- let soonest = Number.POSITIVE_INFINITY;
616
- let byWhom = null;
617
- for (const body of bodies) {
618
- if (body.at > index) {
619
- continue;
620
- }
621
- const arrival = body.delaySec
622
- + (index - body.at + 1) / rate
623
- + coverage.madeBetween(body.at, index) * refetchSecPerSegment;
624
- if (arrival < soonest) {
625
- soonest = arrival;
626
- byWhom = body;
627
- }
628
- }
629
- if (coverage.isReady(index)) {
630
- // It exists. Nobody waits for it and nothing is owedbut whoever passes
631
- // over it makes it a second time, and the swarm fetches its bytes again.
632
- if (byWhom !== null) {
633
- wastedSwarm += refetchSecPerSegment;
634
- }
635
- continue;
636
- }
637
- // A piece nobody is working towards arrives never. There is no third case:
638
- // the host measures what it encodes at, and what it copies at, before any
639
- // viewer exists, so a speed is always a real number and an arrival can
640
- // always be computed.
641
- // Nothing arrives later than never, which is the bound the film's own length
642
- // gives. It is a definition rather than a guard: it also makes the score
643
- // total on a host whose startup measured nothing at all, where every arrival
644
- // is beyond reckoning and every arrangement is therefore equally hopeless.
645
- const when = byWhom === null ? never : Math.min(soonest, never);
646
- if (isBehind(index)) {
647
- behindDone = Math.max(behindDone, when);
648
- } else {
649
- aheadDone = Math.max(aheadDone, when);
650
- }
651
- const deadline = untilNeeded(index);
652
- if (Number.isFinite(deadline)) {
653
- const due = deadline + stalled;
654
- const waited = Math.max(0, when - due);
655
- tardiness += waited;
656
- stalled += waited;
657
- }
658
- }
659
-
660
- return {
661
- // 1. SECONDS ANYBODY SPENDS LOOKING AT A SPINNER. Nothing outranks it.
662
- stall: tardiness,
663
- // 2. WHEN THE FILM IN FRONT OF THEM IS DONE the last piece of it to be
664
- // made, whichever encoder makes it. Film nobody reaches counts as never,
665
- // which is what stops the front being abandoned.
666
- ahead: aheadDone,
667
- // 3. WHEN THE WHOLE FILE IS DONE the film behind included, and the swarm's
668
- // price for anything fetched twice, which delays everything.
669
- whole: Math.max(aheadDone, behindDone) + wastedSwarm
670
- };
671
- }
672
-
673
- /**
674
- * Is the first arrangement cheaper than the second?
675
- *
676
- * Three things in order, stated by the user 2026-09-06: nobody stares at a
677
- * spinner; then the film in front of the viewers is finished soonest; then the
678
- * whole file is. A later one decides only where the earlier ones tie.
679
- *
680
- * That order is why an encoder may stand BEHIND a viewer while film in front is
681
- * still unmade: encoders work at the same time, so one in front and one behind
682
- * can finish the file sooner than two in front — and where nobody is stalled and
683
- * the front is closed just as fast, the file being done sooner is the answer.
684
- *
685
- * @param {{ stall: number, ahead: number, whole: number }} left
686
- * @param {{ stall: number, ahead: number, whole: number }} right
687
- * @returns {boolean}
688
- */
689
- function cheaperThan(left, right) {
690
- if (left.stall !== right.stall) {
691
- return left.stall < right.stall;
692
- }
693
- if (left.ahead !== right.ahead) {
694
- return left.ahead < right.ahead;
695
- }
696
- return left.whole < right.whole;
697
- }
698
-
699
- /**
700
- * How long until a number is needed, read off the map.
701
- *
702
- * The map states it per stretch, for the stretch's NEAR EDGE, because a stretch
703
- * is met at its beginning. Every number inside is needed no sooner than that, so
704
- * taking the stretch's figure for all of them is the safe reading: it can only
705
- * make the filling earlier than it has to be, never later.
706
- *
707
- * Where the map says nothing, nobody is coming and nothing can be late.
708
- *
709
- * Inside a stretch the time GROWS with the distance, because a viewer covers a
710
- * second of film in a second: the number `n` places past the near edge is
711
- * reached `n` segments of film later. Taking the near edge's figure for every
712
- * number inside instead makes a whole stretch due at once measured while
713
- * building this: the first stretch is as wide as the measured allowance, so its
714
- * far end was demanded instantly and an encoder was placed on a number another
715
- * one was already writing.
716
- *
717
- * @param {WantedSpan[]} windows
718
- * @param {number} segmentSeconds - How much film one number holds.
719
- * @returns {(index: number) => number}
720
- */
721
- /** @param {WantedSpan[]} windows */
722
- function firstOf(windows) {
723
- return Math.min(...windows.map((span) => span.from));
724
- }
725
-
726
- /** @param {WantedSpan[]} windows */
727
- function lastOf(windows) {
728
- return Math.max(...windows.map((span) => span.to));
729
- }
730
-
731
- function deadlineReaderFor(windows, segmentSeconds) {
732
- const perSegment = segmentSeconds > 0 ? segmentSeconds : 0;
733
- return (index) => {
734
- let soonest = Number.POSITIVE_INFINITY;
735
- for (const span of windows) {
736
- if (index < span.from || index > span.to) {
737
- continue;
738
- }
739
- const stated = /** @type {{ withinSeconds?: number }} */ (span).withinSeconds;
740
- // A stretch stated with no time is somebody waiting at its near edge: that
741
- // is what stating one means. The rest of it grows with the distance, the
742
- // same as a stated one read as due all at once instead, a window as wide
743
- // as a viewer's cushion demanded its far end instantly and bought an
744
- // encoder to stand beside one already working.
745
- const within = stated === undefined ? 0 : Number(stated);
746
- if (!Number.isFinite(within)) {
747
- // Stated as no time at all: nobody is coming here.
748
- continue;
749
- }
750
- const here = within + (index - span.from) * perSegment;
751
- if (here < soonest) {
752
- soonest = here;
753
- }
754
- }
755
- return soonest;
756
- };
757
- }
758
-
759
- /**
760
- * WHERE ENCODERS BELONG, from the model rather than from a list of cases.
761
- *
762
- * The problem this solves, stated exactly:
763
- *
764
- * - the track is a line of segment numbers; `M` are the ones not made;
765
- * - each `x` carries a DEADLINE `D(x)`, the seconds until somebody needs it.
766
- * That is what the priority map is a reading of a viewer moving forward
767
- * covers a second of film in a second, so the time until they are at `x` is
768
- * the distance to it. `Infinity` where nobody is coming;
769
- * - an encoder is a SEQUENTIAL producer: placed at `a`, it delivers `a + j` at
770
- * time `(j + 1) / r`, where `r` is segments per second, measured. It cannot
771
- * skip, so its whole schedule follows from where it starts;
772
- * - the machine affords `k` of them, measured.
773
- *
774
- * Two consequences fall out and need no rule of their own. Placements
775
- * `a_1 < ... < a_k` PARTITION the line: encoder `i` is useful only on
776
- * `[a_i, a_{i+1})`, because past that its neighbour got there first. And a
777
- * segment served by encoder `i` arrives at `(x - a_i + 1) / r`, which is
778
- * therefore also the answer to "when would the encoder already placed before it
779
- * get here" the second half of the comparison, and the half that was missing.
780
- *
781
- * `x` is LATE when it arrives after `D(x)`. The objective is no late segments;
782
- * where `k` does not stretch to that, lateness beginning as far to the right as
783
- * possible.
784
- *
785
- * THE ALGORITHM is first-fit, left to right:
786
- *
787
- * for each missing x with a finite deadline, ascending:
788
- * if some encoder already placed at a satisfies (x - a + 1)/r <= D(x):
789
- * it covers x
790
- * else:
791
- * place an encoder at x
792
- *
793
- * A LIVE run enters as an encoder already placed at its own head. There is no
794
- * special case for it.
795
- *
796
- * WHY IT IS OPTIMAL. The leftmost missing number with a finite deadline must be
797
- * covered by somebody. An encoder placed exactly on it delivers it at the
798
- * earliest time any placement can, `1/r`, and covers the longest suffix any
799
- * placement can starting further left only re-makes material and arrives
800
- * later, starting further right does not cover it at all. So the greedy choice
801
- * is never worse than any other, and the usual exchange argument carries it to
802
- * the whole line. This is the known result for FIXED-ORDER scheduling with
803
- * deadlines, where first-fit is optimal at unit processing times, and a segment
804
- * is one unit. General machine minimisation with release times and deadlines is
805
- * NP-hard; this case is polynomial because the order is forced and each machine
806
- * covers a contiguous stretch.
807
- *
808
- * WHAT WAS TRIED FIRST AND WAS WRONG, kept because each looked reasonable:
809
- *
810
- * - `(h - p) * s / (1 - s)`, how long a run stays in front of a viewer moving
811
- * forward. It answers a different question: a viewer stopped with an empty
812
- * buffer needs the segment now, and at exactly realtime that formula says
813
- * "for ever" while the viewer waits thirteen minutes;
814
- * - whether a run's head lies inside a wanted band which ties an encoder to
815
- * whoever is standing there, and this layer must never know that;
816
- * - the run's head as a barrier, everything above it placeable. It has no time
817
- * in it at all, so it cannot tell two segments ahead from two hundred.
818
- *
819
- * Each was a case, not a model. The deadline is the model.
820
- *
821
- * @param {import("./CoverageMap.js").CoverageMap} coverage
822
- * @param {Set<object>} surviving - Runs that will still be alive, as encoders
823
- * already placed at their own heads.
824
- * @param {number} rate - Segments produced per second by one encoder, measured.
825
- * Zero when nothing has measured it, and then no arrival time can be computed
826
- * and every claimed number is left alone.
827
- * @returns {(at: number, bound: number, deadlineAt: (index: number) => number, alsoPlaced?: number[]) => number | null}
828
- */
829
- function gapFinderFor(coverage, surviving, rate, refetchSecPerSegment = 0) {
830
- /** Encoders already placed: where each stands, and how far its road runs. */
831
- const placed = [];
832
- for (const run of surviving) {
833
- const head = Number(/** @type {{ head?: number }} */ (run).head);
834
- placed.push({
835
- at: Number.isFinite(head) ? head : Number(/** @type {{ from: number }} */ (run).from),
836
- // A live run's road, so that placing inside it can be priced. A run given
837
- // no end drives to the end of the film, which is what makes the price real.
838
- // A run given no end drives to the end of the film, which is what makes
839
- // the price of cutting in front of it real. Written out rather than
840
- // imported: this file depends on nothing, and that is what lets it be
841
- // exercised with plain values alone.
842
- to: Number(/** @type {{ to: number }} */ (run).to) < Number(/** @type {{ from: number }} */ (run).from)
843
- ? Number.POSITIVE_INFINITY
844
- : Number(/** @type {{ to: number }} */ (run).to)
845
- });
846
- }
847
- return (at, bound, deadlineAt, alsoPlaced) => {
848
- const start = Number.isInteger(at) && at > 0 ? at : 0;
849
- const last = Number.isInteger(bound) ? bound : -1;
850
- // THE LATE NUMBER THAT IS DUE SOONEST, not the leftmost one.
851
- //
852
- // With room for every placement the two are the same answer. With a budget
853
- // that binds they are not, and the objective decides: lateness pushed as far
854
- // to the right as possible means the soonest deadline is served first. A
855
- // walk by number gave the one machine to a viewer due in ten minutes while
856
- // another stood waiting with an empty buffer.
857
- //
858
- // Ties go to the smaller number, so the answer does not depend on the order
859
- // the map happens to be in.
860
- let best = null;
861
- let bestDue = Number.POSITIVE_INFINITY;
862
- for (let index = start; index <= last; index += 1) {
863
- if (coverage.isReady(index)) {
864
- continue;
865
- }
866
- const deadline = deadlineAt(index);
867
- if (!Number.isFinite(deadline)) {
868
- // NOBODY IS COMING HERE, so nothing can be late but the film is still
869
- // wanted, and this is where spare capacity goes. The number is proposed;
870
- // whether an encoder is actually spent on it is the score's answer, and
871
- // the score puts anything anybody is waiting for first.
872
- return index;
873
- }
874
- // When would the SOONEST of those already placed get here? Encoders placed
875
- // EARLIER IN THIS PASS count: the first one placed for a viewer covers the
876
- // stretch in front of them, and without counting it the walk placed a
877
- // second and a third on the very next numbers — three processes a segment
878
- // apart for one person, which is the waste this model exists to refuse.
879
- let soonest = Number.POSITIVE_INFINITY;
880
- for (const a of [...placed.map((live) => live.at), ...(alsoPlaced ?? [])]) {
881
- if (a > index) {
882
- // Standing past it. Encoders only move forward, so it never will.
883
- continue;
884
- }
885
- if (a === index) {
886
- // Standing ON it. No placement is faster than the one already made.
887
- soonest = 0;
888
- break;
889
- }
890
- // WHEN THIS BODY GETS HERE, and both terms of it.
891
- //
892
- // Its own encoding of everything between, and the swarm's price for the
893
- // film it would fetch a SECOND time — every number between that is
894
- // already made, it makes again. That second term is why "should this
895
- // encoder drive on or be moved" is not a question of its own: an
896
- // encoder with three hundred made pieces in front of it is simply slow
897
- // to arrive, and the model compares arrivals. Asked separately it was a
898
- // second authority over the same encoder, and the two disagreed.
899
- const arrival = (index - a + 1) / rate
900
- + coverage.madeBetween(a, index) * refetchSecPerSegment;
901
- if (arrival < soonest) {
902
- soonest = arrival;
903
- }
904
- }
905
- if (soonest <= deadline) {
906
- // Somebody gets here in time. Nothing to decide.
907
- continue;
908
- }
909
- // IT IS LATE, AND THAT IS ALL THIS DECIDES. Whether filling it is worth
910
- // the price is not asked here: this only proposes candidates, and the
911
- // score decides how many of them are taken and by whom. Asked here as
912
- // well, it was a second cost model beside the objective with its own
913
- // idea of what a process costs — and the two disagreed at exactly
914
- // realtime, where every next piece is marginally late and each looked
915
- // worth its own encoder.
916
- if (deadline < bestDue) {
917
- best = index;
918
- bestDue = deadline;
919
- }
920
- }
921
- return best;
922
- };
923
- }
924
-
925
- /**
926
- * The last number of a stretch that begins at `from` and is `length` long.
927
- *
928
- * `-1` when the length is not finite, which is this layer's word for a run with
929
- * no end: the film's length is not known, so there is nothing to stop it at, and
930
- * a number invented here would be an end nobody measured.
931
- *
932
- * @param {number} from
933
- * @param {number} length
934
- * @returns {number}
935
- */
936
- function endOfStretch(from, length) {
937
- return Number.isFinite(length) ? from + Math.max(1, length) - 1 : -1;
938
- }
939
-
940
- /**
941
- * The lowest number a viewer is waiting for that is not ready — what the plan
942
- * is judged by.
943
- *
944
- * Not used to decide anything: it is the figure a log line carries, so that a
945
- * plan that keeps producing while a viewer waits is visible rather than
946
- * inferred.
947
- *
948
- * @param {import("./CoverageMap.js").CoverageMap} coverage
949
- * @param {WantedSpan[]} windows
950
- * @returns {number | null}
951
- */
952
- export function firstUnmetWant(coverage, windows) {
953
- let lowest = null;
954
- for (const span of windows ?? []) {
955
- for (let at = span.from; at <= span.to; at += 1) {
956
- if (!coverage.isReady(at)) {
957
- if (lowest === null || at < lowest) {
958
- lowest = at;
959
- }
960
- break;
961
- }
962
- }
963
- }
964
- return lowest;
965
- }
966
-
967
- /**
968
- * Where to put the encoders this machine can afford.
969
- *
970
- * Two things are wanted of a division of the film, and they are wanted in this
971
- * order:
972
- *
973
- * 1. **the viewer must not stop.** An encoder starting at `q` stays ahead of a
974
- * viewer at `p` while `y / s <= q + y - p`, so it holds `(q - p) * s / (1-s)`
975
- * of film and no more. Beyond that the viewer catches it, and the next
976
- * encoder has to be standing there. That is where the first ones go, and it
977
- * is why the stretches grow: the further off one starts, the later the
978
- * viewer arrives and the longer it may work;
979
- * 2. **the film should be finished as soon as possible.** Once the viewer is
980
- * safe, whatever is left is divided EQUALLY between the encoders that
981
- * remain: equal shares finish together, and any other division finishes when
982
- * its longest share does. That is what makes seeking cheap — the film exists.
983
- *
984
- * At or above realtime the first requirement is met by one encoder for the
985
- * whole film, and every other encoder goes to the second — which is the common
986
- * case on a copied picture, and is why "one viewer, one encoder" was never the
987
- * rule.
988
- *
989
- * @param {object} params
990
- * @param {import("./CoverageMap.js").CoverageMap} params.coverage
991
- * @param {WantedSpan[]} params.windows - The merged map, in this output's own
992
- * numbering. Its highest-numbered band starts where the viewer is.
993
- * @param {number} params.howMany - What the machine affords.
994
- * @param {number} params.speedX - Measured. Zero when nothing has measured it,
995
- * and then only the first requirement can be served.
996
- * @param {(at: number, bound: number, deadlineAt: (index: number) => number, placed: number[]) => number | null} [params.firstGap] -
997
- * Where a gap may be opened. Defaults to the map's own answer; the plan hands
998
- * in one that also counts a number a live run has claimed but will not reach
999
- * before it is needed, which is the only way anybody beyond a working encoder
1000
- * is served.
1001
- * @param {(index: number) => number} [params.deadlineAt] - Seconds until that
1002
- * number is needed. `Infinity` where nobody is coming. Absent means every
1003
- * stated want is due now.
1004
- * @returns {number[]} Where to start each encoder, ascending.
1005
- */
1006
- export function placeEncoders({ coverage, windows, howMany, firstGap = null, deadlineAt = null }) {
1007
- if (!(howMany > 0) || windows.length === 0) {
1008
- return [];
1009
- }
1010
- // NOW when the caller says nothing. A stated want with no time is somebody
1011
- // waiting on it that is what stating one means so the honest reading is
1012
- // that it is due. `Infinity` is a statement in its own right and has to be
1013
- // made: it says nobody is coming.
1014
- const untilNeeded = deadlineAt ?? (() => 0);
1015
- /** Where this pass has placed so far each one covers what it can reach. */
1016
- const placedHere = [];
1017
- const gapAt = firstGap
1018
- ? (at, bound) => firstGap(at, bound, untilNeeded, placedHere)
1019
- : (at, bound) => coverage.firstGapFrom(at, bound);
1020
-
1021
-
1022
- // CANDIDATES COME FROM THE PRIORITY MAP, IN THE ORDER THE MAP STATES.
1023
- //
1024
- // The map already answers every question that was being re-derived here. Its
1025
- // ranks say what matters most the number a viewer is stopped on, then what
1026
- // is in front of them band by band, then the rest of the track, and last of
1027
- // all what lies behind them. A pause flattens those ranks; a seek moves them;
1028
- // a second viewer merges into them. So walking the map in its own order is
1029
- // what "ahead before behind" means, and nothing here has to work out where the
1030
- // viewers are.
1031
- //
1032
- // It was not read that way. This walked the film by number and proposed
1033
- // whatever was late, then a second pass divided the leftovers — an order of
1034
- // its own invention, which put the beginning of the file before the film in
1035
- // front of a viewer and, at one point, proposed #0, #1 and #2 as three
1036
- // separate places.
1037
- //
1038
- // One candidate per zone: the first number in it nobody has and nobody
1039
- // reaches in time. Zones with no deadline can have nothing late in them, so
1040
- // there it is simply the first number nobody has — which is how spare capacity
1041
- // comes to finish the file.
1042
- /** @type {number[]} */
1043
- const places = [];
1044
- const byRank = [...windows].sort(
1045
- (left, right) => (right.priority ?? 0) - (left.priority ?? 0) || left.from - right.from
1046
- );
1047
- for (const zone of byRank) {
1048
- if (places.length >= howMany) {
1049
- break;
1050
- }
1051
- const at = gapAt(zone.from, zone.to);
1052
- if (at === null || places.includes(at)) {
1053
- continue;
1054
- }
1055
- places.push(at);
1056
- placedHere.push(at);
1057
- }
1058
-
1059
- // AND WHERE TO SPLIT WHAT IS LEFT, for the capacity the map has not spent.
1060
- //
1061
- // The search above proposes only what is LATE, so once one encoder covers a
1062
- // zone in time that zone proposes nothing more — and a machine that holds four
1063
- // ran one. Finishing a contiguous stretch soonest with several machines of the
1064
- // same speed means dividing it between them, which is where these come from:
1065
- // the widest run of film between two encoders, split.
1066
- //
1067
- // Proposing is not spending. The score decides whether another process is
1068
- // worth it, and its first term how late the film is always outranks its
1069
- // second, so this can never take capacity from somebody waiting.
1070
- while (places.length < howMany) {
1071
- const edges = [...places].sort((left, right) => left - right);
1072
- let widestFrom = null;
1073
- let widest = 0;
1074
- for (let index = 0; index <= edges.length; index += 1) {
1075
- const from = index === 0 ? firstOf(windows) : edges[index - 1] + 1;
1076
- const to = index === edges.length ? lastOf(windows) : edges[index] - 1;
1077
- const room_ = coverage.unmadeRunFrom(from);
1078
- if (to >= from && room_ > widest) {
1079
- widest = room_;
1080
- widestFrom = from + Math.floor(Math.min(room_, to - from + 1) / 2);
1081
- }
1082
- }
1083
- if (widestFrom === null) {
1084
- break;
1085
- }
1086
- const at = coverage.firstGapFrom(widestFrom, lastOf(windows));
1087
- if (at === null || places.includes(at)) {
1088
- break;
1089
- }
1090
- places.push(at);
1091
- placedHere.push(at);
1092
- }
1093
-
1094
- // These are CANDIDATES, not decisions. What is late proposes first, because
1095
- // that is what a viewer feels; what is merely unmade proposes after it. The
1096
- // score decides which of them are worth a process, and a paused viewer, who
1097
- // states no deadline at all, therefore still leaves the file being finished
1098
- // rather than the machine falling idle.
1099
- return places.sort((left, right) => left - right);
1100
- }
1101
-
1
+ /**
2
+ * @file How many encoders there should be on one output, and where each of them
3
+ * belongs — decided from numbers alone.
4
+ *
5
+ * The decision is separated from carrying it out on purpose. Every rule below
6
+ * was previously a condition somewhere inside an eleven-thousand-line file,
7
+ * reachable only by starting a real ffmpeg, and each of them was written for
8
+ * one viewer:
9
+ *
10
+ * - a run was placed at the position of whoever asked, and never at the first
11
+ * thing missing, so a viewer moving into a stretch already on disk restarted
12
+ * an encoder to make it a second time;
13
+ * - a run had no end at all — neither `-to` nor `-t` appeared anywhere — so it
14
+ * ran until something killed it, and two runs on one output could not exist
15
+ * without writing over each other;
16
+ * - nothing stopped a run that had caught up with material somebody else had
17
+ * already made.
18
+ *
19
+ * The rule this file exists to express, stated by the user 2026-09-04:
20
+ *
21
+ * > Viewers are always independent and always reuse what can be reused. The
22
+ * > number of encoders is however many are needed; how many are needed follows
23
+ * > from which sets of output parameters are wanted and where the viewers stand
24
+ * > inside each. Segments produced by ANY encoder are available to ANY viewer,
25
+ * > and which viewer asked never enters the question.
26
+ *
27
+ * So no name of a viewer reaches this file. It is given what is wanted, what
28
+ * exists, what is being made, and what the machine can afford.
29
+ *
30
+ * **A viewer decides the ORDER the map is walked in and, through the budget, how
31
+ * many processes walk it. Nothing else.** Stated by the user 2026-09-05, and it
32
+ * is the rule the rest of this file now follows: while a file is being encoded
33
+ * it is encoded WHOLE, in the order the map dictates. Who wants which segment
34
+ * decides which gap is closed first, never whether a run may go on living.
35
+ *
36
+ * **A run is therefore never stopped for standing outside a viewer's window.**
37
+ * It used to be, and the two decisions that produced that were in direct
38
+ * contradiction — measured in the field 2026-09-05 on a viewer watching an
39
+ * episode:
40
+ *
41
+ * 1. this file commanded a start inside the window, at #46;
42
+ * 2. `planRunInterval` in the session manager moved the start to #78, because
43
+ * it counted a suspended run's claim as reaching `head + look-ahead`;
44
+ * 3. this file then saw a run at #78 against a window of [27, 57], found no
45
+ * overlap, and killed it as "nothing it was given is wanted";
46
+ * 4. neither coverage nor demand had changed, so the same start was commanded
47
+ * again — 350-700ms per cycle, dozens of times, no segment ever produced,
48
+ * the viewer's picture stopped for 125 seconds.
49
+ *
50
+ * Both of those other authorities are gone (roadmap item 76, step 5). What is
51
+ * left is this file, and the only reasons it stops a run are: nobody is
52
+ * watching the output at all; the machine affords fewer processes; or there is
53
+ * nothing left unmade anywhere in the track.
54
+ *
55
+ * **A run's end comes from the coverage**, never from a window: it runs until
56
+ * it meets material somebody else has made or is making, or until the end of
57
+ * the film.
58
+ */
59
+
60
+ /**
61
+ * One encoder that is running now.
62
+ *
63
+ * @typedef {object} LiveRun
64
+ * @property {string} id
65
+ * @property {number} from - The first number it was given.
66
+ * @property {number} to - The last number it was given, inclusive.
67
+ * @property {number} head - The next number it will produce. Its position.
68
+ * @property {number} speedX - Measured encode speed against realtime, from
69
+ * ffmpeg's own progress. Zero or less means nothing has measured it yet, and
70
+ * then no comparison involving its speed can be made.
71
+ */
72
+
73
+ /**
74
+ * What a viewer is waiting for. Which viewer is deliberately absent.
75
+ *
76
+ * @typedef {object} WantedSpan
77
+ * @property {number} from
78
+ * @property {number} to
79
+ */
80
+
81
+ /**
82
+ * @typedef {{ type: "start", from: number, to: number, because: string }
83
+ * | { type: "move", run: object, from: number, to: number, because: string }
84
+ * | { type: "stop", run: object, because: string }
85
+ * | { type: "keep", run: object, from: number, to: number }} PlanAction
86
+ */
87
+
88
+ /**
89
+ * Decide what to do with the encoders on one output.
90
+ *
91
+ * @param {object} params
92
+ * @param {import("./CoverageMap.js").CoverageMap} params.coverage - What has
93
+ * been made and what is being made.
94
+ * @param {WantedSpan[]} params.windows - What viewers are waiting for, one
95
+ * window each. Empty means nobody is watching this output.
96
+ * @param {LiveRun[]} params.runs - The encoders running on it now.
97
+ * @param {number} params.maxRuns - How many encoders this machine can afford on
98
+ * this output. Comes from the same arithmetic that decides the quality offer;
99
+ * it is measured per host and never chosen here.
100
+ * @param {number} params.segmentSeconds - How much film one segment holds.
101
+ * @param {number} [params.killCostSec] - How long stopping an encoder takes,
102
+ * measured on this host from its own runs. Zero until something has measured
103
+ * it, which makes moving one look cheaper than it is and is said here so the
104
+ * bias is known.
105
+ * @param {number} [params.moveCostSec] - What moving a running encoder costs on
106
+ * this host, measured. `Infinity` until something has been measured, because a
107
+ * move is irreversible and leaving the encoder alone is always available.
108
+ * @param {number} [params.now] - The clock, injected. This layer is arithmetic
109
+ * and reads no clock of its own; how old a run is is one of its inputs.
110
+ * @param {number} [params.firstByteWaitSec] - How long a fresh encoder takes to
111
+ * produce anything: process start, opening the input, and the first piece.
112
+ * Measured the same way. It replaced a constant of 0.12 s taken from one
113
+ * host and charged to every other.
114
+ * @param {(others: number) => number} [params.contentionPenaltyFor] - How much
115
+ * slower ONE encoder runs with that many others beside it, measured on this
116
+ * host. Without it every extra process looks free, and the score then wants an
117
+ * encoder per piece: at exactly realtime each next piece is marginally late
118
+ * however many are running, so another one always seemed to help a little.
119
+ * Unmeasured is 1, and then the budget is the only thing bounding the count.
120
+ * @returns {PlanAction[]} Stops first, then moves, then starts, so that a plan
121
+ * carried out in order never holds two encoders where it means to hold one.
122
+ */
123
+ export function planEncoders({
124
+ coverage,
125
+ windows,
126
+ runs,
127
+ maxRuns,
128
+ segmentSeconds,
129
+ killCostSec = 0,
130
+ firstByteWaitSec = 0,
131
+ moveCostSec = Number.POSITIVE_INFINITY,
132
+ now = Date.now(),
133
+ refetchSecPerFilmSecond = 0,
134
+ contentionPenaltyFor = () => 1,
135
+ speedX = 0
136
+ }) {
137
+ /** @type {PlanAction[]} */
138
+ const stops = [];
139
+ /** @type {PlanAction[]} */
140
+ const moves = [];
141
+ /** @type {PlanAction[]} */
142
+ const starts = [];
143
+ /** @type {PlanAction[]} */
144
+ const keeps = [];
145
+
146
+ const wanted = Array.isArray(windows) ? windows : [];
147
+ const live = Array.isArray(runs) ? runs : [];
148
+
149
+ // Nobody is watching this output: every encoder on it is making segments for
150
+ // no one. This is the case a look-ahead cannot answer, because look-ahead
151
+ // asks how far AHEAD of a viewer a run is and there is no viewer.
152
+ if (wanted.length === 0) {
153
+ for (const run of live) {
154
+ stops.push({ type: "stop", run, because: "nobody is watching this output" });
155
+ }
156
+ return stops;
157
+ }
158
+
159
+ const untilNeeded = deadlineReaderFor(wanted, segmentSeconds);
160
+ // Segments produced per second, from the fastest measured encoder here.
161
+ // Seconds of film per second, divided by the film one piece holds.
162
+ //
163
+ // A RUN WORKING ON THIS OUTPUT OUTRANKS THE BENCHMARK. The startup figure is
164
+ // what this host does on reference clips; a run here is what it does on THIS
165
+ // material, and that is the more specific statement. Taken as a floor instead
166
+ // the larger of the two an encoder reporting half realtime was scored as
167
+ // though it ran at twice, and nothing was ever late.
168
+ const working = live.reduce((best, run) => Math.max(best, run.speedX || 0), 0);
169
+ const rate = segmentSeconds > 0 ? (working > 0 ? working : speedX) / segmentSeconds : 0;
170
+ // How long one piece takes AT THE RATE ACTUALLY IN FORCE. Concurrent encoders
171
+ // slow each other measured on this host so an arrangement's own body count
172
+ // decides it, and the delays below are computed per arrangement for that
173
+ // reason. Taken from the unpenalised rate instead, a piece looked cheaper the
174
+ // more bodies there were, which made extra bodies look free: the plan bought a
175
+ // second encoder where one served, and the arrivals it was compared on were
176
+ // computed at the slower rate all along.
177
+ //
178
+ // `Infinity` where nothing has been measured, which is what "no speed" means
179
+ // and what makes every arrangement equally hopeless rather than equally free.
180
+ const pieceAt = (howManyBodies) => {
181
+ const inForce = rate / contentionPenaltyFor(Math.max(0, howManyBodies - 1));
182
+ return inForce > 0 ? 1 / inForce : Number.POSITIVE_INFINITY;
183
+ };
184
+ // What a body costs to take away from where it stands and put somewhere else:
185
+ // its death, the start of another, and the wait for the first bytes there.
186
+ // Taking an encoder somewhere else is stopping this one and waiting for the
187
+ // next to produce. Both halves are measured on this host.
188
+ // WHAT A MOVE COSTS. Killing an encoder and waiting for a fresh one's first
189
+ // piece is the price; until something has produced anything on this host that
190
+ // price is unknown, and a move is then refused rather than priced at zero.
191
+ // Placing one where there is none is the other question and takes the unknown
192
+ // the other way — see `run-costs.js`.
193
+ const moveSec = Number.isFinite(moveCostSec) ? moveCostSec : killCostSec + firstByteWaitSec;
194
+
195
+ // WHAT A RUN STILL HAS TO GO BEFORE IT PRODUCES ANYTHING — the measured time
196
+ // to a first piece, less the time it has already been alive.
197
+ //
198
+ // This is the memory the score was missing. It is computed afresh whenever
199
+ // anything changes, and every arrangement used to be priced as though it were
200
+ // the last decision anybody would take: a run that started 10 ms ago was
201
+ // assumed to produce instantly, so killing it and starting another looked like
202
+ // a straight gain. A move is justified by a benefit that arrives when the
203
+ // moved run produces something; taken again before it has, the benefit is
204
+ // never collected and the cost is paid twice, three times, forty times.
205
+ //
206
+ // A run 0.8 s old has 0.14 s left to go against 0.94 s to move it, so it is
207
+ // left alone; one working for half a minute has nothing left, and a move
208
+ // happens exactly when the film it would reach sooner is worth the restart. No
209
+ // state to keep and nothing to choose: one measured figure minus elapsed time.
210
+ const finishesItsPieceIn = (run, perPiece) => {
211
+ // WHEN THIS RUN FINISHES THE PIECE IT IS STANDING ON.
212
+ //
213
+ // Two cases and neither is a choice: a run that has produced something is
214
+ // working at a known rate, so the piece under it lands within one piece's
215
+ // worth of time; a run that has produced nothing is still in its warm-up,
216
+ // and what is left of that is the measured time to a first piece less the
217
+ // time it has already been alive.
218
+ //
219
+ // This is the memory the score was missing. It is computed afresh whenever
220
+ // anything changes, and each arrangement used to be priced as though it were
221
+ // the last decision anybody would take: a run 0.8 s into a 0.9 s piece was
222
+ // charged a whole piece for it, the same as one about to start, so killing
223
+ // it and beginning again elsewhere looked cheaper by ten milliseconds. A
224
+ // move is justified by a benefit that arrives when the moved run produces
225
+ // something; taken again before it has, the benefit is never collected and
226
+ // the cost is paid twice, three times, forty times.
227
+ //
228
+ // One measured figure minus elapsed time. Nothing to keep and nothing to
229
+ // choose.
230
+ if (Number(run.head) !== Number(run.from)) {
231
+ return perPiece;
232
+ }
233
+ const startedAt = Number(run.startedAt);
234
+ if (!Number.isFinite(startedAt) || startedAt <= 0) {
235
+ return firstByteWaitSec;
236
+ }
237
+ return Math.max(0, firstByteWaitSec - (now - startedAt) / 1000);
238
+ };
239
+
240
+ // WHAT EACH BODY OWES BEFORE THE PIECE IT STANDS ON EXISTS, priced at the rate
241
+ // the arrangement itself puts in force.
242
+ //
243
+ // Each body states its own debt where it is created, as a function of what one
244
+ // piece costs — because only there is it known what the body IS, and here only
245
+ // how many of them there are. So there is nothing to dispatch on: no kind, no
246
+ // tag, no case analysis. The count is known before any debt is needed, which
247
+ // is why this is one pass over the bodies rather than a figure computed once
248
+ // outside.
249
+ const priced = (bodies) => {
250
+ const perPiece = pieceAt(bodies.length);
251
+ return bodies.map((body) => ({ at: body.at, delaySec: body.owes(perPiece) }));
252
+ };
253
+
254
+
255
+ // ------------------------------------------------------------------ WHERE
256
+ //
257
+ // A question about the FILM, and about nothing else: which numbers are
258
+ // missing, when each is needed, how fast this machine encodes, how many
259
+ // processes it can hold. No encoder that happens to be running enters it,
260
+ // which is why it can be answered by arithmetic.
261
+ const positions = placeEncoders({
262
+ coverage,
263
+ windows: wanted,
264
+ howMany: maxRuns,
265
+ // EVERY LIVE ENCODER IS PRE-PLACED, because that is what "somebody already
266
+ // gets here in time" means. A number one of them reaches before it is
267
+ // needed is not a position at all; a number none of them reaches is, and
268
+ // needs a body brought to it. There is no third case, and in particular no
269
+ // separate question of whether an encoder should drive on or be moved:
270
+ // driving is simply its arrival, and its arrival is priced in one place.
271
+ firstGap: gapFinderFor(coverage, new Set(live), rate, segmentSeconds * refetchSecPerFilmSecond),
272
+ deadlineAt: untilNeeded
273
+ });
274
+
275
+ // -------------------------------------------------------------------- WHO
276
+ //
277
+ // ARGMIN OF THE OBJECTIVE, EVALUATED. Not a rule that approximates it.
278
+ //
279
+ // Every way of filling the positions is scored by `latenessOf` and the best is
280
+ // taken. There are at most a handful of positions and a handful of bodies, so
281
+ // the enumeration is exact: no local rule stands in for the objective, and
282
+ // none can therefore disagree with another.
283
+ //
284
+ // Four such rules were written before this and all four had to go — "place
285
+ // where a number is late", "take a body that serves nothing", "take one whose
286
+ // work is needed later than this", "drive on or move, by cost". Each looked
287
+ // like a consequence of the model and each approximated it from a different
288
+ // side, so together they contradicted one another and the answer depended on
289
+ // which ran first.
290
+ /** One decision per live encoder, so none can be decided twice. @type {Map<object, PlanAction>} */
291
+ const decided = new Map();
292
+ const room = Math.max(0, maxRuns - live.length);
293
+ const refetchPerSegment = segmentSeconds * refetchSecPerFilmSecond;
294
+
295
+ let arrangements = [{ fill: [], used: new Set(), fresh: 0 }];
296
+ for (let index = 0; index < positions.length; index += 1) {
297
+ const next = [];
298
+ for (const arrangement of arrangements) {
299
+ next.push({ fill: [...arrangement.fill, null], used: arrangement.used, fresh: arrangement.fresh });
300
+ // A FRESH PROCESS IS OFFERED BEFORE ANY WORKING BODY, so that when the two
301
+ // score the same the working one is left alone. Taking it is free in the
302
+ // arithmetic — its output stays on disk — but it is not free in fact: the
303
+ // run it belongs to has a position, a warm input and a measured speed, and
304
+ // all three are thrown away for nothing.
305
+ if (arrangement.fresh < room) {
306
+ next.push({
307
+ fill: [...arrangement.fill, "new"],
308
+ used: arrangement.used,
309
+ fresh: arrangement.fresh + 1
310
+ });
311
+ }
312
+ for (const run of live) {
313
+ if (arrangement.used.has(run)) {
314
+ continue;
315
+ }
316
+ next.push({
317
+ fill: [...arrangement.fill, run],
318
+ used: new Set([...arrangement.used, run]),
319
+ fresh: arrangement.fresh
320
+ });
321
+ }
322
+ }
323
+ arrangements = next;
324
+ }
325
+
326
+ let best = null;
327
+ let bestScore = null;
328
+ for (const arrangement of arrangements) {
329
+ const bodies = [];
330
+ for (let index = 0; index < positions.length; index += 1) {
331
+ const filler = arrangement.fill[index];
332
+ if (filler === null) {
333
+ continue;
334
+ }
335
+ if (filler === "new") {
336
+ // A body that does not exist yet owes its own start and then the piece.
337
+ bodies.push({ at: positions[index], owes: (piece) => firstByteWaitSec + piece });
338
+ continue;
339
+ }
340
+ const head = Number(filler.head);
341
+ // Left where it stands it owes what is left of the piece under it; taken
342
+ // somewhere else it owes the killing, the start and a whole piece.
343
+ bodies.push({
344
+ at: positions[index],
345
+ owes: head === positions[index]
346
+ ? (piece) => finishesItsPieceIn(filler, piece)
347
+ : (piece) => moveSec + piece
348
+ });
349
+ }
350
+ // Bodies nobody was given a position for go on working where they stand,
351
+ // and their coverage counts: the file is encoded whole.
352
+ //
353
+ // A body given no end pays a restart the moment anybody is placed inside the
354
+ // road it would drive: where a run stops is fixed when its process starts,
355
+ // so it has to be cut and begun again at its own head. That price was
356
+ // invisible here, and an arrangement was scored as free when it was not.
357
+ for (const run of live) {
358
+ if (arrangement.used.has(run)) {
359
+ continue;
360
+ }
361
+ const head = Number(run.head);
362
+ const endless = Number(run.to) < Number(run.from);
363
+ const cutInFront = arrangement.fill.some((filler, index) =>
364
+ filler !== null && positions[index] > head
365
+ && (endless || positions[index] <= Number(run.to)));
366
+ bodies.push({
367
+ at: head,
368
+ owes: cutInFront
369
+ ? (piece) => moveSec + piece
370
+ : (piece) => finishesItsPieceIn(run, piece)
371
+ });
372
+ }
373
+ const scored = latenessOf(priced(bodies), coverage, wanted, untilNeeded, rate / contentionPenaltyFor(Math.max(0, bodies.length - 1)), refetchPerSegment, segmentSeconds);
374
+ if (bestScore === null || cheaperThan(scored, bestScore)) {
375
+ bestScore = scored;
376
+ best = arrangement;
377
+ }
378
+ }
379
+
380
+ // A BODY STANDING ON FILM THAT EXISTS is the one arrangement the enumeration
381
+ // above cannot reach: the gap in front of it is nobody's deadline, so it is
382
+ // never a position, and the body is left to make three hundred pieces a second
383
+ // time. Each such body is offered its own first gap and the SAME score decides
384
+ // — moving costs a restart on everything downstream, staying costs the repeat.
385
+ //
386
+ // Offered one at a time rather than folded into the enumeration because the
387
+ // enumeration is exponential in the number of positions, and this is called
388
+ // again on every piece produced. One extra evaluation per body against
389
+ // several thousand arrangements is the difference between arithmetic and a
390
+ // stalled proxy.
391
+ const placement = new Map();
392
+ for (let index = 0; index < positions.length; index += 1) {
393
+ const filler = best ? best.fill[index] : null;
394
+ if (filler && filler !== "new") {
395
+ placement.set(filler, positions[index]);
396
+ }
397
+ }
398
+ const bodiesOf = (override) => {
399
+ const bodies = [];
400
+ for (const run of live) {
401
+ if (override.has(run) && override.get(run) === null) {
402
+ // Asked what the film looks like WITHOUT this one.
403
+ continue;
404
+ }
405
+ const at = override.has(run) ? override.get(run) : (placement.get(run) ?? Number(run.head));
406
+ const head = Number(run.head);
407
+ bodies.push({
408
+ at,
409
+ owes: at === head
410
+ ? (piece) => finishesItsPieceIn(run, piece)
411
+ : (piece) => moveSec + piece
412
+ });
413
+ }
414
+ for (let index = 0; index < positions.length; index += 1) {
415
+ if ((best ? best.fill[index] : null) === "new") {
416
+ bodies.push({ at: positions[index], owes: (piece) => firstByteWaitSec + piece });
417
+ }
418
+ }
419
+ return priced(bodies);
420
+ };
421
+ const scoreOf = (override) => {
422
+ const bodies = bodiesOf(override);
423
+ return latenessOf(bodies, coverage, wanted, untilNeeded,
424
+ rate / contentionPenaltyFor(Math.max(0, bodies.length - 1)), refetchPerSegment, segmentSeconds);
425
+ };
426
+ for (const run of live) {
427
+ if (placement.has(run)) {
428
+ continue;
429
+ }
430
+ const gap = coverage.firstGapFrom(run.head, undefined, run);
431
+ if (gap === null || gap === Number(run.head)) {
432
+ continue;
433
+ }
434
+ const asIs = scoreOf(new Map());
435
+ const moved = scoreOf(new Map([[run, gap]]));
436
+ if (cheaperThan(moved, asIs)) {
437
+ placement.set(run, gap);
438
+ }
439
+ }
440
+
441
+ /**
442
+ * Would the film be worse off without this body? Asked of the same score.
443
+ *
444
+ * @param {object} run
445
+ * @returns {boolean}
446
+ */
447
+ const worseWithout = (run) => {
448
+ const kept = bodiesOf(new Map());
449
+ const without = bodiesOf(new Map([[run, null]]));
450
+ const scoreOf_ = (bodies) => latenessOf(bodies, coverage, wanted, untilNeeded,
451
+ rate / contentionPenaltyFor(Math.max(0, bodies.length - 1)), refetchPerSegment, segmentSeconds);
452
+ return cheaperThan(scoreOf_(kept), scoreOf_(without));
453
+ };
454
+
455
+ const stretchAt = (from) => endOfStretch(from, Math.min(
456
+ coverage.unmadeRunFrom(from),
457
+ coverage.freeRunFrom(from, new Set(live))
458
+ ));
459
+
460
+ for (let index = 0; index < positions.length; index += 1) {
461
+ if ((best ? best.fill[index] : null) !== "new") {
462
+ continue;
463
+ }
464
+ const at = positions[index];
465
+ starts.push({
466
+ type: "start",
467
+ from: at,
468
+ to: stretchAt(at),
469
+ because: `#${at} is wanted and nobody reaches it in time`
470
+ });
471
+ }
472
+
473
+ for (const run of live) {
474
+ const head = Number(run.head);
475
+ const at = placement.has(run) ? placement.get(run) : head;
476
+ if (at !== head) {
477
+ decided.set(run, {
478
+ type: "move",
479
+ run,
480
+ from: at,
481
+ to: stretchAt(at),
482
+ because: `standing at #${head} scores worse than standing at #${at}, counting ` +
483
+ "both how late the film would be and the work that would be done twice"
484
+ });
485
+ continue;
486
+ }
487
+ // It stays where it is — unless holding it changes nothing.
488
+ //
489
+ // A body left over from where a viewer used to be goes on costing the
490
+ // machine a process while another encoder already reaches everything it
491
+ // would. The score says so directly: take it away and see. Removing it is
492
+ // refused the moment it makes anything later or leaves film abandoned, so
493
+ // this cannot quietly drop the encoder somebody is waiting on.
494
+ if (!placement.has(run) && !worseWithout(run)) {
495
+ stops.push({
496
+ type: "stop",
497
+ run,
498
+ because: "the film is no worse off without it"
499
+ });
500
+ continue;
501
+ }
502
+ decided.set(run, { type: "keep", run, from: head, to: run.to });
503
+ }
504
+
505
+ // THE MACHINE'S LIMIT BINDS, whatever the map wants. It is measured — the
506
+ // processor, the swarm and the piece store each give a figure and the smallest
507
+ // wins and an encoder over it is one the host cannot feed. Which of them
508
+ // goes is the same question as any other here: the one the film misses least,
509
+ // by the same score.
510
+ while (decided.size + starts.length > maxRuns) {
511
+ let cheapest = null;
512
+ let cheapestScore = null;
513
+ for (const [run, action] of decided) {
514
+ if (action.type !== "keep") {
515
+ continue;
516
+ }
517
+ const without = latenessOf(bodiesOf(new Map([[run, null]])), coverage, wanted, untilNeeded,
518
+ rate / contentionPenaltyFor(Math.max(0, live.length - 2)), refetchPerSegment, segmentSeconds);
519
+ if (cheapestScore === null || cheaperThan(without, cheapestScore)) {
520
+ cheapestScore = without;
521
+ cheapest = run;
522
+ }
523
+ }
524
+ if (cheapest === null) {
525
+ break;
526
+ }
527
+ decided.delete(cheapest);
528
+ placement.delete(cheapest);
529
+ stops.push({
530
+ type: "stop",
531
+ run: cheapest,
532
+ because: `the machine holds ${maxRuns} encoder(s) on this output and this is the one ` +
533
+ "the film misses least"
534
+ });
535
+ }
536
+
537
+ for (const action of decided.values()) {
538
+ if (action.type === "keep") {
539
+ keeps.push(action);
540
+ } else {
541
+ moves.push(action);
542
+ }
543
+ }
544
+
545
+ // ONE ENCODER'S WORK ENDS WHERE THE NEXT ONE'S BEGINS.
546
+ //
547
+ // A free stretch may run to the end of the track, and an encoder given all of
548
+ // it stands in the road of every encoder placed behind it: they write the
549
+ // same names, and each one's output is the other's "material somebody else
550
+ // made", so they stop one another. Field 2026-09-05: three encoders started
551
+ // on one track within 200 ms, each into the road another was already writing.
552
+ // Fifteen readers on a piece store that holds sixteen pieces followed, half
553
+ // of all evictions took a piece a reader had declared, and `/stream` began
554
+ // handing out bytes that were not the file's.
555
+ //
556
+ // The bound is taken from the NEXT ENCODER'S START, not from a band edge: a
557
+ // band edge travels with the viewer, so every step forward would leave a
558
+ // sliver just past the previous encoder and buy an encoder for it.
559
+ // A RUN THAT IS STAYING IS IN THE SORT TOO, because its road can be taken.
560
+ //
561
+ // It used to be left out, on the reading that a run staying put keeps what it
562
+ // was given. That is true of the stretch it was GIVEN and false of the road it
563
+ // will actually drive: a run with no end carries no `-to` and walks to the end
564
+ // of the film, so an encoder placed in front of it writes the same names.
565
+ const placed = [...moves, ...starts, ...keeps].sort(
566
+ (left, right) => /** @type {any} */ (left).from - /** @type {any} */ (right).from
567
+ );
568
+ for (let index = 0; index < placed.length - 1; index += 1) {
569
+ const here = /** @type {{ type: string, run?: object, from: number, to: number }} */ (placed[index]);
570
+ const next = /** @type {{ from: number }} */ (placed[index + 1]);
571
+ if (here.to >= 0 && here.to < next.from) {
572
+ continue;
573
+ }
574
+ here.to = next.from - 1;
575
+ if (here.type !== "keep") {
576
+ continue;
577
+ }
578
+ // SHORTENING A LIVE RUN'S ROAD MEANS STOPPING IT, not merely writing a
579
+ // smaller number down. Where a run's end goes is fixed when its process
580
+ // starts, so one that was given none keeps producing past any bound decided
581
+ // later and would write one piece into the new encoder's road — two
582
+ // processes on one name, which is the collision this whole pass exists to
583
+ // prevent. So it ends here and begins again at its own head with a real end;
584
+ // the viewer in front pays a restart, which is a cost this file already
585
+ // prices rather than a interruption nobody counted.
586
+ keeps.splice(keeps.indexOf(here), 1);
587
+ moves.push({
588
+ type: "move",
589
+ run: here.run,
590
+ from: here.from,
591
+ to: here.to,
592
+ because:
593
+ `an encoder is needed at #${next.from}, which this run would reach only by ` +
594
+ "encoding through; it takes the road up to there and ends by itself"
595
+ });
596
+ }
597
+
598
+ return [...stops, ...moves, ...starts, ...keeps];
599
+ }
600
+
601
+
602
+
603
+ /**
604
+ * THE OBJECTIVE, as a value that can be compared.
605
+ *
606
+ * THREE COUNTS OF SECONDS, COMPARED IN ORDER. The order is the user's, stated
607
+ * 2026-09-06, and a later count decides only where the earlier ones tie:
608
+ *
609
+ * 1. SECONDS ANYBODY SPENDS LOOKING AT A SPINNER. Nothing outranks it, at any
610
+ * size. Walked forward in film order rather than summed piece by piece: a
611
+ * viewer who is stopped is not watching, so a wait moves every deadline
612
+ * behind it by its own length;
613
+ *
614
+ * 2. WHEN THE FILM IN FRONT OF THE VIEWERS IS FINISHED — the last piece of it to
615
+ * be made, whichever encoder makes it. A stretch no encoder will ever reach
616
+ * counts as never, which is what stops the front being abandoned;
617
+ *
618
+ * 3. WHEN THE WHOLE FILE IS FINISHED — the film behind the viewers included,
619
+ * plus what the swarm pays to fetch anything a second time. Film nobody is
620
+ * waiting for still has value: a viewer seeking back into a part that exists
621
+ * starts playing at once, and seeking back is what people do in the first
622
+ * minutes while they find their place. So spare capacity goes to finishing
623
+ * the file. This is where "the file is encoded WHOLE" lives; it used to be a
624
+ * penalty for film below the lowest encoder, which said the same thing as a
625
+ * patch and said it about one edge of the track only.
626
+ *
627
+ * WHY AN ENCODER MAY STAND BEHIND A VIEWER while film in front is still unmade:
628
+ * encoders work at the same time, so one in front and one behind can finish the
629
+ * file sooner than two in front. Where nobody is stalled and the front is closed
630
+ * just as fast, the file being done sooner is the answer count 3 deciding a
631
+ * tie in 1 and 2, which is exactly what the order is for.
632
+ *
633
+ * WHY THE COUNTS ARE COMPARED AND NOT ADDED: seconds of somebody waiting and
634
+ * seconds until a distant stretch exists are not the same thing, and no measured
635
+ * quantity says how many of one are worth one of the other. Adding them would
636
+ * mean choosing that exchange rate, which is inventing a number.
637
+ *
638
+ * @param {{ at: number, delaySec: number }[]} bodies - Where each encoder would
639
+ * stand, and how long before it produces anything there: nothing where it is
640
+ * already standing, a move or a start otherwise.
641
+ * @param {import("./CoverageMap.js").CoverageMap} coverage
642
+ * @param {WantedSpan[]} wanted
643
+ * @param {(index: number) => number} untilNeeded
644
+ * @param {number} rate - Segments per second. Always a real figure: this host
645
+ * measures what it encodes at on startup, before any viewer exists, and every
646
+ * run that works then refines it. There is no "unmeasured" case to answer.
647
+ * @param {number} refetchSecPerSegment
648
+ * @param {number} segmentSeconds
649
+ * @returns {{ stall: number, ahead: number, whole: number }} Three counts of
650
+ * seconds, compared in that order by {@link cheaperThan}.
651
+ */
652
+ function latenessOf(bodies, coverage, wanted, untilNeeded, rate, refetchSecPerSegment, segmentSeconds) {
653
+ const first = Math.min(...wanted.map((span) => span.from));
654
+ const last = Math.max(...wanted.map((span) => span.to));
655
+ // What a number nobody reaches at all counts as. The film's own length is the
656
+ // honest bound — nothing can be later than never — and a finite figure is what
657
+ // lets two hopeless arrangements still be told apart by the rest of the sum.
658
+ const never = (last + 1) * segmentSeconds;
659
+
660
+ // WHICH SIDE OF THE VIEWERS a piece is on. The map states it; nothing here
661
+ // works it out from positions, and nothing here knows where a viewer stands.
662
+ //
663
+ // It was read off the deadline before no time stated meant behind and that
664
+ // is true only of a viewer who is playing. A paused viewer has no times
665
+ // anywhere, so their whole film read as behind them, "ahead before behind"
666
+ // had nothing to compare, and the encoder was free to wander to the start of
667
+ // the file. Which side a stretch is on and how soon it is wanted are two
668
+ // different facts, and the map states both.
669
+ // WHAT RANK THE MAP GIVES THIS NUMBER — the highest, where zones overlap,
670
+ // because a number two viewers want is wanted as much as the more urgent of
671
+ // them wants it.
672
+ //
673
+ // This replaced a boolean, "is it behind everybody", and the boolean was the
674
+ // whole of what the objective knew about the map's own order. The map states
675
+ // ten ranks on a film — p100 at the number a viewer is stopped on, doubling
676
+ // zones down to p91 for the far tail, p1 for what lies behind them and all
677
+ // of that was collapsed into two buckets and then converted to seconds, where
678
+ // "never" for the film behind is the film's own length. On a 48-minute file
679
+ // that is 2024 s, which outvotes everything: field 2026-09-08, one viewer got
680
+ // three encoders, two of them on film behind them, and the run serving them
681
+ // was killed to make room for one.
682
+ const rankAt = (at) => {
683
+ let rank = 0;
684
+ for (const span of wanted) {
685
+ if (at >= span.from && at <= span.to) {
686
+ rank = Math.max(rank, Number(span.priority) || 0);
687
+ }
688
+ }
689
+ return rank;
690
+ };
691
+ // The ranks the map actually states, most urgent first. The comparison is over
692
+ // these and nothing else, so a rank can never be outvoted by a lower one
693
+ // however many seconds are at stake there.
694
+ const ranks = [...new Set(wanted.map((span) => Number(span.priority) || 0))]
695
+ .sort((left, right) => right - left);
696
+
697
+ // EVERY COUNT IS OVER THE FILM, NOT OVER THE ENCODERS. When a piece is made
698
+ // depends on which encoder reaches it soonest, and the encoder that reaches
699
+ // film in front of the viewers may well be standing behind them.
700
+ //
701
+ // Counted over the encoders instead — each charged to the side it stands on —
702
+ // the score had a hole that swallowed everything: an arrangement with every
703
+ // encoder BEHIND the viewers had nothing charged to the film in front, so its
704
+ // second term was zero, which is the best value there is. The plan then
705
+ // abandoned the film in front of a viewer and put both encoders at the start
706
+ // of the file, which is the opposite of the rule it is supposed to obey.
707
+ //
708
+ // AND THE WAITING IS WALKED FORWARD, not summed piece by piece.
709
+ //
710
+ // Not a sum of each piece's own lateness. A viewer who is stopped is not
711
+ // watching, so everything after the piece they are stopped on is needed that
712
+ // much later too: one wait moves every deadline behind it by its own length.
713
+ //
714
+ // Summed independently instead, the far tail of a long file outvoted the film
715
+ // under the viewer's feet — measured, and it placed the only encoder at #114
716
+ // while the viewer stood at #100, because thirteen pieces of certain waiting
717
+ // "cost" less than 886 distant pieces arriving a little later. Walking the
718
+ // clock forward makes that trade impossible: abandoning the near film delays
719
+ // the far film by at least as much.
720
+ let stalled = 0;
721
+ let wastedSwarm = 0;
722
+ /** Seconds anybody waits past a deadline, per rank. @type {Map<number, number>} */
723
+ const lateAt = new Map(ranks.map((rank) => [rank, 0]));
724
+ /** When the last number of a rank is made, per rank. @type {Map<number, number>} */
725
+ const doneAt = new Map(ranks.map((rank) => [rank, 0]));
726
+ for (let index = first; index <= last; index += 1) {
727
+ // Which encoder gets to this piece first, and when. One standing on it is
728
+ // already there; one behind it must work its way up, re-making anything
729
+ // already made on the way, which costs its own time and the swarm's.
730
+ let soonest = Number.POSITIVE_INFINITY;
731
+ let byWhom = null;
732
+ for (const body of bodies) {
733
+ if (body.at > index) {
734
+ continue;
735
+ }
736
+ // WHEN THIS BODY REACHES THIS NUMBER. `delaySec` is when it finishes the
737
+ // piece it is STANDING ON, so the pieces after it are the only ones still
738
+ // to be encoded at `rate`.
739
+ //
740
+ // It used to be `(index - at + 1) / rate` on top of the delay, which
741
+ // charges every body a whole piece for the one it is already working on. A
742
+ // fresh body does start from nothing, so for it that is right and it is
743
+ // now inside its own delay. A run 0.8 s into a 0.9 s piece does not, and
744
+ // charging it 0.94 s for that piece is what made moving it look cheaper
745
+ // than leaving it: from #58 it was priced at 1.89 s to reach #59 against
746
+ // 1.88 s for a kill and a cold start, a difference of ten milliseconds
747
+ // that is nothing but the double charge. Field 2026-09-08: 39 moves in one
748
+ // session, 24 of them between three adjacent numbers, and the picture
749
+ // stood still for 116.7 s.
750
+ const arrival = body.delaySec
751
+ + (index - body.at) / rate
752
+ + coverage.madeBetween(body.at, index) * refetchSecPerSegment;
753
+ if (arrival < soonest) {
754
+ soonest = arrival;
755
+ byWhom = body;
756
+ }
757
+ }
758
+ if (coverage.isReady(index)) {
759
+ // It exists. Nobody waits for it and nothing is owed — but whoever passes
760
+ // over it makes it a second time, and the swarm fetches its bytes again.
761
+ if (byWhom !== null) {
762
+ wastedSwarm += refetchSecPerSegment;
763
+ }
764
+ continue;
765
+ }
766
+ // A piece nobody is working towards arrives never. There is no third case:
767
+ // the host measures what it encodes at, and what it copies at, before any
768
+ // viewer exists, so a speed is always a real number and an arrival can
769
+ // always be computed.
770
+ // Nothing arrives later than never, which is the bound the film's own length
771
+ // gives. It is a definition rather than a guard: it also makes the score
772
+ // total on a host whose startup measured nothing at all, where every arrival
773
+ // is beyond reckoning and every arrangement is therefore equally hopeless.
774
+ const when = byWhom === null ? never : Math.min(soonest, never);
775
+ const rank = rankAt(index);
776
+ doneAt.set(rank, Math.max(doneAt.get(rank) ?? 0, when));
777
+ const deadline = untilNeeded(index);
778
+ if (Number.isFinite(deadline)) {
779
+ const due = deadline + stalled;
780
+ const waited = Math.max(0, when - due);
781
+ lateAt.set(rank, (lateAt.get(rank) ?? 0) + waited);
782
+ stalled += waited;
783
+ }
784
+ }
785
+
786
+ return {
787
+ // THE MAP'S OWN ORDER, AS A VECTOR. One pair per rank the map states, most
788
+ // urgent rank first: how long anybody waits at that rank, then when the last
789
+ // number of it is made.
790
+ //
791
+ // Compared position by position, so a rank is never outvoted by a lower one
792
+ // — which is the whole of what was asked for: nobody stares at a spinner;
793
+ // then the film in front of the viewers is encoded as fast as it can be, band
794
+ // by band as the map ranks them; then, with whatever is left over and only
795
+ // then, the film behind them, in case somebody seeks back.
796
+ //
797
+ // No weights, and none possible: a weight would let seconds at one rank buy
798
+ // seconds at another, and it would be a number nobody measured. The map is
799
+ // the source of truth about what matters, and it already says so.
800
+ byRank: ranks.flatMap((rank) => [lateAt.get(rank) ?? 0, doneAt.get(rank) ?? 0]),
801
+ // HOW MANY ENCODERS IT TAKES. Ranked below every rank of the map and above
802
+ // the swarm's bill, so it cannot buy one where the map is indifferent and
803
+ // the map IS indifferent about spare capacity, which is what bought an
804
+ // encoder for film nobody waits for.
805
+ bodies: bodies.length,
806
+ // WHAT THE SWARM PAYS for anything fetched twice, which delays everything.
807
+ wasted: wastedSwarm
808
+ };
809
+ }
810
+
811
+ /**
812
+ * Is the first arrangement cheaper than the second?
813
+ *
814
+ * Three things in order, stated by the user 2026-09-06: nobody stares at a
815
+ * spinner; then the film in front of the viewers is finished soonest; then the
816
+ * whole file is. A later one decides only where the earlier ones tie.
817
+ *
818
+ * That order is why an encoder may stand BEHIND a viewer while film in front is
819
+ * still unmade: encoders work at the same time, so one in front and one behind
820
+ * can finish the file sooner than two in front — and where nobody is stalled and
821
+ * the front is closed just as fast, the file being done sooner is the answer.
822
+ *
823
+ * @param {{ stall: number, ahead: number, whole: number }} left
824
+ * @param {{ stall: number, ahead: number, whole: number }} right
825
+ * @returns {boolean}
826
+ */
827
+ function cheaperThan(left, right) {
828
+ // POSITION BY POSITION, in the map's own order of ranks. A difference at a
829
+ // higher rank settles it, and nothing at a lower one can reopen it.
830
+ //
831
+ // There is no margin here and there must not be one. A threshold — "a move
832
+ // must beat staying by at least what moving costs" — was written while the
833
+ // arrival arithmetic charged a run for a piece it had already half made, and
834
+ // it was a prop under a comparison that was wrong rather than indifferent.
835
+ // With the arithmetic right the two are 1.08 s against 1.88 s, and nothing
836
+ // needs propping.
837
+ const size = Math.max(left.byRank.length, right.byRank.length);
838
+ for (let index = 0; index < size; index += 1) {
839
+ const here = left.byRank[index] ?? 0;
840
+ const there = right.byRank[index] ?? 0;
841
+ if (here !== there) {
842
+ return here < there;
843
+ }
844
+ }
845
+ // Where every rank is served identically, fewer encoders. The map is
846
+ // indifferent, so the machine decides: a process, a reader of the piece store
847
+ // and the swarm's bandwidth are all paid by the viewers the ranks above are
848
+ // about.
849
+ if (left.bodies !== right.bodies) {
850
+ return left.bodies < right.bodies;
851
+ }
852
+ return left.wasted < right.wasted;
853
+ }
854
+
855
+ /**
856
+ * How long until a number is needed, read off the map.
857
+ *
858
+ * The map states it per stretch, for the stretch's NEAR EDGE, because a stretch
859
+ * is met at its beginning. Every number inside is needed no sooner than that, so
860
+ * taking the stretch's figure for all of them is the safe reading: it can only
861
+ * make the filling earlier than it has to be, never later.
862
+ *
863
+ * Where the map says nothing, nobody is coming and nothing can be late.
864
+ *
865
+ * Inside a stretch the time GROWS with the distance, because a viewer covers a
866
+ * second of film in a second: the number `n` places past the near edge is
867
+ * reached `n` segments of film later. Taking the near edge's figure for every
868
+ * number inside instead makes a whole stretch due at once measured while
869
+ * building this: the first stretch is as wide as the measured allowance, so its
870
+ * far end was demanded instantly and an encoder was placed on a number another
871
+ * one was already writing.
872
+ *
873
+ * @param {WantedSpan[]} windows
874
+ * @param {number} segmentSeconds - How much film one number holds.
875
+ * @returns {(index: number) => number}
876
+ */
877
+ /** @param {WantedSpan[]} windows */
878
+ function firstOf(windows) {
879
+ return Math.min(...windows.map((span) => span.from));
880
+ }
881
+
882
+ /** @param {WantedSpan[]} windows */
883
+ function lastOf(windows) {
884
+ return Math.max(...windows.map((span) => span.to));
885
+ }
886
+
887
+ function deadlineReaderFor(windows, segmentSeconds) {
888
+ const perSegment = segmentSeconds > 0 ? segmentSeconds : 0;
889
+ return (index) => {
890
+ let soonest = Number.POSITIVE_INFINITY;
891
+ for (const span of windows) {
892
+ if (index < span.from || index > span.to) {
893
+ continue;
894
+ }
895
+ const stated = /** @type {{ withinSeconds?: number }} */ (span).withinSeconds;
896
+ // A stretch stated with no time is somebody waiting at its near edge: that
897
+ // is what stating one means. The rest of it grows with the distance, the
898
+ // same as a stated one — read as due all at once instead, a window as wide
899
+ // as a viewer's cushion demanded its far end instantly and bought an
900
+ // encoder to stand beside one already working.
901
+ // `null` IS A STATEMENT AND IT SAYS NOBODY IS COMING. `undefined` is the
902
+ // absence of one, and a caller that knows only a position is somebody
903
+ // waiting at it.
904
+ //
905
+ // Read through `Number()`, `null` becomes 0 — due NOW — so the film BEHIND
906
+ // the viewers, which the map marks with exactly that, was the most urgent
907
+ // material in the file. Everything followed from it: it bought encoders,
908
+ // it took the run standing in front of the viewer because that run was the
909
+ // nearest body to it, and it did so again on every pass. Field 2026-09-08:
910
+ // 39 moves in one session, 24 between three adjacent numbers, one viewer
911
+ // on three encoders, and the picture stood still for 116.7 s in three
912
+ // interruptions, the worst of them 91.8 s.
913
+ //
914
+ // The map has always said it plainly `{"from":0,"to":57,"priority":1,
915
+ // "withinSeconds":null,"behind":true}` is in the log of every session — and
916
+ // this line turned it into its opposite. Fourth time in this repository
917
+ // that the input to a calculation was not what the calculation assumed.
918
+ const within = stated === undefined ? 0 : (stated === null ? Number.NaN : Number(stated));
919
+ if (!Number.isFinite(within)) {
920
+ // Stated as no time at all: nobody is coming here.
921
+ continue;
922
+ }
923
+ const here = within + (index - span.from) * perSegment;
924
+ if (here < soonest) {
925
+ soonest = here;
926
+ }
927
+ }
928
+ return soonest;
929
+ };
930
+ }
931
+
932
+ /**
933
+ * WHERE ENCODERS BELONG, from the model rather than from a list of cases.
934
+ *
935
+ * The problem this solves, stated exactly:
936
+ *
937
+ * - the track is a line of segment numbers; `M` are the ones not made;
938
+ * - each `x` carries a DEADLINE `D(x)`, the seconds until somebody needs it.
939
+ * That is what the priority map is a reading of — a viewer moving forward
940
+ * covers a second of film in a second, so the time until they are at `x` is
941
+ * the distance to it. `Infinity` where nobody is coming;
942
+ * - an encoder is a SEQUENTIAL producer: placed at `a`, it delivers `a + j` at
943
+ * time `(j + 1) / r`, where `r` is segments per second, measured. It cannot
944
+ * skip, so its whole schedule follows from where it starts;
945
+ * - the machine affords `k` of them, measured.
946
+ *
947
+ * Two consequences fall out and need no rule of their own. Placements
948
+ * `a_1 < ... < a_k` PARTITION the line: encoder `i` is useful only on
949
+ * `[a_i, a_{i+1})`, because past that its neighbour got there first. And a
950
+ * segment served by encoder `i` arrives at `(x - a_i + 1) / r`, which is
951
+ * therefore also the answer to "when would the encoder already placed before it
952
+ * get here" — the second half of the comparison, and the half that was missing.
953
+ *
954
+ * `x` is LATE when it arrives after `D(x)`. The objective is no late segments;
955
+ * where `k` does not stretch to that, lateness beginning as far to the right as
956
+ * possible.
957
+ *
958
+ * THE ALGORITHM is first-fit, left to right:
959
+ *
960
+ * for each missing x with a finite deadline, ascending:
961
+ * if some encoder already placed at a satisfies (x - a + 1)/r <= D(x):
962
+ * it covers x
963
+ * else:
964
+ * place an encoder at x
965
+ *
966
+ * A LIVE run enters as an encoder already placed at its own head. There is no
967
+ * special case for it.
968
+ *
969
+ * WHY IT IS OPTIMAL. The leftmost missing number with a finite deadline must be
970
+ * covered by somebody. An encoder placed exactly on it delivers it at the
971
+ * earliest time any placement can, `1/r`, and covers the longest suffix any
972
+ * placement can — starting further left only re-makes material and arrives
973
+ * later, starting further right does not cover it at all. So the greedy choice
974
+ * is never worse than any other, and the usual exchange argument carries it to
975
+ * the whole line. This is the known result for FIXED-ORDER scheduling with
976
+ * deadlines, where first-fit is optimal at unit processing times, and a segment
977
+ * is one unit. General machine minimisation with release times and deadlines is
978
+ * NP-hard; this case is polynomial because the order is forced and each machine
979
+ * covers a contiguous stretch.
980
+ *
981
+ * WHAT WAS TRIED FIRST AND WAS WRONG, kept because each looked reasonable:
982
+ *
983
+ * - `(h - p) * s / (1 - s)`, how long a run stays in front of a viewer moving
984
+ * forward. It answers a different question: a viewer stopped with an empty
985
+ * buffer needs the segment now, and at exactly realtime that formula says
986
+ * "for ever" while the viewer waits thirteen minutes;
987
+ * - whether a run's head lies inside a wanted band — which ties an encoder to
988
+ * whoever is standing there, and this layer must never know that;
989
+ * - the run's head as a barrier, everything above it placeable. It has no time
990
+ * in it at all, so it cannot tell two segments ahead from two hundred.
991
+ *
992
+ * Each was a case, not a model. The deadline is the model.
993
+ *
994
+ * @param {import("./CoverageMap.js").CoverageMap} coverage
995
+ * @param {Set<object>} surviving - Runs that will still be alive, as encoders
996
+ * already placed at their own heads.
997
+ * @param {number} rate - Segments produced per second by one encoder, measured.
998
+ * Zero when nothing has measured it, and then no arrival time can be computed
999
+ * and every claimed number is left alone.
1000
+ * @returns {(at: number, bound: number, deadlineAt: (index: number) => number, alsoPlaced?: number[]) => number | null}
1001
+ */
1002
+ function gapFinderFor(coverage, surviving, rate, refetchSecPerSegment = 0) {
1003
+ /** Encoders already placed: where each stands, and how far its road runs. */
1004
+ const placed = [];
1005
+ for (const run of surviving) {
1006
+ const head = Number(/** @type {{ head?: number }} */ (run).head);
1007
+ placed.push({
1008
+ at: Number.isFinite(head) ? head : Number(/** @type {{ from: number }} */ (run).from),
1009
+ // A live run's road, so that placing inside it can be priced. A run given
1010
+ // no end drives to the end of the film, which is what makes the price real.
1011
+ // A run given no end drives to the end of the film, which is what makes
1012
+ // the price of cutting in front of it real. Written out rather than
1013
+ // imported: this file depends on nothing, and that is what lets it be
1014
+ // exercised with plain values alone.
1015
+ to: Number(/** @type {{ to: number }} */ (run).to) < Number(/** @type {{ from: number }} */ (run).from)
1016
+ ? Number.POSITIVE_INFINITY
1017
+ : Number(/** @type {{ to: number }} */ (run).to)
1018
+ });
1019
+ }
1020
+ return (at, bound, deadlineAt, alsoPlaced) => {
1021
+ const start = Number.isInteger(at) && at > 0 ? at : 0;
1022
+ const last = Number.isInteger(bound) ? bound : -1;
1023
+ // THE LATE NUMBER THAT IS DUE SOONEST, not the leftmost one.
1024
+ //
1025
+ // With room for every placement the two are the same answer. With a budget
1026
+ // that binds they are not, and the objective decides: lateness pushed as far
1027
+ // to the right as possible means the soonest deadline is served first. A
1028
+ // walk by number gave the one machine to a viewer due in ten minutes while
1029
+ // another stood waiting with an empty buffer.
1030
+ //
1031
+ // Ties go to the smaller number, so the answer does not depend on the order
1032
+ // the map happens to be in.
1033
+ let best = null;
1034
+ let bestDue = Number.POSITIVE_INFINITY;
1035
+ for (let index = start; index <= last; index += 1) {
1036
+ if (coverage.isReady(index)) {
1037
+ continue;
1038
+ }
1039
+ const deadline = deadlineAt(index);
1040
+ if (!Number.isFinite(deadline)) {
1041
+ // NOBODY IS COMING HERE, so nothing can be late — but the film is still
1042
+ // wanted, and this is where spare capacity goes. The number is proposed;
1043
+ // whether an encoder is actually spent on it is the score's answer, and
1044
+ // the score puts anything anybody is waiting for first.
1045
+ return index;
1046
+ }
1047
+ // When would the SOONEST of those already placed get here? Encoders placed
1048
+ // EARLIER IN THIS PASS count: the first one placed for a viewer covers the
1049
+ // stretch in front of them, and without counting it the walk placed a
1050
+ // second and a third on the very next numbers — three processes a segment
1051
+ // apart for one person, which is the waste this model exists to refuse.
1052
+ let soonest = Number.POSITIVE_INFINITY;
1053
+ for (const a of [...placed.map((live) => live.at), ...(alsoPlaced ?? [])]) {
1054
+ if (a > index) {
1055
+ // Standing past it. Encoders only move forward, so it never will.
1056
+ continue;
1057
+ }
1058
+ if (a === index) {
1059
+ // Standing ON it. No placement is faster than the one already made.
1060
+ soonest = 0;
1061
+ break;
1062
+ }
1063
+ // WHEN THIS BODY GETS HERE, and both terms of it.
1064
+ //
1065
+ // Its own encoding of everything between, and the swarm's price for the
1066
+ // film it would fetch a SECOND time — every number between that is
1067
+ // already made, it makes again. That second term is why "should this
1068
+ // encoder drive on or be moved" is not a question of its own: an
1069
+ // encoder with three hundred made pieces in front of it is simply slow
1070
+ // to arrive, and the model compares arrivals. Asked separately it was a
1071
+ // second authority over the same encoder, and the two disagreed.
1072
+ const arrival = (index - a + 1) / rate
1073
+ + coverage.madeBetween(a, index) * refetchSecPerSegment;
1074
+ if (arrival < soonest) {
1075
+ soonest = arrival;
1076
+ }
1077
+ }
1078
+ if (soonest <= deadline) {
1079
+ // Somebody gets here in time. Nothing to decide.
1080
+ continue;
1081
+ }
1082
+ // IT IS LATE, AND THAT IS ALL THIS DECIDES. Whether filling it is worth
1083
+ // the price is not asked here: this only proposes candidates, and the
1084
+ // score decides how many of them are taken and by whom. Asked here as
1085
+ // well, it was a second cost model beside the objective — with its own
1086
+ // idea of what a process costs — and the two disagreed at exactly
1087
+ // realtime, where every next piece is marginally late and each looked
1088
+ // worth its own encoder.
1089
+ if (deadline < bestDue) {
1090
+ best = index;
1091
+ bestDue = deadline;
1092
+ }
1093
+ }
1094
+ return best;
1095
+ };
1096
+ }
1097
+
1098
+ /**
1099
+ * The last number of a stretch that begins at `from` and is `length` long.
1100
+ *
1101
+ * `-1` when the length is not finite, which is this layer's word for a run with
1102
+ * no end: the film's length is not known, so there is nothing to stop it at, and
1103
+ * a number invented here would be an end nobody measured.
1104
+ *
1105
+ * @param {number} from
1106
+ * @param {number} length
1107
+ * @returns {number}
1108
+ */
1109
+ function endOfStretch(from, length) {
1110
+ return Number.isFinite(length) ? from + Math.max(1, length) - 1 : -1;
1111
+ }
1112
+
1113
+ /**
1114
+ * The lowest number a viewer is waiting for that is not ready — what the plan
1115
+ * is judged by.
1116
+ *
1117
+ * Not used to decide anything: it is the figure a log line carries, so that a
1118
+ * plan that keeps producing while a viewer waits is visible rather than
1119
+ * inferred.
1120
+ *
1121
+ * @param {import("./CoverageMap.js").CoverageMap} coverage
1122
+ * @param {WantedSpan[]} windows
1123
+ * @returns {number | null}
1124
+ */
1125
+ export function firstUnmetWant(coverage, windows) {
1126
+ let lowest = null;
1127
+ for (const span of windows ?? []) {
1128
+ for (let at = span.from; at <= span.to; at += 1) {
1129
+ if (!coverage.isReady(at)) {
1130
+ if (lowest === null || at < lowest) {
1131
+ lowest = at;
1132
+ }
1133
+ break;
1134
+ }
1135
+ }
1136
+ }
1137
+ return lowest;
1138
+ }
1139
+
1140
+ /**
1141
+ * Where to put the encoders this machine can afford.
1142
+ *
1143
+ * Two things are wanted of a division of the film, and they are wanted in this
1144
+ * order:
1145
+ *
1146
+ * 1. **the viewer must not stop.** An encoder starting at `q` stays ahead of a
1147
+ * viewer at `p` while `y / s <= q + y - p`, so it holds `(q - p) * s / (1-s)`
1148
+ * of film and no more. Beyond that the viewer catches it, and the next
1149
+ * encoder has to be standing there. That is where the first ones go, and it
1150
+ * is why the stretches grow: the further off one starts, the later the
1151
+ * viewer arrives and the longer it may work;
1152
+ * 2. **the film should be finished as soon as possible.** Once the viewer is
1153
+ * safe, whatever is left is divided EQUALLY between the encoders that
1154
+ * remain: equal shares finish together, and any other division finishes when
1155
+ * its longest share does. That is what makes seeking cheap — the film exists.
1156
+ *
1157
+ * At or above realtime the first requirement is met by one encoder for the
1158
+ * whole film, and every other encoder goes to the second — which is the common
1159
+ * case on a copied picture, and is why "one viewer, one encoder" was never the
1160
+ * rule.
1161
+ *
1162
+ * @param {object} params
1163
+ * @param {import("./CoverageMap.js").CoverageMap} params.coverage
1164
+ * @param {WantedSpan[]} params.windows - The merged map, in this output's own
1165
+ * numbering. Its highest-numbered band starts where the viewer is.
1166
+ * @param {number} params.howMany - What the machine affords.
1167
+ * @param {number} params.speedX - Measured. Zero when nothing has measured it,
1168
+ * and then only the first requirement can be served.
1169
+ * @param {(at: number, bound: number, deadlineAt: (index: number) => number, placed: number[]) => number | null} [params.firstGap] -
1170
+ * Where a gap may be opened. Defaults to the map's own answer; the plan hands
1171
+ * in one that also counts a number a live run has claimed but will not reach
1172
+ * before it is needed, which is the only way anybody beyond a working encoder
1173
+ * is served.
1174
+ * @param {(index: number) => number} [params.deadlineAt] - Seconds until that
1175
+ * number is needed. `Infinity` where nobody is coming. Absent means every
1176
+ * stated want is due now.
1177
+ * @returns {number[]} Where to start each encoder, ascending.
1178
+ */
1179
+ export function placeEncoders({ coverage, windows, howMany, firstGap = null, deadlineAt = null }) {
1180
+ if (!(howMany > 0) || windows.length === 0) {
1181
+ return [];
1182
+ }
1183
+ // NOW when the caller says nothing. A stated want with no time is somebody
1184
+ // waiting on it — that is what stating one means — so the honest reading is
1185
+ // that it is due. `Infinity` is a statement in its own right and has to be
1186
+ // made: it says nobody is coming.
1187
+ const untilNeeded = deadlineAt ?? (() => 0);
1188
+ /** Where this pass has placed so far — each one covers what it can reach. */
1189
+ const placedHere = [];
1190
+ const gapAt = firstGap
1191
+ ? (at, bound) => firstGap(at, bound, untilNeeded, placedHere)
1192
+ : (at, bound) => coverage.firstGapFrom(at, bound);
1193
+
1194
+
1195
+ // CANDIDATES COME FROM THE PRIORITY MAP, IN THE ORDER THE MAP STATES.
1196
+ //
1197
+ // The map already answers every question that was being re-derived here. Its
1198
+ // ranks say what matters most — the number a viewer is stopped on, then what
1199
+ // is in front of them band by band, then the rest of the track, and last of
1200
+ // all what lies behind them. A pause flattens those ranks; a seek moves them;
1201
+ // a second viewer merges into them. So walking the map in its own order is
1202
+ // what "ahead before behind" means, and nothing here has to work out where the
1203
+ // viewers are.
1204
+ //
1205
+ // It was not read that way. This walked the film by number and proposed
1206
+ // whatever was late, then a second pass divided the leftovers — an order of
1207
+ // its own invention, which put the beginning of the file before the film in
1208
+ // front of a viewer and, at one point, proposed #0, #1 and #2 as three
1209
+ // separate places.
1210
+ //
1211
+ // One candidate per zone: the first number in it nobody has and nobody
1212
+ // reaches in time. Zones with no deadline can have nothing late in them, so
1213
+ // there it is simply the first number nobody has — which is how spare capacity
1214
+ // comes to finish the file.
1215
+ /** @type {number[]} */
1216
+ const places = [];
1217
+ const byRank = [...windows].sort(
1218
+ (left, right) => (right.priority ?? 0) - (left.priority ?? 0) || left.from - right.from
1219
+ );
1220
+ for (const zone of byRank) {
1221
+ if (places.length >= howMany) {
1222
+ break;
1223
+ }
1224
+ const at = gapAt(zone.from, zone.to);
1225
+ if (at === null || places.includes(at)) {
1226
+ continue;
1227
+ }
1228
+ places.push(at);
1229
+ placedHere.push(at);
1230
+ }
1231
+
1232
+ // AND WHERE TO SPLIT WHAT IS LEFT, for the capacity the map has not spent.
1233
+ //
1234
+ // The search above proposes only what is LATE, so once one encoder covers a
1235
+ // zone in time that zone proposes nothing more — and a machine that holds four
1236
+ // ran one. Finishing a contiguous stretch soonest with several machines of the
1237
+ // same speed means dividing it between them, which is where these come from:
1238
+ // the widest run of film between two encoders, split.
1239
+ //
1240
+ // Proposing is not spending. The score decides whether another process is
1241
+ // worth it, and its first term — how late the film is — always outranks its
1242
+ // second, so this can never take capacity from somebody waiting.
1243
+ while (places.length < howMany) {
1244
+ const edges = [...places].sort((left, right) => left - right);
1245
+ let widestFrom = null;
1246
+ let widest = 0;
1247
+ for (let index = 0; index <= edges.length; index += 1) {
1248
+ const from = index === 0 ? firstOf(windows) : edges[index - 1] + 1;
1249
+ const to = index === edges.length ? lastOf(windows) : edges[index] - 1;
1250
+ const room_ = coverage.unmadeRunFrom(from);
1251
+ if (to >= from && room_ > widest) {
1252
+ widest = room_;
1253
+ widestFrom = from + Math.floor(Math.min(room_, to - from + 1) / 2);
1254
+ }
1255
+ }
1256
+ if (widestFrom === null) {
1257
+ break;
1258
+ }
1259
+ const at = coverage.firstGapFrom(widestFrom, lastOf(windows));
1260
+ if (at === null || places.includes(at)) {
1261
+ break;
1262
+ }
1263
+ places.push(at);
1264
+ placedHere.push(at);
1265
+ }
1266
+
1267
+ // These are CANDIDATES, not decisions. What is late proposes first, because
1268
+ // that is what a viewer feels; what is merely unmade proposes after it. The
1269
+ // score decides which of them are worth a process, and a paused viewer, who
1270
+ // states no deadline at all, therefore still leaves the file being finished
1271
+ // rather than the machine falling idle.
1272
+ return places.sort((left, right) => left - right);
1273
+ }
1274
+