@torrent-tv/proxy 2.107.62 → 2.107.64

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 (41) hide show
  1. package/package.json +1 -1
  2. package/services/encode/EncodeInputs.js +3 -10
  3. package/services/encode/OutputWaitLedger.js +3 -1
  4. package/services/encode/PauseRule.js +3 -7
  5. package/services/encode/available-share.js +2 -10
  6. package/services/encode/learned-median.js +3 -38
  7. package/services/encode/quality/HostLoad.js +5 -4
  8. package/services/encode/run-costs.js +5 -22
  9. package/services/media/SubtitleCues.js +2 -1
  10. package/services/media/container/ElementaryAddresses.js +46 -0
  11. package/services/media/container/ac3-frame.js +5 -6
  12. package/services/media/container/avc-picture-order.js +2 -2
  13. package/services/media/container/bitstream.js +180 -0
  14. package/services/media/container/dts-frame.js +29 -13
  15. package/services/media/container/h264-configuration.js +4 -34
  16. package/services/media/container/h264-elementary-index.js +24 -51
  17. package/services/media/container/hevc-configuration.js +9 -25
  18. package/services/media/container/hevc-elementary-index.js +7 -11
  19. package/services/media/container/hevc-picture-order.js +3 -18
  20. package/services/media/container/latm-frame.js +11 -54
  21. package/services/media/container/mpeg-elementary-index.js +12 -25
  22. package/services/media/container/mpeg-video-configuration.js +12 -14
  23. package/services/media/container/mpeg4-picture-timing.js +4 -4
  24. package/services/media/tracks/audio-bound.js +10 -52
  25. package/services/server/ViewerRequests.js +2 -1
  26. package/services/server/wire-outputs.js +3 -2
  27. package/services/storage/Diagnostics.js +1 -7
  28. package/services/storage/MachineBudget.js +10 -6
  29. package/services/storage/machine-processor.js +1 -10
  30. package/services/storage/memory-report.js +17 -26
  31. package/services/storage/piece-store/shared-piece-store.js +6 -7
  32. package/services/storage/processor-report.js +2 -7
  33. package/services/storage/returns.js +3 -2
  34. package/services/storage/segment-store/SegmentStore.js +2 -1
  35. package/services/torrent/supply-margin.js +3 -11
  36. package/services/torrent/torrent-pool.js +4 -3
  37. package/services/torrent/worker/piece-reader.js +2 -5
  38. package/services/torrent/worker/worker.js +12 -11
  39. package/utils/clamp.js +11 -0
  40. package/utils/median.js +66 -0
  41. package/utils/units.js +35 -0
@@ -32,13 +32,7 @@
32
32
  * PURE: plain values in, plain values out. No container, no torrent.
33
33
  */
34
34
 
35
- /** ISO/IEC 14496-3 Table 1.18: samplingFrequencyIndex to Hz. 0xF is explicit. */
36
- const AAC_SAMPLING_FREQUENCIES = Object.freeze([
37
- 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350
38
- ]);
39
-
40
- /** ISO/IEC 14496-3 Table 1.19: channelConfiguration to channels; 0 is a PCE. */
41
- const AAC_CHANNELS = Object.freeze([null, 1, 2, 3, 4, 5, 6, 8]);
35
+ import { parseAudioSpecificConfig as readAudioSpecificConfig } from "../container/bitstream.js";
42
36
 
43
37
  /** The AAC-LC object type, and the one frame length the bound is stated for. */
44
38
  const AAC_LC = 2;
@@ -62,29 +56,6 @@ const AC3_SAMPLES_PER_FRAME = 1536;
62
56
  * @property {number | null} sampleRate - Hz.
63
57
  */
64
58
 
65
- /**
66
- * A minimal MSB-first bit reader over a buffer.
67
- *
68
- * @param {Buffer} bytes
69
- */
70
- function bitReader(bytes) {
71
- let position = 0;
72
- return {
73
- read(count) {
74
- let value = 0;
75
- for (let i = 0; i < count; i += 1) {
76
- const byte = bytes[position >> 3];
77
- if (byte === undefined) {
78
- throw new RangeError("AudioSpecificConfig ended early");
79
- }
80
- value = (value * 2) + ((byte >> (7 - (position & 7))) & 1);
81
- position += 1;
82
- }
83
- return value;
84
- }
85
- };
86
- }
87
-
88
59
  /**
89
60
  * The fields of an AudioSpecificConfig the bound is computed from (ISO/IEC
90
61
  * 14496-3 §1.6.2.1 and the GASpecificConfig that follows it for AAC-LC).
@@ -94,30 +65,17 @@ function bitReader(bytes) {
94
65
  * Null when the bytes are not a readable config.
95
66
  */
