@torrent-tv/proxy 2.80.4 → 2.80.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/package.json +1 -1
  3. package/routes/api/delivery-sink/get.js +8 -4
  4. package/server.js +415 -403
  5. package/services/data-channel-handler.js +87 -25
  6. package/services/delivery-probe.js +38 -5
  7. package/services/encode/CoverageMap.js +77 -4
  8. package/services/encode/EncodePlan.js +1025 -358
  9. package/services/encode/EncodeRun.js +42 -22
  10. package/services/encode/SegmentDemand.js +0 -0
  11. package/services/encode/SegmentStore.js +55 -3
  12. package/services/encode/open-piece.js +47 -24
  13. package/services/encode/run-command.js +12 -2
  14. package/services/hls-session-manager.js +38 -158
  15. package/services/hwaccel.js +182 -54
  16. package/services/orchestrators/EncodeOrchestrator.js +123 -94
  17. package/services/output/LiveOutputs.js +233 -213
  18. package/services/output/Timeline.js +333 -256
  19. package/services/priority/PriorityMap.js +262 -108
  20. package/services/priority/PriorityOrchestrator.js +31 -6
  21. package/services/quality/EncodeCost.js +555 -500
  22. package/services/torrent-pool.js +9 -4
  23. package/test/encode-orchestrator.test.js +195 -65
  24. package/test/encode-plan-viewers.test.js +719 -0
  25. package/test/encode-plan.test.js +174 -81
  26. package/test/open-piece.test.js +152 -0
  27. package/test/output-speed.test.js +86 -0
  28. package/test/priority-map-download.test.js +25 -7
  29. package/test/priority-map.test.js +134 -83
  30. package/test/seek-landing.test.js +109 -76
  31. package/test/segment-demand.test.js +54 -56
  32. package/test/wedge-certainty.test.js +3 -3
  33. package/test/flushed-piece.test.js +0 -108
@@ -17,7 +17,7 @@ import { logger } from "../utils/logger.js";
17
17
  import { SharedPieceStore, findSharedStore } from "./piece-store/shared-piece-store.js";
18
18
  import { Urgency } from "./demand/index.js";
19
19
  import { demandFor, forgetTorrent, reconcileAll } from "./download/registry.js";
20
- import { AT_THE_VIEWER, NOBODY_IS_COMING } from "./priority/PriorityMap.js";
20
+ import { isAtAWatchingViewer, isBehindEverybody, isNobodyComingNow } from "./priority/PriorityMap.js";
21
21
  import { deriveSourceKey } from "./torrent-source-key.js";
22
22
 
23
23
  /** How a window stated from the priority map names itself. */
