@torrent-tv/proxy 2.59.3 → 2.61.0

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.
@@ -0,0 +1,148 @@
1
+ /**
2
+ * @file How far ahead of the viewer a held segment request may sit.
3
+ *
4
+ * A request is released when the viewer has moved away from it. "Moved away"
5
+ * used to mean more than `MAX_LOOKAHEAD_SEGMENTS` — eight segments, which
6
+ * happened to match a browser holding thirty seconds and would refuse three
7
+ * quarters of the requests of one holding the whole cushion. The width is the
8
+ * encoder's own look-ahead now, which is the same figure the browser sizes its
9
+ * buffer from. Roadmap item 4, step 2.
10
+ */
11
+
12
+ import test from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import { mkdtemp, rm } from "node:fs/promises";
15
+ import os from "node:os";
16
+ import path from "node:path";
17
+ import { HlsSessionManager } from "../services/hls-session-manager.js";
18
+ import { fmp4Format } from "../services/segment-formats/fmp4.js";
19
+
20
+ const SESSION_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
21
+ const SEGMENT_SECONDS = 4;
22
+
23
+ /**
24
+ * @returns {Promise<{ manager: HlsSessionManager, dirPath: string }>}
25
+ */
26
+ async function managerWithSession() {
27
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "held-request-"));
28
+ const manager = new HlsSessionManager({
29
+ enabled: true,
30
+ ffmpegBin: "ffmpeg",
31
+ localBindHost: "127.0.0.1",
32
+ localPort: 9090
33
+ });
34
+ manager.sessionsById.set(SESSION_ID, {
35
+ id: SESSION_ID,
36
+ dirPath,
37
+ state: "ready",
38
+ segmentFormat: fmp4Format,
39
+ segmentBoundaries: Array.from({ length: 201 }, (_, index) => index * SEGMENT_SECONDS),
40
+ segmentCount: 200,
41
+ useSyntheticPlaylist: true,
42
+ // The viewer is at segment #25.
43
+ viewerPositionSeconds: 100
44
+ });
45
+ return { manager, dirPath };
46
+ }
47
+
48
+ /**
49
+ * @param {number} index
50
+ * @returns {string}
51
+ */
52
+ function segment(index) {
53
+ return `segment-${String(index).padStart(5, "0")}.mp4`;
54
+ }
55
+
56
+ test("the width is the encoder's own look-ahead, in segments", async (t) => {
57
+ const { manager, dirPath } = await managerWithSession();
58
+ t.after(async () => {
59
+ await rm(dirPath, { recursive: true, force: true });
60
+ });
61
+
62
+ const width = Math.ceil(manager.lookaheadSeconds / manager.segmentDurationSec);
63
+ assert.equal(width, 30, "120 s of look-ahead over 4 s segments");
64
+ assert.equal(manager.requestStillWanted(SESSION_ID, segment(25 + width)), true, "the far edge");
65
+ assert.equal(
66
+ manager.requestStillWanted(SESSION_ID, segment(25 + width + 1)),
67
+ false,
68
+ "past everything the encoder is allowed to have produced"
69
+ );
70
+ });
71
+
72
+ test("a request the old eight-segment width would have refused is kept", async (t) => {
73
+ const { manager, dirPath } = await managerWithSession();
74
+ t.after(async () => {
75
+ await rm(dirPath, { recursive: true, force: true });
76
+ });
77
+
78
+ // #34 is nine segments ahead of the viewer — inside a 120 s cushion and
79
+ // outside the eight the width used to be. This is the request a browser
80
+ // holding the whole cushion makes constantly.
81
+ assert.equal(manager.requestStillWanted(SESSION_ID, segment(34)), true);
82
+ });
83
+
84
+ test("a segment behind the viewer is still released", async (t) => {
85
+ const { manager, dirPath } = await managerWithSession();
86
+ t.after(async () => {
87
+ await rm(dirPath, { recursive: true, force: true });
88
+ });
89
+
90
+ assert.equal(manager.requestStillWanted(SESSION_ID, segment(24)), false);
91
+ });
92
+
93
+ test("a seek by one viewer does not release the request held for another", async (t) => {
94
+ const { manager, dirPath } = await managerWithSession();
95
+ t.after(async () => {
96
+ await rm(dirPath, { recursive: true, force: true });
97
+ });
98
+ const session = manager.sessionsById.get(SESSION_ID);
99
+
100
+ // Both are watching the same copied picture, so both are this one session.
101
+ // One is at segment #25, the other far ahead at #150 — inside the fixture's
102
+ // own 200-segment timeline, since a position past the end of the grid is
103
+ // clamped to it and would prove nothing about the width.
104
+ manager.requestSeek(SESSION_ID, 100, "behind");
105
+ manager.requestSeek(SESSION_ID, 600, "ahead");
106
+
107
+ // The shared field now holds the leader's position, which is what the
108
+ // encoder is steered by and what every earlier release judged BOTH of them
109
+ // against.
110
+ assert.equal(session.viewerPositionSeconds, 600);
111
+
112
+ assert.equal(
113
+ manager.requestStillWanted(SESSION_ID, segment(26), "behind"),
114
+ true,
115
+ "the segment the viewer behind is waiting for is still theirs to wait for"
116
+ );
117
+ assert.equal(
118
+ manager.requestStillWanted(SESSION_ID, segment(26), "ahead"),
119
+ false,
120
+ "and for the one in front it is a place they have left"
121
+ );
122
+ });
123
+
124
+ test("a viewer's own head moves with their seek", async (t) => {
125
+ const { manager, dirPath } = await managerWithSession();
126
+ t.after(async () => {
127
+ await rm(dirPath, { recursive: true, force: true });
128
+ });
129
+
130
+ // Their last request was at #25; they jump to 600 s, which is #150. The
131
+ // segment at the target must be wanted — refusing it there is the freeze of
132
+ // 2026-08-18.
133
+ manager.requestSeek(SESSION_ID, 600, "viewer");
134
+ assert.equal(manager.requestStillWanted(SESSION_ID, segment(150), "viewer"), true);
135
+ assert.equal(manager.requestStillWanted(SESSION_ID, segment(25), "viewer"), false);
136
+ });
137
+
138
+ test("a viewer nobody can name is judged against the one shared position", async (t) => {
139
+ const { manager, dirPath } = await managerWithSession();
140
+ t.after(async () => {
141
+ await rm(dirPath, { recursive: true, force: true });
142
+ });
143
+
144
+ // A plain HTTP transport builds its own URLs and carries no id. The old
145
+ // behaviour is what remains, which for a single viewer is the same thing.
146
+ assert.equal(manager.requestStillWanted(SESSION_ID, segment(26), ""), true);
147
+ assert.equal(manager.requestStillWanted(SESSION_ID, segment(24), ""), false);
148
+ });
@@ -59,6 +59,7 @@ function fakeSession({ id, encodeHeight, dirPath, transcodeVideo = true }) {
59
59
  seekSettleTimer: null,
60
60
  seekTarget: null,
61
61
  waitEpoch: 0,
62
+ netReports: new Map(),
62
63
  usesExplicitCuts: false,
63
64
  useSyntheticPlaylist: true,
64
65
  playlistText: "#EXTM3U\n",
@@ -660,7 +661,12 @@ test("a separately published audio track starts where the picture is, from the r
660
661
  // picture — so the viewer is at 100 s, and that, less a segment of margin,
661
662
  // is where the track has to begin.
662
663
  base.viewerPositionSeconds = 140;
663
- base.netReport = { linkMbps: 20, bufferedAheadSec: 40, at: Date.now() };
664
+ base.netReports.set("viewer", {
665
+ linkMbps: 20,
666
+ bufferedAheadSec: 40,
667
+ positionSeconds: null,
668
+ at: Date.now()
669
+ });
664
670
  manager.getCachedAudioTracks = () => [
665
671
  { index: 0, language: "rus", title: "", isDefault: true },
666
672
  { index: 1, language: "eng", title: "", isDefault: false }
@@ -683,6 +689,87 @@ test("a separately published audio track starts where the picture is, from the r
683
689
  );
684
690
  });
685
691
 
692
+ test("with two viewers the audio track starts at the EARLIEST picture, not the read head", async (t) => {
693
+ const { manager, base, dirPath } = await managerWithBase();
694
+ t.after(async () => {
695
+ await manager.disposeAll();
696
+ await rm(dirPath, { recursive: true, force: true });
697
+ });
698
+ base.audioSeparate = true;
699
+ // A copied picture is one session shared by both of them. The read head is
700
+ // the furthest request of EITHER, so it belongs to the viewer in front.
701
+ base.viewerPositionSeconds = 140;
702
+ base.netReports.set("ahead", {
703
+ linkMbps: 20,
704
+ bufferedAheadSec: 40,
705
+ positionSeconds: 100,
706
+ at: Date.now()
707
+ });
708
+ base.netReports.set("behind", {
709
+ linkMbps: 20,
710
+ bufferedAheadSec: 8,
711
+ positionSeconds: 40,
712
+ at: Date.now()
713
+ });
714
+ manager.getCachedAudioTracks = () => [
715
+ { index: 0, language: "rus", title: "", isDefault: true },
716
+ { index: 1, language: "eng", title: "", isDefault: false }
717
+ ];
718
+ const created = [];
719
+ manager.createOrGetSession = async (params) => {
720
+ created.push(params);
721
+ const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath });
722
+ rendition.audioOnly = true;
723
+ return { sessionId: VARIANT_ID, session: rendition };
724
+ };
725
+
726
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4");
727
+
728
+ assert.equal(
729
+ created[0].startPositionSeconds,
730
+ 36,
731
+ "the viewer at 40 s, less one segment of margin — a run starting at the leader " +
732
+ "has nothing to give the one behind them"
733
+ );
734
+ });
735
+
736
+ test("a position past the read head is clamped rather than acted on", async (t) => {
737
+ const { manager, base, dirPath } = await managerWithBase();
738
+ t.after(async () => {
739
+ await manager.disposeAll();
740
+ await rm(dirPath, { recursive: true, force: true });
741
+ });
742
+ base.audioSeparate = true;
743
+ base.viewerPositionSeconds = 140;
744
+ // Reports and requests race; a position claiming to be past everything that
745
+ // has been asked for would start the run where no request can reach it.
746
+ base.netReports.set("viewer", {
747
+ linkMbps: 20,
748
+ bufferedAheadSec: 40,
749
+ positionSeconds: 900,
750
+ at: Date.now()
751
+ });
752
+ manager.getCachedAudioTracks = () => [
753
+ { index: 0, language: "rus", title: "", isDefault: true },
754
+ { index: 1, language: "eng", title: "", isDefault: false }
755
+ ];
756
+ const created = [];
757
+ manager.createOrGetSession = async (params) => {
758
+ created.push(params);
759
+ const rendition = fakeSession({ id: VARIANT_ID, encodeHeight: 0, dirPath });
760
+ rendition.audioOnly = true;
761
+ return { sessionId: VARIANT_ID, session: rendition };
762
+ };
763
+
764
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00010.mp4");
765
+
766
+ assert.equal(
767
+ created[0].startPositionSeconds,
768
+ 136,
769
+ "clamped to the read head, less one segment of margin"
770
+ );
771
+ });
772
+
686
773
  test("a stale buffer report is not used to place an audio track", async (t) => {
687
774
  const { manager, base, dirPath } = await managerWithBase();
688
775
  t.after(async () => {
@@ -691,9 +778,14 @@ test("a stale buffer report is not used to place an audio track", async (t) => {
691
778
  });
692
779
  base.audioSeparate = true;
693
780
  base.viewerPositionSeconds = 300;
694
- // Sent a minute ago: the viewer may have seeked anywhere since, so it says
695
- // nothing about where they are now.
696
- base.netReport = { linkMbps: 20, bufferedAheadSec: 5, at: Date.now() - 60_000 };
781
+ // Sent a minute ago: the viewer may have seeked anywhere since, so neither
782
+ // the buffer nor the position in it says where they are now.
783
+ base.netReports.set("viewer", {
784
+ linkMbps: 20,
785
+ bufferedAheadSec: 5,
786
+ positionSeconds: 250,
787
+ at: Date.now() - 60_000
788
+ });
697
789
  manager.getCachedAudioTracks = () => [
698
790
  { index: 0, language: "rus", title: "", isDefault: true },
699
791
  { index: 1, language: "eng", title: "", isDefault: false }
@@ -104,3 +104,79 @@ test("a playlist belongs to no position and is never stale", async () => {
104
104
 
105
105
  await rm(dirPath, { recursive: true, force: true });
106
106
  });
107
+
108
+ test("a request as deep as the cushion the browser is told to hold is still wanted", async () => {
109
+ const { manager, dirPath } = await managerAfterSeek();
110
+
111
+ // The browser sizes its forward buffer from the proxy's own look-ahead, so
112
+ // the deepest request it can make is one for the segment at the far edge of
113
+ // that cushion. Refusing it would be refusing the very depth this proxy
114
+ // asked for: at the old width — eight segments ahead of the viewer — three
115
+ // quarters of a full cushion's requests were stale by definition.
116
+ const edge = Math.floor((SEEK_TO_SECONDS + manager.lookaheadSeconds) / SEGMENT_SECONDS);
117
+
118
+ assert.ok(edge - SEGMENT_AT_SEEK > 8, "the case only exists past the old eight-segment width");
119
+ assert.equal(
120
+ manager.requestStillWanted(SESSION_ID, `segment-${String(edge).padStart(5, "0")}.mp4`),
121
+ true,
122
+ "the far edge of the cushion the proxy itself keeps produced"
123
+ );
124
+
125
+ await rm(dirPath, { recursive: true, force: true });
126
+ });
127
+
128
+ test("the viewer who made the request is the one it is judged against", async () => {
129
+ const { manager, dirPath } = await managerAfterSeek();
130
+ const session = manager.sessionsById.get(SESSION_ID);
131
+ session.consumerHeads = new Map();
132
+ // Two people watching one copied picture. The shared position belongs to the
133
+ // one in front — it is the furthest segment anybody asked for — and the one
134
+ // behind is a hundred segments back, waiting for a segment there.
135
+ const behind = SEGMENT_AT_SEEK - 100;
136
+ session.consumerHeads.set("behind", {
137
+ segment: behind,
138
+ seconds: behind * SEGMENT_SECONDS,
139
+ at: Date.now()
140
+ });
141
+
142
+ assert.equal(
143
+ manager.requestStillWanted(SESSION_ID, `segment-${String(behind).padStart(5, "0")}.mp4`, "behind"),
144
+ true,
145
+ "held for the viewer who is there, whatever the viewer in front is doing"
146
+ );
147
+ assert.equal(
148
+ manager.requestStillWanted(SESSION_ID, `segment-${String(behind).padStart(5, "0")}.mp4`),
149
+ false,
150
+ "unnamed, it can only be judged against the shared position — which is the leader's"
151
+ );
152
+
153
+ await rm(dirPath, { recursive: true, force: true });
154
+ });
155
+
156
+ test("a seek moves the seeking viewer's own head, and nobody else's", async () => {
157
+ const { manager, dirPath } = await managerAfterSeek();
158
+ const session = manager.sessionsById.get(SESSION_ID);
159
+ session.consumerHeads = new Map();
160
+ const staying = SEGMENT_AT_SEEK - 40;
161
+ session.consumerHeads.set("staying", {
162
+ segment: staying,
163
+ seconds: staying * SEGMENT_SECONDS,
164
+ at: Date.now()
165
+ });
166
+
167
+ const jumpTo = 120;
168
+ manager.requestSeek(SESSION_ID, jumpTo, "jumping");
169
+
170
+ assert.equal(
171
+ manager.requestStillWanted(SESSION_ID, `segment-${String(Math.floor(jumpTo / SEGMENT_SECONDS)).padStart(5, "0")}.mp4`, "jumping"),
172
+ true,
173
+ "the segment at the seek target — the request that raced the epoch in 2026-08-18"
174
+ );
175
+ assert.equal(
176
+ manager.requestStillWanted(SESSION_ID, `segment-${String(staying).padStart(5, "0")}.mp4`, "staying"),
177
+ true,
178
+ "somebody else's seek does not move where this viewer is"
179
+ );
180
+
181
+ await rm(dirPath, { recursive: true, force: true });
182
+ });