@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.
- package/package.json +1 -1
- package/services/encode/EncodeInputs.js +3 -10
- package/services/encode/OutputWaitLedger.js +3 -1
- package/services/encode/PauseRule.js +3 -7
- package/services/encode/available-share.js +2 -10
- package/services/encode/learned-median.js +3 -38
- package/services/encode/quality/HostLoad.js +5 -4
- package/services/encode/run-costs.js +5 -22
- package/services/media/SubtitleCues.js +2 -1
- package/services/media/container/ElementaryAddresses.js +46 -0
- package/services/media/container/ac3-frame.js +5 -6
- package/services/media/container/avc-picture-order.js +2 -2
- package/services/media/container/bitstream.js +180 -0
- package/services/media/container/dts-frame.js +29 -13
- package/services/media/container/h264-configuration.js +4 -34
- package/services/media/container/h264-elementary-index.js +24 -51
- package/services/media/container/hevc-configuration.js +9 -25
- package/services/media/container/hevc-elementary-index.js +7 -11
- package/services/media/container/hevc-picture-order.js +3 -18
- package/services/media/container/latm-frame.js +11 -54
- package/services/media/container/mpeg-elementary-index.js +12 -25
- package/services/media/container/mpeg-video-configuration.js +12 -14
- package/services/media/container/mpeg4-picture-timing.js +4 -4
- package/services/media/tracks/audio-bound.js +10 -52
- package/services/server/ViewerRequests.js +2 -1
- package/services/server/wire-outputs.js +3 -2
- package/services/storage/Diagnostics.js +1 -7
- package/services/storage/MachineBudget.js +10 -6
- package/services/storage/machine-processor.js +1 -10
- package/services/storage/memory-report.js +17 -26
- package/services/storage/piece-store/shared-piece-store.js +6 -7
- package/services/storage/processor-report.js +2 -7
- package/services/storage/returns.js +3 -2
- package/services/storage/segment-store/SegmentStore.js +2 -1
- package/services/torrent/supply-margin.js +3 -11
- package/services/torrent/torrent-pool.js +4 -3
- package/services/torrent/worker/piece-reader.js +2 -5
- package/services/torrent/worker/worker.js +12 -11
- package/utils/clamp.js +11 -0
- package/utils/median.js +66 -0
- package/utils/units.js +35 -0
package/package.json
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { medianOf } from "../../utils/median.js";
|
|
1
2
|
import { admitInput } from "./AdmittedInput.js";
|
|
2
3
|
import { admitOriginalInput, originalInputBytes } from "./OriginalInput.js";
|
|
3
4
|
import { OriginalInputStore } from "./OriginalInputStore.js";
|
|
@@ -9,14 +10,6 @@ import { OriginalInputStore } from "./OriginalInputStore.js";
|
|
|
9
10
|
*/
|
|
10
11
|
const RECENT_READINGS = 20;
|
|
11
12
|
|
|
12
|
-
/** @param {number[]} values @returns {number | null} */
|
|
13
|
-
function middleOf(values) {
|
|
14
|
-
if (values.length === 0) return null;
|
|
15
|
-
const sorted = [...values].sort((left, right) => left - right);
|
|
16
|
-
const middle = Math.floor(sorted.length / 2);
|
|
17
|
-
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
|
|
18
|
-
}
|
|
19
|
-
|
|
20
13
|
/** @param {number[]} readings @param {number} value */
|
|
21
14
|
function keep(readings, value) {
|
|
22
15
|
readings.push(value);
|
|
@@ -373,7 +366,7 @@ export class EncodeInputs {
|
|
|
373
366
|
}
|
|
374
367
|
|
|
375
368
|
#sizingFor(output) {
|
|
376
|
-
const rate =
|
|
369
|
+
const rate = medianOf(this.#copyRates);
|
|
377
370
|
const open = this.#openOf(output);
|
|
378
371
|
return rate === null || !open ? null : { bytes: Math.floor(rate * open.seconds * 1000),
|
|
379
372
|
openMeasured: open.measured, openSeconds: open.seconds, copyBytesPerMs: rate };
|
|
@@ -388,7 +381,7 @@ export class EncodeInputs {
|
|
|
388
381
|
*/
|
|
389
382
|
stretchTerms() {
|
|
390
383
|
const capacity = this.#capacity();
|
|
391
|
-
return { copyBytesPerMs:
|
|
384
|
+
return { copyBytesPerMs: medianOf(this.#copyRates), capacityBytes: Number.isFinite(capacity) ? capacity : null };
|
|
392
385
|
}
|
|
393
386
|
|
|
394
387
|
/**
|
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
* given a rank and a number of milliseconds.
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
+
import { medianOf } from "../../utils/median.js";
|
|
25
|
+
|
|
24
26
|
/** How many waits to keep per rank. A median wants a sample, not a history. */
|
|
25
27
|
const HISTORY = 200;
|
|
26
28
|
|
|
@@ -136,7 +138,7 @@ export class WaitLedger {
|
|
|
136
138
|
continue;
|
|
137
139
|
}
|
|
138
140
|
const sorted = [...held].sort((a, b) => a - b);
|
|
139
|
-
const median =
|
|
141
|
+
const median = medianOf(held);
|
|
140
142
|
parts.push(
|
|
141
143
|
`${band} ${counts.get(band) ?? held.length} wait(s) median ${Math.round(median)}ms ` +
|
|
142
144
|
`worst ${Math.round(sorted[sorted.length - 1])}ms`
|
|
@@ -49,6 +49,8 @@
|
|
|
49
49
|
* `L` waited for its input say nothing about `r` and are left out.
|
|
50
50
|
*/
|
|
51
51
|
|
|
52
|
+
import { medianOf, scatterOf } from "../../utils/median.js";
|
|
53
|
+
|
|
52
54
|
/**
|
|
53
55
|
* How many seconds of readings a run keeps. Enough for a baseline before a try
|
|
54
56
|
* and the seconds beside after it; `L`'s cost changes from piece to piece, so
|
|
@@ -354,11 +356,5 @@ function changeOf(remembered, { band, otherRunning, others, draw }) {
|
|
|
354
356
|
* @returns {{ middle: number, scatter: number }}
|
|
355
357
|
*/
|
|
356
358
|
function middleAndScatter(values) {
|
|
357
|
-
|
|
358
|
-
const sorted = [...list].sort((left, right) => left - right);
|
|
359
|
-
const half = Math.floor(sorted.length / 2);
|
|
360
|
-
return sorted.length % 2 === 0 ? (sorted[half - 1] + sorted[half]) / 2 : sorted[half];
|
|
361
|
-
};
|
|
362
|
-
const middle = median(values);
|
|
363
|
-
return { middle, scatter: median(values.map((value) => Math.abs(value - middle))) };
|
|
359
|
+
return { middle: medianOf(values), scatter: scatterOf(values) };
|
|
364
360
|
}
|
|
@@ -56,6 +56,8 @@
|
|
|
56
56
|
* nothing changes.
|
|
57
57
|
*/
|
|
58
58
|
|
|
59
|
+
import { clamp } from "../../utils/clamp.js";
|
|
60
|
+
|
|
59
61
|
/**
|
|
60
62
|
* The share of the machine available to a new encoder.
|
|
61
63
|
*
|
|
@@ -147,13 +149,3 @@ export function correctForAvailability(predictedSpeed, availability) {
|
|
|
147
149
|
function finite(value) {
|
|
148
150
|
return Number.isFinite(value) ? Number(value) : null;
|
|
149
151
|
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* @param {number} value
|
|
153
|
-
* @param {number} low
|
|
154
|
-
* @param {number} high
|
|
155
|
-
* @returns {number}
|
|
156
|
-
*/
|
|
157
|
-
function clamp(value, low, high) {
|
|
158
|
-
return Math.min(high, Math.max(low, value));
|
|
159
|
-
}
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
* but it is answered from the measurements rather than from a constant.
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
|
+
import { scatterOf } from "../../utils/median.js";
|
|
21
|
+
|
|
20
22
|
/**
|
|
21
23
|
* How many of the most recent readings the median is taken over.
|
|
22
24
|
*
|
|
@@ -28,44 +30,7 @@
|
|
|
28
30
|
*/
|
|
29
31
|
export const READINGS_KEPT = 7;
|
|
30
32
|
|
|
31
|
-
|
|
32
|
-
* The middle of a set of readings, or null when there are none.
|
|
33
|
-
*
|
|
34
|
-
* @param {number[]} values
|
|
35
|
-
* @returns {number | null}
|
|
36
|
-
*/
|
|
37
|
-
export function medianOf(values) {
|
|
38
|
-
const usable = (Array.isArray(values) ? values : []).filter((value) => Number.isFinite(value));
|
|
39
|
-
if (usable.length === 0) {
|
|
40
|
-
return null;
|
|
41
|
-
}
|
|
42
|
-
const sorted = [...usable].sort((left, right) => left - right);
|
|
43
|
-
const middle = Math.floor(sorted.length / 2);
|
|
44
|
-
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* How far the readings sit from their own middle — the median of their
|
|
49
|
-
* distances to it.
|
|
50
|
-
*
|
|
51
|
-
* The median distance rather than the mean one, for the same reason the value
|
|
52
|
-
* itself is a median: a single disturbed reading describes the disturbance, not
|
|
53
|
-
* the host.
|
|
54
|
-
*
|
|
55
|
-
* @param {number[]} values
|
|
56
|
-
* @returns {number | null} Null when there is nothing to measure. Zero is a
|
|
57
|
-
* real answer: readings that all agree disagree by nothing.
|
|
58
|
-
*/
|
|
59
|
-
export function scatterOf(values) {
|
|
60
|
-
const middle = medianOf(values);
|
|
61
|
-
if (middle === null) {
|
|
62
|
-
return null;
|
|
63
|
-
}
|
|
64
|
-
const distances = (Array.isArray(values) ? values : [])
|
|
65
|
-
.filter((value) => Number.isFinite(value))
|
|
66
|
-
.map((value) => Math.abs(value - middle));
|
|
67
|
-
return medianOf(distances);
|
|
68
|
-
}
|
|
33
|
+
export { medianOf, scatterOf } from "../../utils/median.js";
|
|
69
34
|
|
|
70
35
|
/**
|
|
71
36
|
* Whether a newly computed median should replace the published one.
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import os from "node:os";
|
|
11
11
|
import { monitorEventLoopDelay } from "node:perf_hooks";
|
|
12
12
|
import { logger } from "../../../utils/logger.js";
|
|
13
|
+
import { megabytesPerSecond } from "../../../utils/units.js";
|
|
13
14
|
import { availableShareFrom } from "../available-share.js";
|
|
14
15
|
import { encoderCpuBetween } from "./encoder-cpu.js";
|
|
15
16
|
import { baseDrawFrom, costPerMegabyteFrom } from "../torrent-cost.js";
|
|
@@ -40,7 +41,7 @@ function threadSays(now, previous) {
|
|
|
40
41
|
const freeBytes = (now.selection?.freeBytes ?? 0) - (previous.selection?.freeBytes ?? 0);
|
|
41
42
|
const held = ms > 0 && freeMs >= 0 && freeMs <= ms
|
|
42
43
|
? `; our selection held a peer back ${Math.round((1 - freeMs / ms) * 100)}% of the time` +
|
|
43
|
-
(freeMs > 0 ? `, the rest gave ${(freeBytes / freeMs
|
|
44
|
+
(freeMs > 0 ? `, the rest gave ${megabytesPerSecond(freeBytes / freeMs * 1000)}` : "") : "";
|
|
44
45
|
return loop + reads + held;
|
|
45
46
|
}
|
|
46
47
|
|
|
@@ -281,12 +282,12 @@ export class HostLoad {
|
|
|
281
282
|
// processor can be set against each kind of work (torrent-tv/meta#178).
|
|
282
283
|
const movedOf = (key) => Number.isFinite(now[key]) && Number.isFinite(previous[key]) && now[key] >= previous[key]
|
|
283
284
|
? (now[key] - previous[key]) / 1e6 : null;
|
|
284
|
-
const rateOf = (key) => movedOf(key) === null ? "n/a" :
|
|
285
|
+
const rateOf = (key) => movedOf(key) === null ? "n/a" : megabytesPerSecond(movedOf(key) * 1e6 / elapsedSec);
|
|
285
286
|
if (megabytes > 0 || Number.isFinite(limit) || movedOf("served") > 0 || movedOf("uploaded") > 0) {
|
|
286
287
|
logger.info(
|
|
287
|
-
`torrent: downloaded ${(megabytes / elapsedSec)
|
|
288
|
+
`torrent: downloaded ${megabytesPerSecond(megabytes * 1e6 / elapsedSec)}, sent to peers ${rateOf("uploaded")}, ` +
|
|
288
289
|
`handed to readers ${rateOf("served")} over ${elapsedSec.toFixed(1)}s, ` +
|
|
289
|
-
`limit ${Number.isFinite(limit) ?
|
|
290
|
+
`limit ${Number.isFinite(limit) ? megabytesPerSecond(limit) : "none"}; ` +
|
|
290
291
|
`its thread drew ${Math.round(cpuSeconds / elapsedSec * 100)}% of the machine` + threadSays(now, previous)
|
|
291
292
|
);
|
|
292
293
|
}
|
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
* answer.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
+
import { medianOf } from "../../utils/median.js";
|
|
19
|
+
|
|
18
20
|
/**
|
|
19
21
|
* How many recent readings a figure is taken from. The same reasoning as the
|
|
20
22
|
* other learned figures in this proxy: long enough that one reading does not
|
|
@@ -22,25 +24,6 @@
|
|
|
22
24
|
*/
|
|
23
25
|
const RECENT_READINGS = 20;
|
|
24
26
|
|
|
25
|
-
/**
|
|
26
|
-
* The middle of a set of readings, or null when there are none.
|
|
27
|
-
*
|
|
28
|
-
* Written here rather than borrowed from the general helper one level up: this
|
|
29
|
-
* layer states facts and imports nothing above itself, and four lines of
|
|
30
|
-
* arithmetic are not worth breaking that for.
|
|
31
|
-
*
|
|
32
|
-
* @param {number[]} values
|
|
33
|
-
* @returns {number | null}
|
|
34
|
-
*/
|
|
35
|
-
function middleOf(values) {
|
|
36
|
-
if (values.length === 0) {
|
|
37
|
-
return null;
|
|
38
|
-
}
|
|
39
|
-
const sorted = [...values].sort((left, right) => left - right);
|
|
40
|
-
const middle = Math.floor(sorted.length / 2);
|
|
41
|
-
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
|
|
42
|
-
}
|
|
43
|
-
|
|
44
27
|
export class RunCosts {
|
|
45
28
|
/** How long dying took, in milliseconds. @type {number[]} */
|
|
46
29
|
#dying = [];
|
|
@@ -145,7 +128,7 @@ export class RunCosts {
|
|
|
145
128
|
* @returns {{ seconds: number, measured: boolean } | null}
|
|
146
129
|
*/
|
|
147
130
|
openOf(address) {
|
|
148
|
-
const own =
|
|
131
|
+
const own = medianOf(this.#opens.get(address) ?? []);
|
|
149
132
|
if (own !== null) return { seconds: own, measured: true };
|
|
150
133
|
const startup = this.#atStartup?.firstByteWaitSec;
|
|
151
134
|
return Number.isFinite(startup) && startup > 0 ? { seconds: startup, measured: false } : null;
|
|
@@ -191,9 +174,9 @@ export class RunCosts {
|
|
|
191
174
|
// piece's encoding. Whoever uses it separates the two, because the piece
|
|
192
175
|
// costs more when encoders share the machine and the spawn does not.
|
|
193
176
|
return {
|
|
194
|
-
killCostSec: (
|
|
177
|
+
killCostSec: (medianOf(this.#dying) ?? 0) / 1000 || (this.#atStartup?.killCostSec ?? 0),
|
|
195
178
|
firstByteWaitSec:
|
|
196
|
-
(
|
|
179
|
+
(medianOf(this.#firstOutput) ?? 0) / 1000 || (this.#atStartup?.firstByteWaitSec ?? 0),
|
|
197
180
|
samples: Math.min(this.#dying.length, this.#firstOutput.length)
|
|
198
181
|
};
|
|
199
182
|
}
|
|
@@ -31,6 +31,7 @@ import { TextSubtitleTrack } from "./tracks/TextSubtitleTrack.js";
|
|
|
31
31
|
import { detectLanguage } from "./tracks/language-detect.js";
|
|
32
32
|
import { isUnavailable, strictReader } from "./container/unavailable.js";
|
|
33
33
|
import { logger } from "../../utils/logger.js";
|
|
34
|
+
import { megabytes } from "../../utils/units.js";
|
|
34
35
|
|
|
35
36
|
/**
|
|
36
37
|
* One file of one torrent, as much of it as this layer is allowed to know.
|
|
@@ -419,7 +420,7 @@ function reportWalk(source, state, stats, covered, indexed) {
|
|
|
419
420
|
`${stats.fromSearch ?? 0} found by searching the bytes, ${stats.rejectedCandidates ?? 0} candidate(s) refused, ` +
|
|
420
421
|
`${stats.pendingCandidates ?? 0} waiting for bytes, ${stats.contradictions ?? 0} withdrawn, ` +
|
|
421
422
|
`${stats.unreadable ?? 0} unreadable, ${stats.refusedElements ?? 0} block(s) over one read, ` +
|
|
422
|
-
`${
|
|
423
|
+
`${megabytes(stats.bytesWalked ?? 0)} read`
|
|
423
424
|
);
|
|
424
425
|
}
|
|
425
426
|
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the bytes of one elementary stream came from, and the PES stamps that arrived with them. A transport
|
|
3
|
+
* stream is walked once and its packets discarded; this keeps just enough to give every access unit or audio
|
|
4
|
+
* frame the exact source ranges of its bytes and the last stamp at or before its first byte.
|
|
5
|
+
*/
|
|
6
|
+
export class ElementaryAddresses {
|
|
7
|
+
#mappings = [];
|
|
8
|
+
#stamps = [];
|
|
9
|
+
#incomplete;
|
|
10
|
+
|
|
11
|
+
/** @param {string} incomplete - The error message when some byte of a range has no source address. */
|
|
12
|
+
constructor(incomplete) {
|
|
13
|
+
this.#incomplete = incomplete;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Bytes `from` up to `from + length` of the elementary stream sit at `sourceStart` of the file. */
|
|
17
|
+
map(from, length, sourceStart) {
|
|
18
|
+
this.#mappings.push({ from, to: from + length, sourceStart });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A stamp that arrived with the byte at elementary position `position`. */
|
|
22
|
+
stamp(position, pts, dts = pts) {
|
|
23
|
+
this.#stamps.push({ position, pts, dts });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @returns {{ position: number, pts: number, dts: number } | null} the last stamp at or before `position`, consumed with the ones before it */
|
|
27
|
+
stampAt(position) {
|
|
28
|
+
let latest = null;
|
|
29
|
+
while (this.#stamps[0]?.position <= position) latest = this.#stamps.shift();
|
|
30
|
+
return latest;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @returns {Array<[number, number]>} the inclusive source ranges of elementary bytes `from` up to `to` */
|
|
34
|
+
ranges(from, to) {
|
|
35
|
+
const ranges = this.#mappings.filter(mapping => mapping.from < to && mapping.to > from).map(mapping => [
|
|
36
|
+
mapping.sourceStart + Math.max(from, mapping.from) - mapping.from,
|
|
37
|
+
mapping.sourceStart + Math.min(to, mapping.to) - mapping.from - 1]);
|
|
38
|
+
if (ranges.reduce((sum, [a, b]) => sum + b - a + 1, 0) !== to - from) throw new Error(this.#incomplete);
|
|
39
|
+
return ranges;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Forget the addresses of every byte before `end`: nothing will ask for them again. */
|
|
43
|
+
release(end) {
|
|
44
|
+
this.#mappings = this.#mappings.filter(mapping => mapping.to > end);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -1,14 +1,13 @@
|
|
|
1
|
+
import { Bits } from "./bitstream.js";
|
|
2
|
+
|
|
1
3
|
/** ATSC A/52 sync information gives exact frame length and sample count. */
|
|
2
4
|
export function ac3Frame(bytes) {
|
|
3
5
|
if (bytes.length < 7 || bytes[0] !== 0x0b || bytes[1] !== 0x77) throw new Error("AC-3 frame synchronization is invalid.");
|
|
4
6
|
const bitstreamId = bytes[5] >> 3;
|
|
5
7
|
if (bitstreamId > 16) throw new Error("AC-3 bitstream version is invalid.");
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
for (let bit = 0; bit < count; bit++, position++) value = (value << 1) | ((bytes[position >> 3] >> (7 - (position & 7))) & 1);
|
|
10
|
-
return value;
|
|
11
|
-
};
|
|
8
|
+
const bits = new Bits(bytes, "AC-3 frame header");
|
|
9
|
+
bits.skip(16);
|
|
10
|
+
const read = count => bits.uint(count);
|
|
12
11
|
let sampleRate, size, channelMode, lfe, samples, codecId;
|
|
13
12
|
const frequencies = [48000, 44100, 32000];
|
|
14
13
|
if (bitstreamId <= 10) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Bits,
|
|
1
|
+
import { Bits, rbsp } from "./bitstream.js";
|
|
2
2
|
|
|
3
3
|
/** AVC frame picture-order counts, retaining reference and frame-number wraps. */
|
|
4
4
|
export class AvcPictureOrder {
|
|
@@ -15,7 +15,7 @@ export class AvcPictureOrder {
|
|
|
15
15
|
(params.type === 1 && !Array.isArray(params.referenceOffsets))) {
|
|
16
16
|
throw new Error("AVC missing timestamps require supported frame picture-order declarations.");
|
|
17
17
|
}
|
|
18
|
-
const bits = new Bits(
|
|
18
|
+
const bits = new Bits(rbsp(nal, 1), "AVC slice header");
|
|
19
19
|
bits.ue(); bits.ue(); bits.ue();
|
|
20
20
|
const frameNumber = bits.uint(params.frameNumberBits);
|
|
21
21
|
const idr = (nal[0] & 31) === 5;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file How this proxy reads the bits of a video or audio elementary stream:
|
|
3
|
+
* one bounded MSB-first reader, one emulation-prevention rule, one AAC
|
|
4
|
+
* sampling-frequency table and one AudioSpecificConfig parser. Every parser of
|
|
5
|
+
* a bitstream (AVC, HEVC, MPEG video, DTS, AC-3, AAC/LATM) reads through this
|
|
6
|
+
* file, so a stream is refused or accepted the same way wherever it is read.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** ISO/IEC 14496-3 Table 1.18: samplingFrequencyIndex to Hz. 0xF is an explicit 24-bit rate. */
|
|
10
|
+
export const AAC_SAMPLE_RATES = Object.freeze([96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]);
|
|
11
|
+
|
|
12
|
+
/** ISO/IEC 14496-3 Table 1.19: channelConfiguration to channels; 0 is a program configuration element. */
|
|
13
|
+
const AAC_CHANNELS = Object.freeze([null, 1, 2, 3, 4, 5, 6, 8]);
|
|
14
|
+
|
|
15
|
+
/** A bounded MSB-first bit reader. A read past the end throws under `label`. */
|
|
16
|
+
export class Bits {
|
|
17
|
+
at = 0;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {Buffer | Uint8Array} bytes
|
|
21
|
+
* @param {string} label - Names what is read in every error ("HEVC SPS" gives "HEVC SPS bits are truncated.").
|
|
22
|
+
*/
|
|
23
|
+
constructor(bytes, label) {
|
|
24
|
+
this.bytes = bytes;
|
|
25
|
+
this.label = label;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** @param {number} count - 0 to 32 bits. @returns {number} the unsigned value */
|
|
29
|
+
uint(count) {
|
|
30
|
+
if (!(count >= 0 && count <= 32) || this.at + count > this.bytes.length * 8) throw new Error(`${this.label} bits are truncated.`);
|
|
31
|
+
let value = 0;
|
|
32
|
+
for (let index = 0; index < count; index++, this.at++) value = value * 2 + ((this.bytes[this.at >> 3] >> (7 - (this.at & 7))) & 1);
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @param {number} count - Any number of bits to pass over. */
|
|
37
|
+
skip(count) {
|
|
38
|
+
if (!(count >= 0) || this.at + count > this.bytes.length * 8) throw new Error(`${this.label} bits are truncated.`);
|
|
39
|
+
this.at += count;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @returns {number} an unsigned Exp-Golomb value */
|
|
43
|
+
ue() {
|
|
44
|
+
let zeroes = 0;
|
|
45
|
+
while (!this.uint(1)) if (++zeroes > 31) throw new Error(`${this.label} Exp-Golomb value is invalid.`);
|
|
46
|
+
return 2 ** zeroes - 1 + this.uint(zeroes);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** @returns {number} a signed Exp-Golomb value */
|
|
50
|
+
se() {
|
|
51
|
+
const code = this.ue();
|
|
52
|
+
return code & 1 ? (code + 1) / 2 : -code / 2;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The bits from `from` to `to` as bytes, MSB first and zero padded; the read position is left where it was.
|
|
57
|
+
* @returns {Buffer}
|
|
58
|
+
*/
|
|
59
|
+
copy(from, to) {
|
|
60
|
+
const reader = new Bits(this.bytes, this.label);
|
|
61
|
+
reader.skip(from);
|
|
62
|
+
const bytes = Buffer.alloc(Math.ceil((to - from) / 8));
|
|
63
|
+
for (let done = 0; done < to - from; done += 8) {
|
|
64
|
+
const width = Math.min(8, to - from - done);
|
|
65
|
+
bytes[done >> 3] = reader.uint(width) << (8 - width);
|
|
66
|
+
}
|
|
67
|
+
return bytes;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The emulation-prevention rule, one byte at a time: a 0x03 after two zero bytes is dropped whatever follows
|
|
73
|
+
* it. H.264 §7.4.1 forbids 0x000003 before a byte above 0x03, but encoders write it (LostFilm's LostCoder)
|
|
74
|
+
* and decoders drop it (ffmpeg's ff_h2645_extract_rbsp), so refusing it refuses files every player plays.
|
|
75
|
+
*/
|
|
76
|
+
export class EmulationPrevention {
|
|
77
|
+
#zeroes = 0;
|
|
78
|
+
|
|
79
|
+
/** @param {number} byte @returns {boolean} whether the byte belongs to the RBSP (false: it is the 0x03 to drop) */
|
|
80
|
+
keeps(byte) {
|
|
81
|
+
if (this.#zeroes >= 2 && byte === 3) {
|
|
82
|
+
this.#zeroes = 0;
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
this.#zeroes = byte === 0 ? this.#zeroes + 1 : 0;
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The raw byte sequence payload of a NAL unit: emulation prevention bytes removed, never throws.
|
|
92
|
+
* @param {Buffer} nal
|
|
93
|
+
* @param {number} start - Where the payload begins: 1 after an AVC header, 2 after an HEVC header.
|
|
94
|
+
* @returns {Buffer} a new buffer; `nal` is left alone
|
|
95
|
+
*/
|
|
96
|
+
export function rbsp(nal, start) {
|
|
97
|
+
const bytes = Buffer.allocUnsafe(Math.max(0, nal.length - start));
|
|
98
|
+
const rule = new EmulationPrevention();
|
|
99
|
+
let length = 0;
|
|
100
|
+
for (let at = start; at < nal.length; at++) if (rule.keeps(nal[at])) bytes[length++] = nal[at];
|
|
101
|
+
return bytes.subarray(0, length);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Read an AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1) from the current position, as the one reading of it:
|
|
106
|
+
* explicit SBR and parametric stereo, and the program configuration element of channelConfiguration 0.
|
|
107
|
+
* Given a `Bits` it reads from where that stands, as a LATM stream does, and truncation throws under its label.
|
|
108
|
+
* Given bytes it answers null when they are no readable configuration.
|
|
109
|
+
*
|
|
110
|
+
* `objectType` is the type as first declared (5 SBR, 29 PS, else the codec's own) and `audioObjectType` the
|
|
111
|
+
* codec underneath; `sampleRate` is the output rate and `coreSampleRate` the one a frame lasts by. A
|
|
112
|
+
* configuration this proxy cannot describe (a codec other than AAC Main/LC/SSR/LTP, no rate, a channel
|
|
113
|
+
* configuration above 7) answers `supported: false` with only what was read before it was told so.
|
|
114
|
+
*
|
|
115
|
+
* @param {Bits | Buffer} source
|
|
116
|
+
* @returns {null | { supported: boolean, objectType: number, audioObjectType: number, sampleRate: number | undefined,
|
|
117
|
+
* coreSampleRate: number | undefined, channelConfiguration: number, channels: number | null,
|
|
118
|
+
* frameLength: number | null, extensionVersion: number }}
|
|
119
|
+
*/
|
|
120
|
+
export function parseAudioSpecificConfig(source) {
|
|
121
|
+
if (source instanceof Bits) return readConfig(source);
|
|
122
|
+
if (!Buffer.isBuffer(source) || source.length < 2) return null;
|
|
123
|
+
try { return readConfig(new Bits(source, "AudioSpecificConfig")); }
|
|
124
|
+
catch { return null; }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function readConfig(bits) {
|
|
128
|
+
const start = bits.at;
|
|
129
|
+
const objectType = audioObjectType(bits);
|
|
130
|
+
let type = objectType;
|
|
131
|
+
const coreSampleRate = audioRate(bits);
|
|
132
|
+
const channelConfiguration = bits.uint(4);
|
|
133
|
+
let sampleRate = coreSampleRate;
|
|
134
|
+
if (type === 5 || type === 29) {
|
|
135
|
+
sampleRate = audioRate(bits);
|
|
136
|
+
type = audioObjectType(bits);
|
|
137
|
+
}
|
|
138
|
+
const result = { supported: false, objectType, audioObjectType: type, sampleRate, coreSampleRate, channelConfiguration,
|
|
139
|
+
channels: AAC_CHANNELS[channelConfiguration] ?? null, frameLength: null, extensionVersion: 0 };
|
|
140
|
+
if (![1, 2, 3, 4].includes(type) || !(coreSampleRate > 0) || !(sampleRate > 0) || channelConfiguration > 7) return result;
|
|
141
|
+
const shortFrame = bits.uint(1);
|
|
142
|
+
if (bits.uint(1)) bits.uint(14);
|
|
143
|
+
const extension = bits.uint(1);
|
|
144
|
+
const channels = channelConfiguration ? result.channels : programChannels(bits, start, coreSampleRate);
|
|
145
|
+
if (extension) result.extensionVersion = bits.uint(1);
|
|
146
|
+
return { ...result, supported: true, frameLength: shortFrame ? 960 : 1024,
|
|
147
|
+
channels: objectType === 29 && channels === 1 ? 2 : channels };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function audioObjectType(bits) {
|
|
151
|
+
const type = bits.uint(5);
|
|
152
|
+
return type === 31 ? 32 + bits.uint(6) : type;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function audioRate(bits) {
|
|
156
|
+
const index = bits.uint(4);
|
|
157
|
+
return index === 15 ? bits.uint(24) : AAC_SAMPLE_RATES[index];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The program configuration element declares every single, paired and LFE channel. */
|
|
161
|
+
function programChannels(bits, start, sampleRate) {
|
|
162
|
+
bits.skip(6);
|
|
163
|
+
if (AAC_SAMPLE_RATES[bits.uint(4)] !== sampleRate) throw new Error("AAC program sample rate differs from its decoder declaration.");
|
|
164
|
+
const front = bits.uint(4), side = bits.uint(4), back = bits.uint(4), lfe = bits.uint(2),
|
|
165
|
+
associated = bits.uint(3), coupled = bits.uint(4);
|
|
166
|
+
if (bits.uint(1)) bits.skip(4);
|
|
167
|
+
if (bits.uint(1)) bits.skip(4);
|
|
168
|
+
if (bits.uint(1)) bits.skip(3);
|
|
169
|
+
let channels = lfe;
|
|
170
|
+
for (let index = 0; index < front + side + back; index++) {
|
|
171
|
+
channels += bits.uint(1) ? 2 : 1;
|
|
172
|
+
bits.skip(4);
|
|
173
|
+
}
|
|
174
|
+
bits.skip(4 * (lfe + associated));
|
|
175
|
+
bits.skip(5 * coupled);
|
|
176
|
+
bits.skip((8 - ((bits.at - start) % 8)) % 8);
|
|
177
|
+
bits.skip(bits.uint(8) * 8);
|
|
178
|
+
if (!channels) throw new Error("AAC program declares no output channels.");
|
|
179
|
+
return channels;
|
|
180
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { Bits } from "./bitstream.js";
|
|
2
|
+
|
|
1
3
|
/** DTS core headers declare physical frame length and PCM block duration. */
|
|
2
4
|
export function dtsFrame(bytes) {
|
|
3
5
|
if (bytes.length < 24) throw new Error("DTS core header is truncated.");
|
|
@@ -7,19 +9,9 @@ export function dtsFrame(bytes) {
|
|
|
7
9
|
if (![0x7ffe8001, 0xfe7f0180, 0x1fffe800, 0xff1f00e8].includes(sync)) {
|
|
8
10
|
throw new Error("DTS core synchronization is invalid.");
|
|
9
11
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
let byte = physical >> 3;
|
|
14
|
-
if (little) byte ^= 1;
|
|
15
|
-
if (byte >= bytes.length) throw new Error("DTS core header is truncated.");
|
|
16
|
-
return (bytes[byte] >> (7 - (physical & 7))) & 1;
|
|
17
|
-
};
|
|
18
|
-
const read = count => {
|
|
19
|
-
let value = 0;
|
|
20
|
-
for (let at = 0; at < count; at++) value = value * 2 + bit(position++);
|
|
21
|
-
return value;
|
|
22
|
-
};
|
|
12
|
+
const bits = new Bits(logicalBytes(bytes.subarray(0, 24), packed, little), "DTS core header");
|
|
13
|
+
bits.skip(32);
|
|
14
|
+
const read = count => bits.uint(count);
|
|
23
15
|
read(1);
|
|
24
16
|
if (read(5) !== 31) throw new Error("DTS deficit sample count is invalid.");
|
|
25
17
|
const crc = read(1);
|
|
@@ -49,3 +41,27 @@ export function dtsFrame(bytes) {
|
|
|
49
41
|
return { size: packed ? Math.ceil(logicalSize * 8 / 14) * 2 : logicalSize,
|
|
50
42
|
sampleRate, channels: channels + Number(lfe > 0), duration: blocks * 32 / sampleRate, codecId: "dts" };
|
|
51
43
|
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The header as a plain big-endian bit string: bytes swapped when the stream is little-endian, and the
|
|
47
|
+
* 14-bit words of a packed stream (two padding bits in each 16) joined end to end.
|
|
48
|
+
*/
|
|
49
|
+
function logicalBytes(bytes, packed, little) {
|
|
50
|
+
const ordered = Buffer.from(bytes.subarray(0, bytes.length - (bytes.length & 1)));
|
|
51
|
+
if (little) ordered.swap16();
|
|
52
|
+
if (!packed) return ordered;
|
|
53
|
+
const words = new Bits(ordered, "DTS core header");
|
|
54
|
+
const joined = [];
|
|
55
|
+
let held = 0, count = 0;
|
|
56
|
+
while (words.at < ordered.length * 8) {
|
|
57
|
+
words.skip(2);
|
|
58
|
+
held = held * 16384 + words.uint(14);
|
|
59
|
+
count += 14;
|
|
60
|
+
while (count >= 8) {
|
|
61
|
+
count -= 8;
|
|
62
|
+
joined.push(Math.floor(held / 2 ** count));
|
|
63
|
+
held %= 2 ** count;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return Buffer.from(joined);
|
|
67
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { Bits, rbsp } from "./bitstream.js";
|
|
2
|
+
|
|
1
3
|
/** H.264 SPS facts required to bound decode reordering and describe frames. */
|
|
2
4
|
export function h264Configuration(avcc) {
|
|
3
5
|
if (!Buffer.isBuffer(avcc) || avcc.length < 7 || avcc[0] !== 1) throw new Error("AVC decoder configuration is invalid.");
|
|
@@ -21,7 +23,7 @@ export function h264Configuration(avcc) {
|
|
|
21
23
|
|
|
22
24
|
function readSps(nal, includeOrder = false) {
|
|
23
25
|
if ((nal[0] & 31) !== 7 || nal[0] & 128) throw new Error("AVC configuration entry is not an SPS.");
|
|
24
|
-
const bits = new Bits(
|
|
26
|
+
const bits = new Bits(rbsp(nal, 1), "AVC SPS");
|
|
25
27
|
const profile = bits.uint(8), constraints = bits.uint(8), level = bits.uint(8);
|
|
26
28
|
bits.ue();
|
|
27
29
|
let chroma = 1, separate = 0, depth = 8;
|
|
@@ -117,27 +119,11 @@ function readSps(nal, includeOrder = false) {
|
|
|
117
119
|
|
|
118
120
|
export function avcOrderParameters(sps, pps) {
|
|
119
121
|
const facts = readSps(sps, true);
|
|
120
|
-
const bits = new Bits(
|
|
122
|
+
const bits = new Bits(rbsp(pps, 1), "AVC PPS");
|
|
121
123
|
bits.ue(); bits.ue(); bits.uint(1);
|
|
122
124
|
return { ...facts.pictureOrder, bottomFieldOrderPresent: bits.uint(1) === 1 };
|
|
123
125
|
}
|
|
124
126
|
|
|
125
|
-
/**
|
|
126
|
-
* Remove every emulation prevention byte: a 0x03 after two zero bytes, whatever follows it. H.264 §7.4.1
|
|
127
|
-
* forbids 0x000003 before a byte above 0x03, but encoders write it (LostFilm's LostCoder) and decoders drop
|
|
128
|
-
* it (ffmpeg's ff_h2645_extract_rbsp), so refusing it refuses files every player plays.
|
|
129
|
-
*/
|
|
130
|
-
export function unescapeNal(nal) {
|
|
131
|
-
const bytes = [];
|
|
132
|
-
for (let at = 1, zeroes = 0; at < nal.length; at++) {
|
|
133
|
-
const byte = nal[at];
|
|
134
|
-
if (zeroes >= 2 && byte === 3) { zeroes = 0; continue; }
|
|
135
|
-
bytes.push(byte);
|
|
136
|
-
zeroes = byte === 0 ? zeroes + 1 : 0;
|
|
137
|
-
}
|
|
138
|
-
return Buffer.from(bytes);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
127
|
/** Build the decoder declaration from the complete in-band SPS and PPS units. */
|
|
142
128
|
export function avcConfigurationFromUnits(sps, pps) {
|
|
143
129
|
if (!Buffer.isBuffer(sps) || !Buffer.isBuffer(pps) || sps.length < 4 || !pps.length ||
|
|
@@ -158,19 +144,3 @@ function hrd(bits) {
|
|
|
158
144
|
bits.uint(5);
|
|
159
145
|
return removal + output;
|
|
160
146
|
}
|
|
161
|
-
|
|
162
|
-
export class Bits {
|
|
163
|
-
constructor(bytes, label = "AVC") { this.bytes = bytes; this.at = 0; this.label = label; }
|
|
164
|
-
uint(count) {
|
|
165
|
-
if (count < 0 || count > 32 || this.at + count > this.bytes.length * 8) throw new Error(`${this.label} SPS bits are truncated.`);
|
|
166
|
-
let value = 0;
|
|
167
|
-
for (let index = 0; index < count; index++, this.at++) value = value * 2 + ((this.bytes[this.at >> 3] >> (7 - (this.at & 7))) & 1);
|
|
168
|
-
return value;
|
|
169
|
-
}
|
|
170
|
-
ue() {
|
|
171
|
-
let zeroes = 0;
|
|
172
|
-
while (!this.uint(1)) if (++zeroes > 31) throw new Error(`${this.label} Exp-Golomb value is invalid.`);
|
|
173
|
-
return 2 ** zeroes - 1 + this.uint(zeroes);
|
|
174
|
-
}
|
|
175
|
-
se() { const code = this.ue(); return code & 1 ? (code + 1) / 2 : -code / 2; }
|
|
176
|
-
}
|