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