@torrent-tv/proxy 2.67.0 → 2.69.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.
- package/CHANGELOG.md +19 -0
- package/corpus.tmp.json +1 -0
- package/package.json +1 -1
- package/routes/api/subtitles/get.js +8 -3
- package/services/controllers/SubtitleController.js +24 -4
- package/services/data-channel-handler.js +5 -3
- package/services/language-detect.js +161 -6
- package/services/torrent-worker/background-fill.js +31 -9
- package/services/torrent-worker/piece-reader.js +30 -0
- package/services/torrent-worker/subtitle-cues.js +13 -1
- package/test/background-fill.test.js +34 -0
- package/test/subtitle-language.test.js +241 -0
- package/test/worker-channel.test.js +9 -1
package/package.json
CHANGED
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
import { spawn } from "node:child_process";
|
|
28
|
-
import {
|
|
28
|
+
import { detectLanguageFromVtt } from "../../../services/language-detect.js";
|
|
29
29
|
import { SubtitleController } from "../../../services/controllers/SubtitleController.js";
|
|
30
30
|
import { logger } from "../../../utils/logger.js";
|
|
31
31
|
|
|
@@ -137,7 +137,7 @@ export async function handleApiSubtitlesGet(req, reply, { sourceRegistry, torren
|
|
|
137
137
|
* Extractions by `sourceKey:fileIndex:trackIndex`, so the scan happens once per
|
|
138
138
|
* track however many times it is asked for.
|
|
139
139
|
*
|
|
140
|
-
* @type {Map<string, { state: "running" | "done" | "failed", body?: Buffer, language?: string, error?: string }>}
|
|
140
|
+
* @type {Map<string, { state: "running" | "done" | "failed", body?: Buffer, language?: { code: string, name: string } | null, error?: string }>}
|
|
141
141
|
*/
|
|
142
142
|
const extractions = new Map();
|
|
143
143
|
|
|
@@ -190,7 +190,12 @@ function startExtraction({ key, ffmpegBin, localBaseUrl, sourceKey, fileIndex, t
|
|
|
190
190
|
logger.warn(`subtitles ${key}: nothing produced after ${seconds}s`);
|
|
191
191
|
return;
|
|
192
192
|
}
|
|
193
|
-
|
|
193
|
+
// The whole document, decoded as one string, and only its cue text.
|
|
194
|
+
// Detecting on the first 4096 BYTES was wrong twice over: a byte cut lands
|
|
195
|
+
// mid-character on any non-Latin track, and most of those bytes are
|
|
196
|
+
// timestamps rather than words. This runs once per track in the background,
|
|
197
|
+
// so reading all of it costs nothing anybody waits for.
|
|
198
|
+
extractions.set(key, { state: "done", body, language: detectLanguageFromVtt(body.toString("utf8")) });
|
|
194
199
|
logger.info(`subtitles ${key}: ${body.length} bytes in ${seconds}s`);
|
|
195
200
|
};
|
|
196
201
|
ffmpeg.once("close", settle);
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import { subtitleOrchestrator } from "../orchestrators/SubtitleOrchestrator.js";
|
|
11
11
|
import { convertSubtitleToVtt, decodeSubtitleBytes } from "../subtitle-convert.js";
|
|
12
|
-
import { detectLanguage } from "../language-detect.js";
|
|
12
|
+
import { detectLanguage, detectLanguageFromVtt } from "../language-detect.js";
|
|
13
13
|
import { finalizeCues } from "../torrent-worker/subtitle-cues.js";
|
|
14
14
|
|
|
15
15
|
const EXTERNAL_MAX_BYTES = 8 * 1024 * 1024;
|
|
@@ -75,7 +75,12 @@ export class SubtitleController {
|
|
|
75
75
|
const text = decodeSubtitleBytes(bytes);
|
|
76
76
|
const vtt = convertSubtitleToVtt(text, ext);
|
|
77
77
|
if (!vtt) return { error: `Unsupported subtitle format: ${ext}`, status: 422 };
|
|
78
|
-
|
|
78
|
+
// The language is read from the CONVERTED document, not from the file.
|
|
79
|
+
// The conversion has already dropped everything that is not the words —
|
|
80
|
+
// and on an ASS file that is half of it, in Latin letters, which is what
|
|
81
|
+
// made a Russian track answer `en` (field 2026-09-01, and the whole of
|
|
82
|
+
// `research/subtitle-language-ass-markup-2026-09-01.md`).
|
|
83
|
+
return { vtt, language: detectLanguageFromVtt(vtt), headers: {} };
|
|
79
84
|
} catch (e) {
|
|
80
85
|
return { error: `Could not read subtitle file: ${e?.message ?? e}`, status: 502 };
|
|
81
86
|
} finally {
|
|
@@ -105,8 +110,23 @@ export class SubtitleController {
|
|
|
105
110
|
const cursor = held.cues.reduce((h, c) => Math.max(h, Number(c.seq) || 0), 0);
|
|
106
111
|
const fresh = Number.isInteger(since) ? held.cues.filter((c) => (Number(c.seq) || 0) > since)
|
|
107
112
|
: Number.isFinite(after) ? held.cues.filter((c) => c.startSeconds > after) : held.cues;
|
|
108
|
-
const
|
|
109
|
-
const
|
|
113
|
+
const codecId = held.track?.codecId ?? track?.codecId ?? "";
|
|
114
|
+
const vtt = cuesToVtt(fresh, codecId);
|
|
115
|
+
// Two things this reads, and each of them was wrong before 2.68.1.
|
|
116
|
+
//
|
|
117
|
+
// It reads the cues through `finalizeCues`, which is what turns an ASS
|
|
118
|
+
// dialogue row into the words: a raw cue carries the nine
|
|
119
|
+
// comma-separated fields of the row and its `{\…}` override groups, and
|
|
120
|
+
// those are Latin on a Russian track. Detecting on the raw text is the
|
|
121
|
+
// same fault as detecting on a whole `.ass` file, one layer down.
|
|
122
|
+
//
|
|
123
|
+
// And it reads EVERY cue held so far, not the `fresh` subset that is
|
|
124
|
+
// being sent. A re-subscription after a reconnect asks only for what this
|
|
125
|
+
// page missed, which can be three lines, and three lines are not a sample
|
|
126
|
+
// of a language.
|
|
127
|
+
const language = detectLanguage(
|
|
128
|
+
finalizeCues(held.cues, codecId).map((cue) => cue.text).join("\n")
|
|
129
|
+
);
|
|
110
130
|
return {
|
|
111
131
|
vtt,
|
|
112
132
|
language,
|
|
@@ -590,10 +590,12 @@ export function createDataChannelHandler({
|
|
|
590
590
|
* are tiny (kilobytes at most for a whole track), so this is one message,
|
|
591
591
|
* not a stream.
|
|
592
592
|
*
|
|
593
|
-
* @param {{ sourceKey: string, fileIndex: number, trackIndex: number, cues: object[],
|
|
593
|
+
* @param {{ sourceKey: string, fileIndex: number, trackIndex: number, cues: object[],
|
|
594
|
+
* language: string, detectedLanguage: { code: string, name: string } | null,
|
|
595
|
+
* cursor: number }} event
|
|
594
596
|
* @returns {void}
|
|
595
597
|
*/
|
|
596
|
-
function publishSubtitleCues({ sourceKey, fileIndex, trackIndex, cues, language, cursor }) {
|
|
598
|
+
function publishSubtitleCues({ sourceKey, fileIndex, trackIndex, cues, language, detectedLanguage, cursor }) {
|
|
597
599
|
const set = subtitleSubscribers.get(`${sourceKey}:${fileIndex}`);
|
|
598
600
|
if (!set || set.size === 0) {
|
|
599
601
|
log(
|
|
@@ -602,7 +604,7 @@ export function createDataChannelHandler({
|
|
|
602
604
|
);
|
|
603
605
|
return;
|
|
604
606
|
}
|
|
605
|
-
const message = { type: "subtitle-cues", fileIndex, trackIndex, cues, language, cursor };
|
|
607
|
+
const message = { type: "subtitle-cues", fileIndex, trackIndex, cues, language, detectedLanguage, cursor };
|
|
606
608
|
const total = set.size;
|
|
607
609
|
let sent = 0;
|
|
608
610
|
for (const channel of set) {
|
|
@@ -54,20 +54,175 @@ const LANG_3_TO_1 = {
|
|
|
54
54
|
|
|
55
55
|
const ONLY = Object.keys(LANG_3_TO_1);
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* The least text, in characters, that supports an answer of each language.
|
|
59
|
+
*
|
|
60
|
+
* MEASURED, not chosen — `research/franc-boundary-2026-09-02.md`. Method:
|
|
61
|
+
* Wikipedia extracts per language (deliberately NOT the UDHR, which is what
|
|
62
|
+
* franc's own profiles are built from and would read optimistically), 120
|
|
63
|
+
* windows cut at random from them at each length of a ladder from 40 to 1300
|
|
64
|
+
* characters, and the figure recorded is the shortest length from which franc
|
|
65
|
+
* answered correctly in at least 95 % of trials AND kept doing so at every
|
|
66
|
+
* longer length measured.
|
|
67
|
+
*
|
|
68
|
+
* Why it is per language rather than one number: the answer is not equally hard
|
|
69
|
+
* to reach, and the spread is fivefold. Greek and Korean settle at 40
|
|
70
|
+
* characters because their script settles it; English needs 130; Russian and
|
|
71
|
+
* Czech need 650, because each competes with neighbours in this very list for
|
|
72
|
+
* the same trigrams — Russian with Bulgarian, Serbian and Ukrainian, Czech with
|
|
73
|
+
* Slovak.
|
|
74
|
+
*
|
|
75
|
+
* Two languages are deliberately ABSENT. Swedish and Chinese did not settle
|
|
76
|
+
* anywhere in the ladder on the corpora collected, so no figure for them is
|
|
77
|
+
* measured and none is invented; they take the fallback below.
|
|
78
|
+
*
|
|
79
|
+
* A language with no entry gets the WORST measured figure. That is the
|
|
80
|
+
* conservative reading and it is still a measurement rather than a guess: it
|
|
81
|
+
* says "no better than the hardest language we have measured".
|
|
82
|
+
*
|
|
83
|
+
* @type {Record<string, number>}
|
|
84
|
+
*/
|
|
85
|
+
const LEAST_TEXT = {
|
|
86
|
+
bel: 100,
|
|
87
|
+
bul: 80,
|
|
88
|
+
ces: 650,
|
|
89
|
+
deu: 200,
|
|
90
|
+
ell: 40,
|
|
91
|
+
eng: 130,
|
|
92
|
+
fra: 80,
|
|
93
|
+
heb: 60,
|
|
94
|
+
ita: 160,
|
|
95
|
+
kor: 40,
|
|
96
|
+
nld: 130,
|
|
97
|
+
pol: 200,
|
|
98
|
+
por: 200,
|
|
99
|
+
rus: 650,
|
|
100
|
+
spa: 100,
|
|
101
|
+
srp: 100,
|
|
102
|
+
tur: 160,
|
|
103
|
+
ukr: 250
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** The worst measured figure, used for any language not in the table. */
|
|
107
|
+
const LEAST_TEXT_WORST = Math.max(...Object.values(LEAST_TEXT), 0);
|
|
108
|
+
|
|
109
|
+
/** franc's own floor: below this it is not asked at all. */
|
|
110
|
+
const FRANC_FLOOR = 15;
|
|
111
|
+
|
|
112
|
+
/** One space between words, nothing else — the form every figure above is in. */
|
|
113
|
+
function normalise(text) {
|
|
114
|
+
return typeof text === "string" ? text.replace(/\s+/g, " ").trim() : "";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* franc's answer for this text, or null when it has none.
|
|
119
|
+
*
|
|
120
|
+
* @param {string} text
|
|
121
|
+
* @returns {string | null} ISO 639-3.
|
|
122
|
+
*/
|
|
123
|
+
function ask(text) {
|
|
124
|
+
if (text.length < FRANC_FLOOR) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
const iso3 = franc(text, { only: ONLY, minLength: FRANC_FLOOR });
|
|
128
|
+
return iso3 === "und" ? null : iso3;
|
|
129
|
+
}
|
|
130
|
+
|
|
57
131
|
/**
|
|
58
132
|
* Best-effort detect the language of subtitle text.
|
|
59
133
|
*
|
|
60
|
-
*
|
|
134
|
+
* **Give this the words a viewer reads and nothing else.** franc scores letter
|
|
135
|
+
* trigrams over the whole string it is handed, so anything around the words
|
|
136
|
+
* competes with them. An ASS file is markup by half: measured 2026-09-01 on
|
|
137
|
+
* `[HorribleSubs] Drifters - 03 [1080p].ass`, 5040 Latin characters of Aegisub
|
|
138
|
+
* headers, style and font names, `Format:`/`Dialogue:` field prefixes and
|
|
139
|
+
* `{\…}` override groups against 5983 Cyrillic characters of dialogue —
|
|
140
|
+
* `franc(the file) = eng`, `franc(the dialogue) = rus`. The proxy had already
|
|
141
|
+
* built the markup-free text and detected on the file anyway, so a Russian
|
|
142
|
+
* track was offered to the viewer as English.
|
|
143
|
+
*
|
|
144
|
+
* `detectLanguageFromVtt` below is the safe entry point for a whole document;
|
|
145
|
+
* this one is for text that is already only text.
|
|
146
|
+
*
|
|
147
|
+
* @param {string} text - Subtitle text with no markup left in it.
|
|
61
148
|
* @returns {{ code: string, name: string } | null} Detected language, or null when uncertain.
|
|
62
149
|
*/
|
|
63
150
|
export function detectLanguage(text) {
|
|
64
|
-
|
|
151
|
+
const words = normalise(text);
|
|
152
|
+
if (words.length < FRANC_FLOOR) {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
const candidate = ask(words);
|
|
156
|
+
if (candidate === null) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
// Enough text to support THIS answer. The figure is the language's own,
|
|
160
|
+
// because the languages are not alike: Russian shares its trigrams with
|
|
161
|
+
// Bulgarian, Serbian and Ukrainian and needs several times what English does.
|
|
162
|
+
if (words.length < (LEAST_TEXT[candidate] ?? LEAST_TEXT_WORST)) {
|
|
65
163
|
return null;
|
|
66
164
|
}
|
|
67
|
-
//
|
|
68
|
-
|
|
69
|
-
|
|
165
|
+
// And an answer that does not survive losing half the text was an accident of
|
|
166
|
+
// where the text happened to stop, not a reading of it. Free — franc costs
|
|
167
|
+
// about 2 ms whatever the size, measured — and it needs no figure of its own,
|
|
168
|
+
// because the test is taken on the text in hand.
|
|
169
|
+
const middle = Math.floor(words.length / 2);
|
|
170
|
+
if (ask(words.slice(0, middle)) !== candidate || ask(words.slice(middle)) !== candidate) {
|
|
70
171
|
return null;
|
|
71
172
|
}
|
|
72
|
-
return LANG_3_TO_1[
|
|
173
|
+
return LANG_3_TO_1[candidate] ?? null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The words of a WebVTT document — what a viewer reads, with everything the
|
|
178
|
+
* format puts around them removed.
|
|
179
|
+
*
|
|
180
|
+
* A WebVTT document is a series of blocks separated by blank lines. A block
|
|
181
|
+
* that holds a timing line (`00:00:12.060 --> 00:00:13.270`) is a cue, and the
|
|
182
|
+
* lines after that timing line are its text; the lines before it are the cue's
|
|
183
|
+
* optional identifier. A block with NO timing line is the `WEBVTT` header or a
|
|
184
|
+
* `NOTE` / `STYLE` / `REGION` block, and none of those is anybody's language.
|
|
185
|
+
* That one rule removes the identifiers, the timings and the headers together.
|
|
186
|
+
*
|
|
187
|
+
* What is left can still carry WebVTT's own inline markup — `<v Speaker>`,
|
|
188
|
+
* `<i>`, `<c.yellow>` — and character references. Both are dropped: a speaker
|
|
189
|
+
* name and a class name are written in whatever language the releaser's tooling
|
|
190
|
+
* used, which is not the language of the film.
|
|
191
|
+
*
|
|
192
|
+
* @param {string} vtt - A WebVTT document.
|
|
193
|
+
* @returns {string} The cue text, blocks joined by newlines.
|
|
194
|
+
*/
|
|
195
|
+
export function cueTextOfVtt(vtt) {
|
|
196
|
+
if (typeof vtt !== "string") {
|
|
197
|
+
return "";
|
|
198
|
+
}
|
|
199
|
+
const blocks = vtt.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split(/\n{2,}/);
|
|
200
|
+
const spoken = [];
|
|
201
|
+
for (const block of blocks) {
|
|
202
|
+
const lines = block.split("\n");
|
|
203
|
+
const timingAt = lines.findIndex((line) => line.includes("-->"));
|
|
204
|
+
if (timingAt < 0) {
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
for (const line of lines.slice(timingAt + 1)) {
|
|
208
|
+
spoken.push(line);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return spoken
|
|
212
|
+
.join("\n")
|
|
213
|
+
.replace(/<[^>]*>/g, "")
|
|
214
|
+
// A character reference stands for one character and never for a word, so a
|
|
215
|
+
// space in its place keeps the neighbouring words apart and adds nothing.
|
|
216
|
+
.replace(/&[a-z]+;|&#\d+;|&#x[0-9a-f]+;/gi, " ")
|
|
217
|
+
.trim();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Detect the language of a WebVTT document, reading only its cue text.
|
|
222
|
+
*
|
|
223
|
+
* @param {string} vtt - A WebVTT document.
|
|
224
|
+
* @returns {{ code: string, name: string } | null} Detected language, or null when uncertain.
|
|
225
|
+
*/
|
|
226
|
+
export function detectLanguageFromVtt(vtt) {
|
|
227
|
+
return detectLanguage(cueTextOfVtt(vtt));
|
|
73
228
|
}
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
*/
|
|
29
29
|
|
|
30
30
|
import { logger } from "../../utils/logger.js";
|
|
31
|
-
import { readersAreBlockedOn } from "./piece-reader.js";
|
|
31
|
+
import { readersAreBlockedOn, stallsSeenOn } from "./piece-reader.js";
|
|
32
32
|
|
|
33
33
|
/**
|
|
34
34
|
* How long to stand aside after finding the viewer's own reading blocked.
|
|
@@ -101,7 +101,7 @@ function readRange(file, start, end) {
|
|
|
101
101
|
* @param {object} torrent
|
|
102
102
|
* @param {number} fileIndex
|
|
103
103
|
* @param {string} sourceKey
|
|
104
|
-
* @param {{ chunkBytes?: number, isBlocked?: (infoHash: string) => boolean }} [options]
|
|
104
|
+
* @param {{ chunkBytes?: number, isBlocked?: (infoHash: string) => boolean, stallsSeen?: (infoHash: string) => number }} [options]
|
|
105
105
|
* `isBlocked` answers "is the viewer's own reading starving right now"; it is
|
|
106
106
|
* the tier boundary, and it is a parameter so it can be exercised without a
|
|
107
107
|
* swarm.
|
|
@@ -123,7 +123,8 @@ export function fillFileInBackground(torrent, fileIndex, sourceKey, options = {}
|
|
|
123
123
|
? options.chunkBytes
|
|
124
124
|
: (Number(torrent?.pieceLength) || 4 * 1024 * 1024);
|
|
125
125
|
const isBlocked = typeof options.isBlocked === "function" ? options.isBlocked : readersAreBlockedOn;
|
|
126
|
-
const
|
|
126
|
+
const stallsSeen = typeof options.stallsSeen === "function" ? options.stallsSeen : stallsSeenOn;
|
|
127
|
+
const work = fill(torrent, file, fileIndex, chunkBytes, isBlocked, stallsSeen).finally(() => {
|
|
127
128
|
running.delete(key);
|
|
128
129
|
});
|
|
129
130
|
running.set(key, work);
|
|
@@ -136,25 +137,41 @@ export function fillFileInBackground(torrent, fileIndex, sourceKey, options = {}
|
|
|
136
137
|
* @param {number} fileIndex
|
|
137
138
|
* @param {number} chunkBytes
|
|
138
139
|
* @param {(infoHash: string) => boolean} isBlocked
|
|
140
|
+
* @param {(infoHash: string) => number} stallsSeen
|
|
139
141
|
* @returns {Promise<void>}
|
|
140
142
|
*/
|
|
141
|
-
async function fill(torrent, file, fileIndex, chunkBytes, isBlocked) {
|
|
143
|
+
async function fill(torrent, file, fileIndex, chunkBytes, isBlocked, stallsSeen) {
|
|
142
144
|
const startedAt = Date.now();
|
|
143
145
|
const infoHash = String(torrent?.infoHash ?? "");
|
|
144
146
|
let read = 0;
|
|
145
147
|
let stoodAsideMs = 0;
|
|
148
|
+
// The stall count this fill last saw. A chunk is fetched only when it has not
|
|
149
|
+
// moved since the previous one.
|
|
150
|
+
let quietSince = stallsSeen(infoHash);
|
|
146
151
|
logger.info(
|
|
147
152
|
`background-fill: "${String(file.name).slice(0, 40)}" (${(file.length / 1e6).toFixed(1)}MB) will be ` +
|
|
148
153
|
"fetched whole while the viewer's own reading leaves room"
|
|
149
154
|
);
|
|
150
155
|
for (let start = 0; start < file.length; start += chunkBytes) {
|
|
151
|
-
// Stand aside
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
//
|
|
155
|
-
|
|
156
|
+
// Stand aside while anything the viewer is watching is waiting on the
|
|
157
|
+
// swarm — AND for as long after it as it takes for a quiet stretch to
|
|
158
|
+
// pass. Pausing only DURING a stall is not enough: on a swarm delivering
|
|
159
|
+
// exactly what the film needs, this still takes bandwidth between stalls,
|
|
160
|
+
// and the stalls themselves are the proof there was none to spare. Field
|
|
161
|
+
// 2026-08-31, the case that forced this: 200-600 KB/s delivered against
|
|
162
|
+
// the 399 KB/s the film eats, one piece waited 101 s, and the picture
|
|
163
|
+
// stood still 145.6 s.
|
|
164
|
+
//
|
|
165
|
+
// "A quiet stretch" is measured, not chosen: the stall counter must not
|
|
166
|
+
// have moved while the previous chunk was being fetched. On a starving
|
|
167
|
+
// swarm it moves constantly and this stops altogether, which is the right
|
|
168
|
+
// answer — there is no spare room to use.
|
|
169
|
+
while (isBlocked(infoHash) || stallsSeen(infoHash) !== quietSince) {
|
|
156
170
|
stoodAsideMs += STAND_ASIDE_MS;
|
|
157
171
|
await pause(STAND_ASIDE_MS);
|
|
172
|
+
// Re-baselined after the pause, so a stretch that passes without a new
|
|
173
|
+
// stall lets the fill go on. Without this it could never resume.
|
|
174
|
+
quietSince = stallsSeen(infoHash);
|
|
158
175
|
}
|
|
159
176
|
// The torrent may have been destroyed under us — a viewer who left, the
|
|
160
177
|
// disk sweep, a restart. Reading a destroyed file throws, and there is
|
|
@@ -162,6 +179,11 @@ async function fill(torrent, file, fileIndex, chunkBytes, isBlocked) {
|
|
|
162
179
|
if (!torrent?.files?.[fileIndex]) {
|
|
163
180
|
return;
|
|
164
181
|
}
|
|
182
|
+
// Taken BEFORE the read, and deliberately not refreshed after it: a stall
|
|
183
|
+
// that happens while this chunk is in flight must still be visible to the
|
|
184
|
+
// next iteration. Refreshing afterwards erased exactly that evidence, which
|
|
185
|
+
// is the defect a test caught here.
|
|
186
|
+
quietSince = stallsSeen(infoHash);
|
|
165
187
|
const bytes = await readRange(file, start, Math.min(start + chunkBytes, file.length) - 1);
|
|
166
188
|
if (bytes === 0) {
|
|
167
189
|
logger.info(
|
|
@@ -617,6 +617,14 @@ function describeSteering(key) {
|
|
|
617
617
|
*/
|
|
618
618
|
const blockedReaders = new Map();
|
|
619
619
|
|
|
620
|
+
/**
|
|
621
|
+
* How many stalls a torrent's readers have had, ever. Only differences between
|
|
622
|
+
* two readings of it mean anything.
|
|
623
|
+
*
|
|
624
|
+
* @type {Map<string, number>}
|
|
625
|
+
*/
|
|
626
|
+
const stallsSeen = new Map();
|
|
627
|
+
|
|
620
628
|
/**
|
|
621
629
|
* Whether any reader on this torrent is waiting for a piece right now.
|
|
622
630
|
*
|
|
@@ -627,6 +635,25 @@ export function readersAreBlockedOn(infoHash) {
|
|
|
627
635
|
return (blockedReaders.get(infoHash) ?? 0) > 0;
|
|
628
636
|
}
|
|
629
637
|
|
|
638
|
+
/**
|
|
639
|
+
* How many times a reader on this torrent has been blocked since the process
|
|
640
|
+
* started.
|
|
641
|
+
*
|
|
642
|
+
* Exists so that work of lower importance can ask "did the viewer stall while I
|
|
643
|
+
* was busy?" — which is a different and stricter question than "is the viewer
|
|
644
|
+
* stalled right now". On a swarm delivering exactly what the film needs, a
|
|
645
|
+
* background fetch that only pauses DURING a stall still takes bandwidth
|
|
646
|
+
* between them, and the stalls are the proof it had none to spare. Field
|
|
647
|
+
* 2026-08-31: the swarm delivered 200-600 KB/s against the 399 KB/s the film
|
|
648
|
+
* needs, and the picture stood still 145.6 s.
|
|
649
|
+
*
|
|
650
|
+
* @param {string} infoHash
|
|
651
|
+
* @returns {number}
|
|
652
|
+
*/
|
|
653
|
+
export function stallsSeenOn(infoHash) {
|
|
654
|
+
return stallsSeen.get(infoHash) ?? 0;
|
|
655
|
+
}
|
|
656
|
+
|
|
630
657
|
/**
|
|
631
658
|
* @param {string} infoHash
|
|
632
659
|
* @param {number} delta
|
|
@@ -636,6 +663,9 @@ function countBlockedReader(infoHash, delta) {
|
|
|
636
663
|
if (!infoHash) {
|
|
637
664
|
return;
|
|
638
665
|
}
|
|
666
|
+
if (delta > 0) {
|
|
667
|
+
stallsSeen.set(infoHash, (stallsSeen.get(infoHash) ?? 0) + 1);
|
|
668
|
+
}
|
|
639
669
|
const next = (blockedReaders.get(infoHash) ?? 0) + delta;
|
|
640
670
|
if (next > 0) {
|
|
641
671
|
blockedReaders.set(infoHash, next);
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import { readSubtitlePlan, harvestCluster } from "../container-index/matroska-subtitles.js";
|
|
21
21
|
import { decodeSubtitleSample, readMp4SubtitlePlan } from "../container-index/mp4-subtitles.js";
|
|
22
22
|
import { iterateElements } from "../container-index/ebml-reader.js";
|
|
23
|
+
import { detectLanguage } from "../language-detect.js";
|
|
23
24
|
import { logger } from "../../utils/logger.js";
|
|
24
25
|
|
|
25
26
|
/** Enough to read any cluster's own element header. */
|
|
@@ -483,12 +484,23 @@ export async function warmSubtitleCues(torrent, fileIndex, sourceKey) {
|
|
|
483
484
|
}
|
|
484
485
|
const highest = newCues.reduce((max, cue) => Math.max(max, Number(cue.seq) || 0), since);
|
|
485
486
|
state.pushed.set(track.trackNumber, highest);
|
|
486
|
-
const
|
|
487
|
+
const codecId = held.track?.codecId ?? track.codecId;
|
|
488
|
+
const cues = finalizeCues(newCues, codecId);
|
|
487
489
|
fresh.push({
|
|
488
490
|
// ffmpeg's own numbering, which is the only one the browser knows.
|
|
489
491
|
trackIndex: Number.isInteger(track.declaredIndex) ? track.declaredIndex : order,
|
|
490
492
|
cues,
|
|
491
493
|
language: held.track?.language ?? "",
|
|
494
|
+
// What the CUES say the language is, re-read on every push over every cue
|
|
495
|
+
// held so far rather than over this batch. A track whose container states
|
|
496
|
+
// no language is unreadable at the start of a session — a handful of cues
|
|
497
|
+
// is not a sample of a language, and the detector refuses to answer on one
|
|
498
|
+
// — so the answer has to be re-taken as the film downloads, and the label
|
|
499
|
+
// moved when it arrives. Costs about 6 ms per push, measured; pushes
|
|
500
|
+
// arrive about once a second per file being read.
|
|
501
|
+
detectedLanguage: detectLanguage(
|
|
502
|
+
finalizeCues(held.cues, codecId).map((cue) => cue.text).join("\n")
|
|
503
|
+
),
|
|
492
504
|
// Where the browser should resume from if it has to ask again — after a
|
|
493
505
|
// reconnect, which loses the subscription these pushes ride on.
|
|
494
506
|
cursor: highest,
|
|
@@ -154,3 +154,37 @@ test("the gate is re-asked before every chunk, not once at the start", async ()
|
|
|
154
154
|
await waitFor(() => !fillIsRunning("source-f", 0));
|
|
155
155
|
assert.equal(file.reads.length, 3);
|
|
156
156
|
});
|
|
157
|
+
|
|
158
|
+
test("a stall during a chunk makes the next one wait, not just a stall in progress", async () => {
|
|
159
|
+
// The case this exists for: a swarm delivering exactly what the film needs.
|
|
160
|
+
// Nothing is blocked at the moment the gate is asked, but the viewer stalled
|
|
161
|
+
// while the last chunk was in flight — which is the proof there was no room.
|
|
162
|
+
const file = fakeFile({ length: 12 });
|
|
163
|
+
const torrent = { infoHash: "ggg", pieceLength: 4, files: [file] };
|
|
164
|
+
let stalls = 0;
|
|
165
|
+
let starving = true;
|
|
166
|
+
// A stall happens DURING every chunk, exactly as it does on a swarm with no
|
|
167
|
+
// surplus — and nothing is blocked at the moment the gate is asked.
|
|
168
|
+
const originalRead = file.createReadStream.bind(file);
|
|
169
|
+
file.createReadStream = (range) => {
|
|
170
|
+
if (starving) {
|
|
171
|
+
stalls += 1;
|
|
172
|
+
}
|
|
173
|
+
return originalRead(range);
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
fillFileInBackground(torrent, 0, "source-g", {
|
|
177
|
+
chunkBytes: 4,
|
|
178
|
+
isBlocked: () => false,
|
|
179
|
+
stallsSeen: () => stalls
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
await waitFor(() => file.reads.length === 1);
|
|
183
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
184
|
+
assert.equal(file.reads.length, 1, "a stall during the chunk holds the next one back");
|
|
185
|
+
|
|
186
|
+
// The swarm settles: no further stalls, so it may go on.
|
|
187
|
+
starving = false;
|
|
188
|
+
await waitFor(() => !fillIsRunning("source-g", 0), 8000);
|
|
189
|
+
assert.equal(file.reads.length, 3);
|
|
190
|
+
});
|