96
67
  export function parseAudioSpecificConfig(bytes) {
97
- if (!Buffer.isBuffer(bytes) || bytes.length < 2) {
98
- return null;
99
- }
100
- try {
101
- const bits = bitReader(bytes);
102
- let objectType = bits.read(5);
103
- if (objectType === 31) {
104
- objectType = 32 + bits.read(6);
105
- }
106
- const frequencyIndex = bits.read(4);
107
- const sampleRate = frequencyIndex === 0xf
108
- ? bits.read(24)
109
- : (AAC_SAMPLING_FREQUENCIES[frequencyIndex] ?? null);
110
- const channelConfiguration = bits.read(4);
111
- const channels = AAC_CHANNELS[channelConfiguration] ?? null;
112
- // GASpecificConfig begins with frameLengthFlag for the object types that
113
- // carry one; for any other the frame length is not read here.
114
- const frameLength = objectType === AAC_LC
115
- ? (bits.read(1) === 1 ? 960 : AAC_LC_FRAME_LENGTH)
116
- : null;
117
- return { objectType, sampleRate: sampleRate > 0 ? sampleRate : null, channels, frameLength };
118
- } catch {
68
+ const config = readAudioSpecificConfig(bytes);
69
+ if (!config) {
119
70
  return null;
120
71
  }
72
+ return {
73
+ objectType: config.objectType,
74
+ sampleRate: config.sampleRate > 0 ? config.sampleRate : null,
75
+ channels: config.channels,
76
+ // Only the AAC-LC bound is stated for a frame length, so only AAC-LC reports one.
77
+ frameLength: config.objectType === AAC_LC ? config.frameLength : null
78
+ };
121
79
  }
122
80
 
123
81
  /**
@@ -7,6 +7,7 @@
7
7
  * returns; where encoders go follows from those facts and is the plan's.
8
8
  */
9
9
 
10
+ import { megabytesPerSecond } from "../../utils/units.js";
10
11
  import { logger } from "../../utils/logger.js";
11
12
  import { isOutputName, OutputSpec } from "../encode/output/index.js";
12
13
  import { withSubtitleReadiness } from "./subtitle-readiness.js";
@@ -1254,7 +1255,7 @@ export class ViewerRequests {
1254
1255
  `${operation.track} ${operation.operation} ${Number.isFinite(operation.speed) ? operation.speed.toFixed(2) : "?"}x`);
1255
1256
  const downloads = (input.sources ?? []).map(source => {
1256
1257
  const rate = this.#host.playbackReadiness.forecastRate(source.downloadRateReadings, now, 0, "time");
1257
- return `${Number.isFinite(rate) ? (rate / 1_048_576).toFixed(2) : "?"} MB/s`;
1258
+ return megabytesPerSecond(rate);
1258
1259
  });
1259
1260
  logger.info(`playback held ${session.id} consumer=${consumerId}: delay ${seconds(delay)}s by ` +
1260
1261
  (holding.kind === "position-not-held" ? "the position, which nothing buffered covers" :
@@ -11,6 +11,7 @@
11
11
  import { EventEmitter } from "node:events";
12
12
  import { writeJsonAtomic } from "../../utils/atomic-json.js";
13
13
  import { logger } from "../../utils/logger.js";
14
+ import { megabytesPerSecond } from "../../utils/units.js";
14
15
  import { KeyframeTables } from "../media/KeyframeTables.js";
15
16
  import { matroskaIdOf } from "../media/tracks/codec-names.js";
16
17
  import { bandOf, WaitLedger } from "../encode/OutputWaitLedger.js";
@@ -828,8 +829,8 @@ export function wireOutputs({
828
829
  because = `${made}; the swarm's rate is not measured yet`;
829
830
  } else {
830
831
  held = swarm > needs;
831
- because = `${made}; the swarm gives ${(swarm / 1e6).toFixed(2)} MB/s, ` +
832
- `${held ? "more than" : "not more than"} the ${(needs / 1e6).toFixed(2)} MB/s its film needs at ${asked.toFixed(2)}x`;
832
+ because = `${made}; the swarm gives ${megabytesPerSecond(swarm)}, ` +
833
+ `${held ? "more than" : "not more than"} the ${megabytesPerSecond(needs)} its film needs at ${asked.toFixed(2)}x`;
833
834
  }
834
835
  }
835
836
  if (held === parts.speculativeHeld) return;
@@ -43,6 +43,7 @@
43
43
  * left where it is: changing it is a decision about evidence, not about disk.
44
44
  */
45
45
 
46
+ import { megabytes } from "../../utils/units.js";
46
47
  import { readdir, stat } from "node:fs/promises";
47
48
  import path from "node:path";
48
49
 
@@ -193,10 +194,3 @@ export class Diagnostics {
193
194
  }
194
195
  }
195
196
 
196
- /**
197
- * @param {number} bytes
198
- * @returns {string}
199
- */
200
- function megabytes(bytes) {
201
- return `${Math.round(Math.max(0, bytes) / (1024 * 1024))}MB`;
202
- }
@@ -49,6 +49,7 @@
49
49
  * is the one kind of number that is not ours to derive.
50
50
  */
51
51
 
52
+ import { mebibytes, megabytes } from "../../utils/units.js";
52
53
  import { OtherDemand, divideAllowance } from "./allowance.js";
53
54
 
54
55
  /**
@@ -242,8 +243,8 @@ export class MachineBudget {
242
243
  // SAID, because a claimant working below what it needs is a fault of
243
244
  // the machine and not of the code, and it is invisible otherwise.
244
245
  this.#logger?.warn?.(
245
- `budget: ${share.name} has ${megabytes(share.allowed)} of ${name}, ` +
246
- `below the ${megabytes(claimants.find((one) => one.name === share.name)?.minimum ?? 0)} it needs`
246
+ `budget: ${share.name} has ${printed(name, share.allowed)} of ${name}, ` +
247
+ `below the ${printed(name, claimants.find((one) => one.name === share.name)?.minimum ?? 0)} it needs`
247
248
  );
248
249
  }
249
250
  }
@@ -297,18 +298,21 @@ export class MachineBudget {
297
298
  const lines = [];
298
299
  for (const [name, reading] of this.#last) {
299
300
  const parts = reading.shares.map(
300
- (share) => `${share.name} ${megabytes(share.held)} of ${megabytes(share.allowed)}${share.short ? " (short)" : ""}`
301
+ (share) => `${share.name} ${printed(name, share.held)} of ${printed(name, share.allowed)}${share.short ? " (short)" : ""}`
301
302
  );
302
- lines.push(`${name}: ${megabytes(reading.freeBytes)} free; ${parts.join(", ")}`);
303
+ lines.push(`${name}: ${printed(name, reading.freeBytes)} free; ${parts.join(", ")}`);
303
304
  }
304
305
  return `budget — ${lines.join(" | ")}`;
305
306
  }
306
307
  }
307
308
 
308
309
  /**
310
+ * Memory is printed in binary units under its own label, a disk (data) in decimal.
311
+ *
312
+ * @param {string} resource
309
313
  * @param {number} bytes
310
314
  * @returns {string}
311
315
  */
312
- function megabytes(bytes) {
313
- return `${Math.round(Math.max(0, bytes) / (1024 * 1024))}MB`;
316
+ function printed(resource, bytes) {
317
+ return resource === "memory" ? mebibytes(bytes) : megabytes(bytes);
314
318
  }
@@ -28,6 +28,7 @@
28
28
  * (`machine-memory.js`); the cgroup is found the same way.
29
29
  */
30
30
 
31
+ import { clamp } from "../../utils/clamp.js";
31
32
  import { readFileSync } from "node:fs";
32
33
  import os from "node:os";
33
34
 
@@ -383,13 +384,3 @@ function statField(text, name) {
383
384
  }
384
385
  return null;
385
386
  }
386
-
387
- /**
388
- * @param {number} value
389
- * @param {number} low
390
- * @param {number} high
391
- * @returns {number}
392
- */
393
- function clamp(value, low, high) {
394
- return Math.min(high, Math.max(low, value));
395
- }
@@ -22,6 +22,7 @@
22
22
  import { readdir, readFile, rm, statfs } from "node:fs/promises";
23
23
  import { availableMemory } from "./machine-memory.js";
24
24
  import os from "node:os";
25
+ import { megabytes, mebibytes } from "../../utils/units.js";
25
26
  import v8 from "node:v8";
26
27
  import path from "node:path";
27
28
 
@@ -217,16 +218,6 @@ async function readDiskFree(directory) {
217
218
  return null;
218
219
  }
219
220
 
220
- /**
221
- * Render a size the way a person reads one.
222
- *
223
- * @param {number} bytes
224
- * @returns {string}
225
- */
226
- function megabytes(bytes) {
227
- return `${Math.round(bytes / (1024 * 1024))}MB`;
228
- }
229
-
230
221
  /**
231
222
  * One line saying what the process holds and what the machine has left.
232
223
  *
@@ -282,27 +273,27 @@ export function describeMemory({
282
273
  // grows, so a spilled piece frees a slot and no memory.
283
274
  const storesPart = stores.length === 0
284
275
  ? "no torrent stores"
285
- : `${stores.length} torrent store(s) holding ${megabytes(storeResident)}, ` +
286
- `committed ${megabytes(storeCommitted)} of ${megabytes(storeBudget)} allowed, ` +
276
+ : `${stores.length} torrent store(s) holding ${mebibytes(storeResident)}, ` +
277
+ `committed ${mebibytes(storeCommitted)} of ${mebibytes(storeBudget)} allowed, ` +
287
278
  `${megabytes(storeSpilled)} spilled to disk`;
288
279
  const isolate =
289
- `heap=${megabytes(usage.heapUsed)}/${megabytes(usage.heapTotal)}` +
290
- `${usage.heapLimit ? ` of ${megabytes(usage.heapLimit)} allowed` : ""} ` +
291
- `external=${megabytes(usage.external)} arrayBuffers=${megabytes(usage.arrayBuffers)}`;
280
+ `heap=${mebibytes(usage.heapUsed)}/${mebibytes(usage.heapTotal)}` +
281
+ `${usage.heapLimit ? ` of ${mebibytes(usage.heapLimit)} allowed` : ""} ` +
282
+ `external=${mebibytes(usage.external)} arrayBuffers=${mebibytes(usage.arrayBuffers)}`;
292
283
  const tail = extra ? `; ${extra}` : "";
293
284
  if (scope === "thread") {
294
285
  return `memory (${label || "thread"}): ${isolate}; ${storesPart}${tail}`;
295
286
  }
296
287
  const shape = mappings === null
297
288
  ? ""
298
- : ` mappings=[heap ${megabytes(mappings.heapBytes)}, ` +
299
- `${mappings.largeCount} anon ≥2MB = ${megabytes(mappings.largeBytes)} ` +
300
- `(largest ${megabytes(mappings.largestBytes)}), ` +
301
- `${mappings.smallCount} anon <2MB = ${megabytes(mappings.smallBytes)}, ` +
302
- `files ${megabytes(mappings.fileBytes)}]`;
289
+ : ` mappings=[heap ${mebibytes(mappings.heapBytes)}, ` +
290
+ `${mappings.largeCount} anon ≥2MiB = ${mebibytes(mappings.largeBytes)} ` +
291
+ `(largest ${mebibytes(mappings.largestBytes)}), ` +
292
+ `${mappings.smallCount} anon <2MiB = ${mebibytes(mappings.smallBytes)}, ` +
293
+ `files ${mebibytes(mappings.fileBytes)}]`;
303
294
  return (
304
- `memory: rss=${megabytes(usage.rss)} ${isolate}` +
305
- `${anonymousBytes === null ? "" : ` anon=${megabytes(anonymousBytes)}`}${shape}; ` +
295
+ `memory: rss=${mebibytes(usage.rss)} ${isolate}` +
296
+ `${anonymousBytes === null ? "" : ` anon=${mebibytes(anonymousBytes)}`}${shape}; ` +
306
297
  `${storesPart}; ` +
307
298
  describeAvailable(available) +
308
299
  `${diskFreeBytes === null ? "" : `, ${megabytes(diskFreeBytes)} free on disk`}` +
@@ -326,8 +317,8 @@ function describeAvailable(available) {
326
317
  : `${available.source} decides`;
327
318
  const limit = available.limitBytes === null
328
319
  ? "no container limit"
329
- : `container limit ${megabytes(available.limitBytes)}`;
330
- return `machine has ${megabytes(available.bytes)} available (${decided}; ${limit})`;
320
+ : `container limit ${mebibytes(available.limitBytes)}`;
321
+ return `machine has ${mebibytes(available.bytes)} available (${decided}; ${limit})`;
331
322
  }
332
323
 
333
324
  /**
@@ -500,7 +491,7 @@ export function startMemoryReport({
500
491
  // that names what is holding the memory, and it is why it is bounded by
501
492
  // a floor, by a growth step and by how many are kept.
502
493
  v8.writeHeapSnapshot(snapPath);
503
- log(`memory: wrote heap snapshot of the ${label || scope} to ${snapPath} (${megabytes(watchedBytes)}, ${why})`);
494
+ log(`memory: wrote heap snapshot of the ${label || scope} to ${snapPath} (${mebibytes(watchedBytes)}, ${why})`);
504
495
  } catch {
505
496
  // silent-ok: no snapshot is worse than a snapshot, and much better than
506
497
  // ending the series that leads to the next one.
@@ -628,7 +619,7 @@ export function startMemoryReport({
628
619
  // line is, and at one reading a second an unconditional warning would be
629
620
  // a line a second for as long as the process stayed large.
630
621
  if (scope !== "thread" && anonymousBytes !== null && processMemory.rss > 800 * 1024 * 1024) {
631
- log(`memory: high rss=${megabytes(processMemory.rss)} anon=${megabytes(anonymousBytes)} heap=${megabytes(processMemory.heapUsed)} — watch for OOM`);
622
+ log(`memory: high rss=${mebibytes(processMemory.rss)} anon=${mebibytes(anonymousBytes)} heap=${mebibytes(processMemory.heapUsed)} — watch for OOM`);
632
623
  }
633
624
  } catch {
634
625
  // silent-ok: a reading that fails is not worth ending the series over.
@@ -41,6 +41,7 @@
41
41
  * and nothing here disagrees.
42
42
  */
43
43
 
44
+ import { medianOf, upperMiddleOf } from "../../../utils/median.js";
44
45
  import { divideAllowance, machineAllowanceBytes, OtherDemand } from "../allowance.js";
45
46
  import { availableMemoryBytes as availableMemorySync } from "../machine-memory.js";
46
47
  import { PieceLru } from "./piece-lru.js";
@@ -269,11 +270,7 @@ function median(values) {
269
270
  if (values.length === 0) {
270
271
  return null;
271
272
  }
272
- const sorted = [...values].sort((left, right) => left - right);
273
- const middle = Math.floor(sorted.length / 2);
274
- return sorted.length % 2 === 0
275
- ? Math.round((sorted[middle - 1] + sorted[middle]) / 2)
276
- : sorted[middle];
273
+ return Math.round(medianOf(values));
277
274
  }
278
275
  const CLAIM_RETRY_MS = 50;
279
276
 
@@ -1101,8 +1098,10 @@ export class SharedPieceStore {
1101
1098
  if (this.#writeDurations.length === 0 || this.#admittedAt.length < 2) {
1102
1099
  return 0;
1103
1100
  }
1104
- const sorted = [...this.#writeDurations].sort((left, right) => left - right);
1105
- const writeMs = sorted[Math.floor(sorted.length / 2)];
1101
+ // The upper middle, not the true median, on purpose: slack is a number of
1102
+ // pieces to keep in hand, so the slower of the two middle writes is the
1103
+ // safe side and a count stays an integer. Unchanged since before #294.
1104
+ const writeMs = upperMiddleOf(this.#writeDurations);
1106
1105
  const spanMs = this.#admittedAt[this.#admittedAt.length - 1] - this.#admittedAt[0];
1107
1106
  if (!(spanMs > 0)) {
1108
1107
  return 0;
@@ -22,6 +22,7 @@
22
22
  * beside it; nothing decides on it yet.
23
23
  */
24
24
 
25
+ import { medianOf, scatterOf } from "../../utils/median.js";
25
26
  import { readFileSync, readdirSync } from "node:fs";
26
27
 
27
28
  /** Clock ticks per second of `/proc/<pid>/stat`, as in `encode/host-load.js`. */
@@ -269,13 +270,7 @@ export function describeRuns(runs) {
269
270
  */
270
271
  function middleAndScatter(values) {
271
272
  if (values.length === 0) return null;
272
- const median = (list) => {
273
- const sorted = [...list].sort((a, b) => a - b);
274
- const half = Math.floor(sorted.length / 2);
275
- return sorted.length % 2 === 0 ? (sorted[half - 1] + sorted[half]) / 2 : sorted[half];
276
- };
277
- const middle = median(values);
278
- return { middle, scatter: median(values.map((value) => Math.abs(value - middle))) };
273
+ return { middle: medianOf(values), scatter: scatterOf(values) };
279
274
  }
280
275
 
281
276
  /**
@@ -16,6 +16,8 @@
16
16
  * what viewers actually do instead of from what a period felt like.
17
17
  */
18
18
 
19
+ import { medianOf } from "../../utils/median.js";
20
+
19
21
  /** How many returns are kept. Enough to see a shape, few enough to say in a line. */
20
22
  const KEPT = 200;
21
23
 
@@ -65,11 +67,10 @@ export class Returns {
65
67
  return null;
66
68
  }
67
69
  const sorted = [...this.#ages].sort((left, right) => left - right);
68
- const middle = Math.floor(sorted.length / 2);
69
70
  return {
70
71
  warm: this.#warm,
71
72
  cold: this.#cold,
72
- medianMs: sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle],
73
+ medianMs: medianOf(sorted),
73
74
  longestMs: sorted[sorted.length - 1]
74
75
  };
75
76
  }
@@ -45,6 +45,7 @@ import { rmSync } from "node:fs";
45
45
  import os from "node:os";
46
46
  import path from "node:path";
47
47
  import { writeFileAtomic } from "../../../utils/atomic-json.js";
48
+ import { megabytes } from "../../../utils/units.js";
48
49
 
49
50
  /** Where every output's segments live. One root for the process. */
50
51
  const DEFAULT_STORE_ROOT = path.join(os.tmpdir(), "torrent-tv-hls");
@@ -1388,7 +1389,7 @@ export class SegmentStore {
1388
1389
  if (found.length > 0) {
1389
1390
  this.#logger.info(
1390
1391
  `segment-store startup sweep: ${found.length} directories left by a previous run, ` +
1391
- `${totals.segments} segments, ${(totals.bytes / 1048576).toFixed(1)}MB, ` +
1392
+ `${totals.segments} segments, ${megabytes(totals.bytes)}, ` +
1392
1393
  `${unidentified} of them unidentifiable — each one is an encoder that ended ` +
1393
1394
  "without anything recording why"
1394
1395
  );
@@ -55,6 +55,8 @@
55
55
  * nothing smooths, weights or decays anything.
56
56
  */
57
57
 
58
+ import { medianOf } from "../../utils/median.js";
59
+
58
60
  /**
59
61
  * One measured interruption: how long a read waited, and when the wait ended.
60
62
  *
@@ -106,7 +108,7 @@ export function requiredSpeedFrom(waits) {
106
108
  if (intervals.length === 0) {
107
109
  return null;
108
110
  }
109
- const medianIntervalSec = median(intervals);
111
+ const medianIntervalSec = medianOf(intervals);
110
112
  if (!(medianIntervalSec > 0)) {
111
113
  return null;
112
114
  }
@@ -244,16 +246,6 @@ function usableWaits(waits) {
244
246
  .sort((left, right) => left.at - right.at);
245
247
  }
246
248
 
247
- /**
248
- * @param {number[]} values - Non-empty.
249
- * @returns {number}
250
- */
251
- function median(values) {
252
- const sorted = [...values].sort((left, right) => left - right);
253
- const middle = Math.floor(sorted.length / 2);
254
- return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
255
- }
256
-
257
249
  /**
258
250
  * @param {unknown} value
259
251
  * @returns {number}
@@ -8,6 +8,7 @@
8
8
  * download.
9
9
  */
10
10
 
11
+ import { megabytes } from "../../utils/units.js";
11
12
  import { IDLE_KEEP_MS, SWARM_HOLD_MS } from "../storage/keep.js";
12
13
  import dns from "node:dns/promises";
13
14
  import os from "node:os";
@@ -1658,14 +1659,14 @@ export class TorrentPool {
1658
1659
  for (const zone of ordered) {
1659
1660
  const level = levelOf(zone);
1660
1661
  const byteCount = Math.max(0, Math.min(length - 1, zone.byteEnd) - zone.byteStart + 1);
1661
- const held = byLevel.get(level) ?? { zones: 0, megabytes: 0 };
1662
+ const held = byLevel.get(level) ?? { zones: 0, bytes: 0 };
1662
1663
  held.zones += 1;
1663
- held.megabytes += byteCount / 1048576;
1664
+ held.bytes += byteCount;
1664
1665
  byLevel.set(level, held);
1665
1666
  }
1666
1667
  const shape = [...byLevel.entries()]
1667
1668
  .sort((left, right) => right[0] - left[0])
1668
- .map(([level, held]) => `${urgencyName(level)} ${held.zones} zone(s) ${held.megabytes.toFixed(0)}MB`)
1669
+ .map(([level, held]) => `${urgencyName(level)} ${held.zones} zone(s) ${megabytes(held.bytes)}`)
1669
1670
  .join(", ");
1670
1671
  // Something is wanted of this torrent, which may be news: a map published
1671
1672
  // for a file of a torrent whose swarm was let go is what takes it back.
@@ -20,6 +20,7 @@
20
20
  * with those bytes — not when they were sent, because nothing was sent.
21
21
  */
22
22
 
23
+ import { medianOf } from "../../../utils/median.js";
23
24
  import { pieceStoreOf } from "../piece-store-of.js";
24
25
  import { urgencyName } from "../demand/index.js";
25
26
  import { demandFor } from "../download/registry.js";
@@ -232,14 +233,10 @@ function describeWaitLevels(key) {
232
233
  if (!byLevel || byLevel.size === 0) {
233
234
  return null;
234
235
  }
235
- const middle = (values) => {
236
- const sorted = [...values].sort((left, right) => left - right);
237
- return sorted[Math.floor(sorted.length / 2)];
238
- };
239
236
  return [...byLevel.entries()]
240
237
  .sort(([left], [right]) => left - right)
241
238
  .map(([urgency, waits]) =>
242
- `${urgencyName(urgency)} ${waits.length} waits median ${middle(waits)}ms ` +
239
+ `${urgencyName(urgency)} ${waits.length} waits median ${Math.round(medianOf(waits))}ms ` +
243
240
  `worst ${Math.max(...waits)}ms`)
244
241
  .join(", ");
245
242
  }
@@ -20,6 +20,7 @@
20
20
  // before WebTorrent can reach the native one. Two isolates using
21
21
  // node-datachannel at once abort the process, and the torrent's wss trackers
22
22
  // create peer connections of their own.
23
+ import { megabytes, mebibytes } from "../../../utils/units.js";
23
24
  import { isUsableTorrentHandle, requireCurrentTorrent } from "./handle-state.js";
24
25
  import "./install-webrtc-shim.js";
25
26
  import { parentPort, workerData } from "node:worker_threads";
@@ -826,21 +827,21 @@ setInterval(() => {
826
827
  if (revised.evicted > 0) {
827
828
  log(
828
829
  `piece-store "${revised.name.slice(0, 40)}": allowance is now ` +
829
- `${Math.round(revised.ceilingBytes / 1048576)}MB, evicted ${revised.evicted} piece(s) to meet it` +
830
+ `${mebibytes(revised.ceilingBytes)}, evicted ${revised.evicted} piece(s) to meet it` +
830
831
  (revised.releasedBlocks > 0 ? `, gave back ${revised.releasedBlocks} block(s) of memory` : "") +
831
- ` — now ${Math.round(revised.committedBytes / 1048576)}MB committed`
832
+ ` — now ${mebibytes(revised.committedBytes)} committed`
832
833
  );
833
834
  } else if (revised.belowActiveDemand) {
834
835
  log(
835
836
  `piece-store "${revised.name.slice(0, 40)}": the machine's share is smaller than active read demand, ` +
836
- `so the allowance is held at ${Math.round(revised.ceilingBytes / 1048576)}MB ` +
837
+ `so the allowance is held at ${mebibytes(revised.ceilingBytes)} ` +
837
838
  "— a store cannot finish a read if it cannot hold the pieces that read is using"
838
839
  );
839
840
  } else if (revised.committedBytes > revised.ceilingBytes) {
840
841
  log(
841
842
  `piece-store "${revised.name.slice(0, 40)}": allowance is now ` +
842
- `${Math.round(revised.ceilingBytes / 1048576)}MB and ` +
843
- `${Math.round(revised.committedBytes / 1048576)}MB is committed — ` +
843
+ `${mebibytes(revised.ceilingBytes)} and ` +
844
+ `${mebibytes(revised.committedBytes)} is committed — ` +
844
845
  `all resident pieces are pinned, cannot shrink yet`
845
846
  );
846
847
  }
@@ -863,7 +864,7 @@ setInterval(() => {
863
864
  if (reserveNow !== reserveBefore || reserveNow !== lastReserveBytes) {
864
865
  lastReserveBytes = reserveNow;
865
866
  log(
866
- `piece-store: leaving ${Math.round(reserveNow / 1048576)}MB for everything else on this ` +
867
+ `piece-store: leaving ${mebibytes(reserveNow)} for everything else on this ` +
867
868
  "machine — the largest fall in available memory this process has seen and did not cause"
868
869
  );
869
870
  }
@@ -882,11 +883,11 @@ setInterval(() => {
882
883
  const fromMemoryShare = reads > 0 ? ((stats.fromMemory / reads) * 100).toFixed(1) : "—";
883
884
  log(
884
885
  `piece-store "${stats.name.slice(0, 40)}": resident=${stats.resident}/${stats.capacity} ` +
885
- `(${Math.round((stats.residentBytes || 0) / 1048576)}MB of ` +
886
- `${Math.round((stats.budgetBytes || 0) / 1048576)}MB allowed) ` +
887
- `committed=${Math.round((stats.committedBytes || 0) / 1048576)}MB ` +
886
+ `(${mebibytes(stats.residentBytes || 0)} of ` +
887
+ `${mebibytes(stats.budgetBytes || 0)} allowed) ` +
888
+ `committed=${mebibytes(stats.committedBytes || 0)} ` +
888
889
  `blocks=${stats.blocksAllocated} (${stats.blocksFree} spare) ` +
889
- `on-disk=${Math.round((stats.spilledBytes || 0) / 1048576)}MB ` +
890
+ `on-disk=${megabytes(stats.spilledBytes || 0)} ` +
890
891
  `pinned=${stats.pinned} spilled=${stats.spilled} reads=${reads} (${fromMemoryShare}% from memory) ` +
891
892
  `spills=${stats.spills} revivals=${stats.revivals}` +
892
893
  (stats.blockedByPins > 0 ? ` no-block-for=${stats.blockedByPins}` : "") +
@@ -1206,7 +1207,7 @@ async function keepWholeFiles() {
1206
1207
  });
1207
1208
  if (kept) {
1208
1209
  logger.info(
1209
- `whole files: kept "${file.name}" (${Math.round(kept.length / 1048576)}MB, ` +
1210
+ `whole files: kept "${file.name}" (${megabytes(kept.length)}, ` +
1210
1211
  `written in ${((performance.now() - startedAt) / 1000).toFixed(1)}s) — ` +
1211
1212
  "it is a file now, and reading it needs no torrent"
1212
1213
  );
package/utils/clamp.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The value, held between `low` and `high` (torrent-tv/meta#294: one clamp).
3
+ *
4
+ * @param {number} value
5
+ * @param {number} low
6
+ * @param {number} high
7
+ * @returns {number}
8
+ */
9
+ export function clamp(value, low, high) {
10
+ return Math.min(high, Math.max(low, value));
11
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @file The one median (torrent-tv/meta#294).
3
+ *
4
+ * Every place that needs the middle of a set of readings takes it from here, so
5
+ * that two logs saying "median" mean the same thing. Layers that may not import
6
+ * `utils/` (`viewer/`, `encode/output/`, `media/container/`) are handed the
7
+ * function instead.
8
+ */
9
+
10
+ /**
11
+ * The finite readings, ascending, as a new array.
12
+ *
13
+ * @param {number[]} values
14
+ * @returns {number[]}
15
+ */
16
+ function sortedFinite(values) {
17
+ return (Array.isArray(values) ? values : []).filter((value) => Number.isFinite(value)).sort((left, right) => left - right);
18
+ }
19
+
20
+ /**
21
+ * The middle of a set of readings, or null when there are none. Readings that
22
+ * are not finite numbers are left out; on an even count the two middle
23
+ * readings are averaged.
24
+ *
25
+ * @param {number[]} values
26
+ * @returns {number | null}
27
+ */
28
+ export function medianOf(values) {
29
+ const sorted = sortedFinite(values);
30
+ if (sorted.length === 0) {
31
+ return null;
32
+ }
33
+ const middle = Math.floor(sorted.length / 2);
34
+ return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
35
+ }
36
+
37
+ /**
38
+ * The element at index floor(n / 2) of the sorted finite readings: the upper of
39
+ * the two middle readings on an even count, never their mean, so a count stays
40
+ * an integer. Null when there are none.
41
+ *
42
+ * @param {number[]} values
43
+ * @returns {number | null}
44
+ */
45
+ export function upperMiddleOf(values) {
46
+ const sorted = sortedFinite(values);
47
+ return sorted.length === 0 ? null : sorted[Math.floor(sorted.length / 2)];
48
+ }
49
+
50
+ /**
51
+ * How far the readings sit from their own middle: the median of their
52
+ * distances to it. The median distance rather than the mean one, for the same
53
+ * reason the value itself is a median: a single disturbed reading describes the
54
+ * disturbance, not the host.
55
+ *
56
+ * @param {number[]} values
57
+ * @returns {number | null} Null when there is nothing to measure. Zero is a
58
+ * real answer: readings that all agree disagree by nothing.
59
+ */
60
+ export function scatterOf(values) {
61
+ const middle = medianOf(values);
62
+ if (middle === null) {
63
+ return null;
64
+ }
65
+ return medianOf(sortedFinite(values).map((value) => Math.abs(value - middle)));
66
+ }