@torrent-tv/proxy 2.80.15 → 2.80.17

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