@@ -1056,14 +1056,19 @@ export class TorrentPool {
1056
1056
  * @returns {number}
1057
1057
  */
1058
1058
  const levelOf = (zone) => {
1059
+ // Read through the map's own words rather than by comparing its numbers.
1060
+ // The scale is that layer's, and the numbers inside a band mean nothing
1061
+ // but their order.
1059
1062
  const priority = zone.priority ?? 0;
1060
- if (priority <= NOBODY_IS_COMING) {
1063
+ if (isBehindEverybody(priority)) {
1061
1064
  return Urgency.BEHIND;
1062
1065
  }
1063
- if (priority <= NOBODY_IS_COMING + 1) {
1066
+ if (isNobodyComingNow(priority)) {
1067
+ // In front of somebody who has stopped the picture, and of nobody who is
1068
+ // watching. Wanted, and wanted after everyone who is on their way.
1064
1069
  return Urgency.TAIL;
1065
1070
  }
1066
- return priority >= AT_THE_VIEWER ? Urgency.NEAR : Urgency.AHEAD;
1071
+ return isAtAWatchingViewer(priority) ? Urgency.NEAR : Urgency.AHEAD;
1067
1072
  };
1068
1073
  ordered.forEach((zone, index) => {
1069
1074
  // A second of film sits at that fraction of the file. Constant bitrate is
@@ -15,6 +15,22 @@ import { EncodeRun } from "../services/encode/EncodeRun.js";
15
15
  import { ENCODE_EXIT } from "../services/encode/encode-exit.js";
16
16
  import { SoftwareEncoder } from "../services/encode/SoftwareEncoder.js";
17
17
  import { EncodeOrchestrator } from "../services/orchestrators/EncodeOrchestrator.js";
18
+ import { contentionPenalty, penaltiesFrom } from "../services/contention.js";
19
+
20
+ // WHAT A SECOND ENCODER COSTS THE FIRST — measured, never a formula.
21
+ //
22
+ // Addon host, 2026-09-03: 854x480 through libx264 `ultrafast` ran at 7.12x with
23
+ // the machine to itself, and at 4.20x and 4.16x when two ran at once. The
24
+ // penalty is read off that reading by the SAME two functions production uses,
25
+ // so nothing here invents a shape: beyond what was measured the reading is held
26
+ // rather than extrapolated.
27
+ const MEASURED_PENALTIES = penaltiesFrom(7.12, [{ others: 1, speed: 4.18 }]);
28
+ const penaltyFor = (others) => contentionPenalty(others, MEASURED_PENALTIES).penalty;
29
+
30
+ // What a start and a stop cost, measured on the same host: a spawn with its
31
+ // input open is 0.12 s there.
32
+ const RUN_COSTS = { killCostSec: 0, firstByteWaitSec: 0.12 };
33
+
18
34
 
19
35
  const PICTURE = "torrent:abc:fmt=fmp4:grid=kf@0:video-only:v=0/copy";
20
36
 
@@ -36,6 +52,42 @@ class FakeProcess extends EventEmitter {
36
52
  /**
37
53
  * @param {{ maxRuns?: number }} [options]
38
54
  */
55
+ /**
56
+ * What is wanted of the picture, as ONE map.
57
+ *
58
+ * The encoding receives a map per output, already merged and with nobody's name
59
+ * on it; these tests state the same thing, so what a viewer's zone becomes is
60
+ * the priority layer's business and not asserted here.
61
+ *
62
+ * @param {EncodeOrchestrator} made
63
+ * @param {{ from: number, to: number, priority?: number, withinSeconds?: number }[]} zones
64
+ */
65
+ function wants(made, zones) {
66
+ made.notePriorityMap(PICTURE, zones.map((zone) => ({
67
+ from: zone.from,
68
+ to: zone.to,
69
+ priority: zone.priority ?? 1,
70
+ withinSeconds: zone.withinSeconds ?? 0
71
+ })));
72
+ }
73
+
74
+ /**
75
+ * How many encoders are working the stretch a given number falls in.
76
+ *
77
+ * The count that matters for a viewer is not how many exist — what the machine
78
+ * has spare goes to finishing the file, which is what makes a seek back into a
79
+ * made part start at once — but how many are crowded onto one place.
80
+ *
81
+ * @param {EncodeOrchestrator} made
82
+ * @param {number} segment
83
+ */
84
+ function onTheStretchOf(made, segment) {
85
+ return made.runsOn(PICTURE).filter((run) => {
86
+ const to = run.to < run.from ? Number.POSITIVE_INFINITY : run.to;
87
+ return run.from <= segment && segment <= to;
88
+ }).length;
89
+ }
90
+
39
91
  function orchestrator({ maxRuns = 2 } = {}) {
40
92
  const lines = [];
41
93
  const processes = new Map();
@@ -44,13 +96,22 @@ function orchestrator({ maxRuns = 2 } = {}) {
44
96
  made = new EncodeOrchestrator({
45
97
  maxRunsFor: () => maxRuns,
46
98
  segmentSeconds: 4,
47
- restartCostSec: 0.12,
99
+ ...RUN_COSTS,
48
100
  // A host that has measured what the swarm charges to fetch a second of film
49
101
  // again. Without it the drive-or-move comparison has only one side and the
50
102
  // plan keeps the encoder rather than paying an unknown price — which is its
51
103
  // own check in `encode-plan.test.js` rather than the shape every check here
52
104
  // is written against.
53
105
  refetchSecPerFilmSecond: () => 0.25,
106
+ // What this host was measured to encode at before any run reported —
107
+ // the startup benchmark, which exists before a viewer does.
108
+ startingSpeedFor: () => 2,
109
+ // What a second encoder costs the first, measured on the addon host
110
+ // 2026-09-03: 1.70x beside one other at 480p, 1.98x at 1080p. Sharing one
111
+ // machine is close to proportional, so this is the measured shape. Without
112
+ // it every extra process is free and the score always wants more of them —
113
+ // and fewer encoders can genuinely finish sooner.
114
+ contentionPenalties: MEASURED_PENALTIES,
54
115
  now: () => 1000,
55
116
  logger: { info: (line) => lines.push(line), warn: (line) => lines.push(line) },
56
117
  makeRun: ({ address, from, to }) => {
@@ -73,48 +134,149 @@ function orchestrator({ maxRuns = 2 } = {}) {
73
134
  }
74
135
  });
75
136
  made.setSegmentCount(PICTURE, 1000);
76
- return { made, lines, processes };
137
+ // A run built the way the session builds the FIRST one of an output: outside
138
+ // the plan, and with no end, because the free stretch reaches the last
139
+ // segment of the film and `-1` is how that is written everywhere here.
140
+ const buildRun = ({ address = PICTURE, from = 0, to = -1 } = {}) => {
141
+ const process_ = new FakeProcess();
142
+ const run = new EncodeRun({
143
+ address,
144
+ encoder: new SoftwareEncoder(),
145
+ from,
146
+ to,
147
+ buildArgs: () => ["-i", "in", "out"],
148
+ spawn: () => process_,
149
+ logger: { info: (line) => lines.push(line), warn: (line) => lines.push(line) },
150
+ now: () => 1000,
151
+ onEnded: (ended) => made.noteEnded(ended)
152
+ });
153
+ processes.set(run, process_);
154
+ return run;
155
+ };
156
+ return { made, lines, processes, buildRun };
77
157
  }
78
158
 
79
159
  test("a viewer waiting gets an encoder at what they are waiting for", () => {
80
160
  const { made } = orchestrator();
81
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 130 });
161
+ wants(made, [{ from: 100, to: 130 }]);
82
162
  made.reconcile();
83
163
  const runs = made.runsOn(PICTURE);
84
- assert.equal(runs.length, 1);
85
- assert.equal(runs[0].from, 100, "where the viewer is stopped");
86
- assert.equal(runs[0].to, 999, "and on to the end of the film, nothing being in the way");
164
+ assert.equal(onTheStretchOf(made, 100), 1, "one encoder where the viewer is stopped");
165
+ assert.ok(runs.some((run) => run.from === 100), "and it begins exactly there");
166
+ });
167
+
168
+ test("an encoder already working covers what it will reach in time", () => {
169
+ // THE MODEL, not a case: a segment is late when it arrives after it is needed,
170
+ // and an encoder placed at `a` delivers `a + j` at `(j + 1) / r`. So the
171
+ // question asked of a working encoder is the same one asked of a new one —
172
+ // when would it get here — and the answer decides whether a second process is
173
+ // wanted at all.
174
+ const { made, buildRun } = orchestrator();
175
+ const first = buildRun({ from: 0, to: -1 });
176
+ first.start("a viewer needs it");
177
+ first.noteSpeed(8);
178
+ made.adopt(PICTURE, first);
179
+ made.noteProduced(PICTURE, 0);
180
+ made.noteProduced(PICTURE, 1);
181
+ assert.equal(first.head, 2, "where it stands");
182
+
183
+ const coverage = made.coverageOf(PICTURE);
184
+ assert.equal(coverage.stateOf(15), "making", "it holds the road it was given");
185
+ assert.equal(coverage.stateOf(500), "making", "all of it, to the end of the film");
186
+
187
+ // Wanted fourteen segments ahead of it, and not needed for a hundred seconds.
188
+ // At 8x on four-second segments it makes two a second, so it arrives in about
189
+ // seven — in time, and no second process is bought.
190
+ wants(made, [{ from: 15, to: 45, withinSeconds: 100 }]);
191
+ made.reconcile();
192
+ assert.equal(made.runsOn(PICTURE).length, 1, "one encoder, because one is enough");
193
+ assert.equal(made.runsOn(PICTURE)[0], first);
194
+ });
195
+
196
+ test("somebody stopped where no encoder can arrive in time is served, and the score says how", () => {
197
+ // The encoder that exists is 197 pieces behind them and would take 788 seconds
198
+ // to arrive. What serves them soonest is the question, and on a machine where
199
+ // a second encoder costs the first half its speed the answer is to bring this
200
+ // one — two of them, each at half, deliver the piece later than one at full.
201
+ //
202
+ // Nobody is watching where it stood, so nothing is lost by moving it. That the
203
+ // film there goes unmade is the third of the three counts, and the first —
204
+ // seconds anybody spends looking at a spinner — outranks it.
205
+ const { made, buildRun } = orchestrator();
206
+ const first = buildRun({ from: 0, to: -1 });
207
+ first.start("a viewer needs it");
208
+ first.noteSpeed(1);
209
+ made.adopt(PICTURE, first);
210
+ made.noteProduced(PICTURE, 0);
211
+ made.noteProduced(PICTURE, 1);
212
+ made.noteProduced(PICTURE, 2);
213
+
214
+ wants(made, [{ from: 200, to: 230, withinSeconds: 0 }]);
215
+ made.reconcile();
216
+
217
+ assert.equal(made.coverageOf(PICTURE).stateOf(200), "making",
218
+ "somebody is making what the viewer is waiting for");
219
+ assert.equal(onTheStretchOf(made, 200), 1, "and one encoder is on it, not a crowd");
220
+ });
221
+
222
+ test("two encoders on one output never share a segment number", () => {
223
+ // Non-overlap is not a rule here, it is a consequence: placements partition
224
+ // the line, because past its neighbour's start an encoder would only make
225
+ // what that neighbour makes sooner.
226
+ const { made, buildRun } = orchestrator();
227
+ const first = buildRun({ from: 0, to: -1 });
228
+ first.start("a viewer needs it");
229
+ first.noteSpeed(1);
230
+ made.adopt(PICTURE, first);
231
+ made.noteProduced(PICTURE, 0);
232
+ wants(made, [{ from: 200, to: 230, withinSeconds: 0 }]);
233
+ made.reconcile();
234
+ const spans = made.runsOn(PICTURE)
235
+ .map((run) => [run.from, run.to < run.from ? Number.POSITIVE_INFINITY : run.to])
236
+ .sort((left, right) => left[0] - right[0]);
237
+ for (let index = 0; index < spans.length - 1; index += 1) {
238
+ assert.ok(spans[index][1] < spans[index + 1][0],
239
+ `#${spans[index][0]}..#${spans[index][1]} must end before #${spans[index + 1][0]}`);
240
+ }
87
241
  });
88
242
 
89
243
  test("a second viewer at the same place starts nothing more", () => {
90
244
  // One encode serves everyone standing in front of it, which is the whole
91
245
  // reason the decision is made from a union and not per viewer.
92
246
  const { made } = orchestrator();
93
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 130 });
247
+ wants(made, [{ from: 100, to: 130 }]);
94
248
  made.reconcile();
95
- made.want({ claimant: "two", address: PICTURE, from: 102, to: 132 });
249
+ wants(made, [{ from: 102, to: 132 }]);
96
250
  made.reconcile();
97
- assert.equal(made.runsOn(PICTURE).length, 1);
251
+ assert.equal(onTheStretchOf(made, 102), 1, "the same encoder serves them both");
98
252
  });
99
253
 
100
- test("a second viewer far behind gets an encoder of their own", () => {
101
- // Nobody is dragged: the run in front keeps its stretch and goes on making it.
254
+ test("a second viewer far behind is served, at whatever the score says is soonest", () => {
255
+ // They may get an encoder of their own, or the one in front may come back to
256
+ // them — which is better depends on what a second process costs this machine,
257
+ // and that is measured. What must hold is that somebody is making what they
258
+ // are waiting for.
102
259
  const { made } = orchestrator();
103
- made.want({ claimant: "one", address: PICTURE, from: 500, to: 530 });
260
+ wants(made, [{ from: 500, to: 530, withinSeconds: 0 }]);
104
261
  made.reconcile();
105
- made.want({ claimant: "two", address: PICTURE, from: 100, to: 130 });
262
+ for (const run of made.runsOn(PICTURE)) {
263
+ run.noteSpeed(2);
264
+ }
265
+ wants(made, [
266
+ { from: 500, to: 530, withinSeconds: 0 },
267
+ { from: 100, to: 130, withinSeconds: 0 }
268
+ ]);
106
269
  made.reconcile();
107
- const spans = made.runsOn(PICTURE).map((run) => [run.from, run.to]);
108
- assert.equal(spans.length, 2);
109
- assert.ok(spans.some(([from]) => from === 500), "the one in front is untouched");
110
- assert.ok(spans.some(([from]) => from === 100), "the one behind got its own");
270
+
271
+ assert.equal(made.coverageOf(PICTURE).stateOf(100), "making", "the one behind is served");
272
+ assert.ok(made.runsOn(PICTURE).length <= 2, "and never more than the machine holds");
111
273
  });
112
274
 
113
275
  test("a machine that can afford one encoder does not start a second", () => {
114
276
  const { made } = orchestrator({ maxRuns: 1 });
115
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 130 });
277
+ wants(made, [{ from: 100, to: 130 }]);
116
278
  made.reconcile();
117
- made.want({ claimant: "two", address: PICTURE, from: 500, to: 530 });
279
+ wants(made, [{ from: 500, to: 530 }]);
118
280
  made.reconcile();
119
281
  assert.equal(made.runsOn(PICTURE).length, 1);
120
282
  });
@@ -122,7 +284,7 @@ test("a machine that can afford one encoder does not start a second", () => {
122
284
  test("a viewer asking for what is already made starts nothing", () => {
123
285
  const { made } = orchestrator();
124
286
  made.noteAlreadyMade(PICTURE, [100, 101, 102, 103, 104]);
125
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 104 });
287
+ wants(made, [{ from: 100, to: 104 }]);
126
288
  made.reconcile();
127
289
  assert.equal(made.runsOn(PICTURE).length, 0);
128
290
  });
@@ -132,19 +294,21 @@ test("segments left by a previous life of this process are used, not remade", ()
132
294
  // like any other, whoever made it and whatever became of them.
133
295
  const { made } = orchestrator();
134
296
  made.noteAlreadyMade(PICTURE, [100, 101, 102]);
135
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 110 });
297
+ wants(made, [{ from: 100, to: 110 }]);
136
298
  made.reconcile();
137
299
  const runs = made.runsOn(PICTURE);
138
- assert.equal(runs.length, 1);
139
- assert.equal(runs[0].from, 103, "it starts at the first thing missing");
300
+ assert.ok(runs.some((run) => run.from === 103), "it starts at the first thing missing");
301
+ assert.equal(onTheStretchOf(made, 103), 1, "and one encoder is enough for it");
140
302
  });
141
303
 
142
304
  test("a viewer who leaves takes the encoder with them", () => {
143
305
  const { made } = orchestrator();
144
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 130 });
306
+ wants(made, [{ from: 100, to: 130 }]);
145
307
  made.reconcile();
146
308
  assert.equal(made.runsOn(PICTURE).length, 1);
147
- made.release("one");
309
+ // Nobody left watching. An EMPTY map is how that is said: there is no name to
310
+ // release, because no viewer's name ever reaches this layer.
311
+ wants(made, []);
148
312
  made.reconcile();
149
313
  assert.equal(made.runsOn(PICTURE).length, 0);
150
314
  assert.equal(made.endings()[ENCODE_EXIT.STOPPED], 1);
@@ -152,7 +316,7 @@ test("a viewer who leaves takes the encoder with them", () => {
152
316
 
153
317
  test("a run that meets material made elsewhere is moved past it", () => {
154
318
  const { made } = orchestrator();
155
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 200 });
319
+ wants(made, [{ from: 100, to: 200 }]);
156
320
  made.reconcile();
157
321
  const first = made.runsOn(PICTURE)[0];
158
322
  // It has made a few, and meanwhile 105..150 arrived from somewhere else.
@@ -171,11 +335,11 @@ test("a run that meets material made elsewhere is moved past it", () => {
171
335
 
172
336
  test("every ending is counted, and our own kill is not counted as normal", () => {
173
337
  const { made, processes } = orchestrator();
174
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 130 });
338
+ wants(made, [{ from: 100, to: 130 }]);
175
339
  made.reconcile();
176
340
  const run = made.runsOn(PICTURE)[0];
177
341
  processes.get(run).emit("exit", 255, null);
178
- made.release("one");
342
+ wants(made, []);
179
343
  made.reconcile();
180
344
  const tally = made.endings();
181
345
  assert.equal(tally[ENCODE_EXIT.FAILED], 1);
@@ -187,7 +351,7 @@ test("the line says whether anybody is still waiting", () => {
187
351
  // making is the failure this layer removes; it has to be readable, not
188
352
  // inferred.
189
353
  const { made } = orchestrator();
190
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 130 });
354
+ wants(made, [{ from: 100, to: 130 }]);
191
355
  made.reconcile();
192
356
  assert.match(made.describe(), /waiting=#100/);
193
357
  for (let index = 100; index <= 130; index += 1) {
@@ -201,50 +365,16 @@ test("nothing wanted anywhere is said plainly", () => {
201
365
  assert.match(made.describe(), /nothing wanted/);
202
366
  });
203
367
 
204
- test("a run adopted with no end holds what it has made, not the rest of the film", () => {
205
- // A session's own encoder is handed to the plan rather than built by it, and
206
- // it carries `to = -1` — no end, which means the film's length is not known.
207
- // Claiming the film from there would leave a viewer further in with no
208
- // encoder at all: they would wait for this run to encode its way to them,
209
- // which on a long film is an hour. What it holds is what it has produced,
210
- // which is a fact rather than a distance nobody measured.
211
- const { made } = orchestrator({ maxRuns: 2 });
212
- const adopted = {
213
- from: 0,
214
- to: -1,
215
- head: 3,
216
- isAlive: true,
217
- isStopping: false,
218
- // Slow enough that the swarm is not what limits the count here: at 0.25
219
- // seconds of swarm time per second of film, one encoder at 1x takes a
220
- // quarter of what is delivered and four may run. The swarm's own limit has
221
- // its own check below.
222
- speedX: 1,
223
- stop() {
224
- this.isAlive = false;
225
- }
226
- };
227
- made.adopt(PICTURE, adopted);
228
-
229
- made.want({ claimant: "far", address: PICTURE, from: 200, to: 230 });
230
- made.reconcile();
231
-
232
- const runs = made.runsOn(PICTURE);
233
- assert.equal(runs.length, 2, "the viewer further in got an encoder of their own");
234
- assert.ok(adopted.isAlive, "and the adopted run was not stopped to make room");
235
- assert.equal(runs.some((run) => run.from === 200), true, "started where that viewer is waiting");
236
- });
237
-
238
368
  test("the swarm limits the encoders, whatever the processor allows", () => {
239
369
  // Every encoder reads the same torrent, so together they cannot consume
240
370
  // faster than it is delivered. At 0.25 seconds of swarm time per second of
241
371
  // film, one encoder running at 8x takes twice everything there is — so a
242
372
  // machine whose processor would allow two gets one.
243
373
  const { made, lines } = orchestrator({ maxRuns: 2 });
244
- made.want({ claimant: "one", address: PICTURE, from: 100, to: 130 });
374
+ wants(made, [{ from: 100, to: 130 }]);
245
375
  made.reconcile();
246
376
  made.runsOn(PICTURE)[0].noteSpeed(8);
247
- made.want({ claimant: "two", address: PICTURE, from: 500, to: 530 });
377
+ wants(made, [{ from: 500, to: 530 }]);
248
378
  made.reconcile();
249
379
 
250
380
  assert.equal(made.runsOn(PICTURE).length, 1);