moqtail 0.16.0 → 0.17.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.
@@ -1,9 +1,29 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-CmQyd0Gu.cjs");
1
+ // \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
2
22
  const require_model = require("./model.cjs");
3
23
  const require_emitter = require("./emitter-qNJYD3yQ.cjs");
4
- const require_client = require("./client-DQ5aGbLR.cjs");
24
+ const require_client = require("./client-FnSNJocV.cjs");
5
25
  let valibot = require("valibot");
6
- valibot = require_rolldown_runtime.__toESM(valibot, 1);
26
+ valibot = __toESM(valibot, 1);
7
27
  // src/player/error.ts
8
28
  const CATEGORY = {
9
29
  SESSION_LOST: "network",
@@ -88,8 +108,8 @@ function parseMsfUrl(uri) {
88
108
  case "wallclock-range":
89
109
  source.wallclockRanges.push(parseTimeRange(value));
90
110
  break;
91
- case "c4m":
92
- source.c4m = value;
111
+ case "cat":
112
+ source.cat = value;
93
113
  break;
94
114
  case "connection":
95
115
  if (value !== "q" && value !== "wt") unsupported(`connection must be q or wt, got ${value}`);
@@ -1654,7 +1674,7 @@ const hasBom = (bytes) => bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 1
1654
1674
  * (MSF 5.2.39 to 5.2.42, CMSF 5.1) stay untyped extra fields.
1655
1675
  */
1656
1676
  /** The `version` values this player parses, with the editor's draft rules. */
1657
- const SUPPORTED_MSF_VERSIONS = ["draft-01"];
1677
+ const SUPPORTED_MSF_VERSIONS = ["draft-01", "draft-02"];
1658
1678
  const int = valibot.pipe(valibot.number(), valibot.integer());
1659
1679
  const location = valibot.tuple([int, int]);
1660
1680
  /** MSF 5.2.5: `key=value;key=value`, the first occurrence of a key wins. */
@@ -1975,7 +1995,7 @@ function checkNames(tracks) {
1975
1995
  * Applies a delta update object to `base`, which is left as it is.
1976
1996
  * @throws PlayerError `INVALID_CATALOG_UPDATE` when the delta, or the catalog it leads to, is invalid.
1977
1997
  */
1978
- function applyDelta(base, bytes, ctx) {
1998
+ function applyDelta$1(base, bytes, ctx) {
1979
1999
  try {
1980
2000
  const warnings = [];
1981
2001
  const delta = valibot.safeParse(DeltaSchema, readJson(bytes, ctx, warnings));
@@ -2064,7 +2084,7 @@ const IGNORED = /* @__PURE__ */ new Set([
2064
2084
  "namespace",
2065
2085
  "template"
2066
2086
  ]);
2067
- const KNOWN = /* @__PURE__ */ new Set([...TRACK_FIELD_NAMES, "init"]);
2087
+ const KNOWN$1 = /* @__PURE__ */ new Set([...TRACK_FIELD_NAMES, "init"]);
2068
2088
  function diffTracks(before, after) {
2069
2089
  const previous = new Map(before.map((t) => [trackKey(t), t]));
2070
2090
  const diff = {
@@ -2094,7 +2114,7 @@ function diffTracks(before, after) {
2094
2114
  }
2095
2115
  const changed = [.../* @__PURE__ */ new Set([...Object.keys(old), ...Object.keys(track)])].filter((field) => !IGNORED.has(field) && !deepEqual(old[field], track[field]));
2096
2116
  const inPlace = (field) => {
2097
- if (!KNOWN.has(field)) return true;
2117
+ if (!KNOWN$1.has(field)) return true;
2098
2118
  return IN_PLACE.has(field) && (field !== "isLive" || old.isLive);
2099
2119
  };
2100
2120
  if (changed.every(inPlace)) {
@@ -2108,6 +2128,25 @@ function diffTracks(before, after) {
2108
2128
  return diff;
2109
2129
  }
2110
2130
  // src/player/elements/catalog/selection.ts
2131
+ /**
2132
+ * Copyright 2026 The MOQtail Authors
2133
+ *
2134
+ * Licensed under the Apache License, Version 2.0 (the "License");
2135
+ * you may not use this file except in compliance with the License.
2136
+ * You may obtain a copy of the License at
2137
+ *
2138
+ * http://www.apache.org/licenses/LICENSE-2.0
2139
+ *
2140
+ * Unless required by applicable law or agreed to in writing, software
2141
+ * distributed under the License is distributed on an "AS IS" BASIS,
2142
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2143
+ * See the License for the specific language governing permissions and
2144
+ * limitations under the License.
2145
+ */
2146
+ /**
2147
+ * Default source selection: one video and one audio switching
2148
+ * set from the first render group, plus the event timelines the player opted into.
2149
+ */
2111
2150
  /** A track with its `role` inferred when the catalog leaves it out: MIME type, then video or audio fields. */
2112
2151
  function withRole(track) {
2113
2152
  if (track.role !== void 0) return track;
@@ -2170,9 +2209,20 @@ function startFirst(tracks) {
2170
2209
  const start = spaced.reduce((a, b) => b.keyframeSpacing < a.keyframeSpacing ? b : a);
2171
2210
  return [start, ...tracks.filter((t) => t !== start)];
2172
2211
  }
2173
- /** The default video and audio sets, in that order, with their start tracks first. */
2212
+ /**
2213
+ * The default video and audio sets, in that order, with their start tracks first. Of the sets
2214
+ * sharing an `altGroup` and `lang`, only those whose definition has the lowest priority are kept.
2215
+ */
2174
2216
  function selectMedia(tracks, options) {
2175
- const sets = mediaSets(tracks, options.probe);
2217
+ const all = mediaSets(tracks, options.probe);
2218
+ const key = (s) => s.tracks[0].altGroup === void 0 ? void 0 : setKey(s.tracks[0], 0);
2219
+ const rank = (s) => s.definition.priority ?? 100;
2220
+ const best = /* @__PURE__ */ new Map();
2221
+ for (const s of all) {
2222
+ const k = key(s);
2223
+ if (k !== void 0) best.set(k, Math.min(best.get(k) ?? Infinity, rank(s)));
2224
+ }
2225
+ const sets = all.filter((s) => key(s) === void 0 || rank(s) === best.get(key(s)));
2176
2226
  return [sets.find((s) => s.tracks[0].role === "video"), pickAudio(sets.filter((s) => s.tracks[0].role === "audio"), options.language)].filter((s) => s !== void 0).map((s) => ({
2177
2227
  ...s,
2178
2228
  tracks: startFirst(s.tracks)
@@ -2258,7 +2308,7 @@ var CatalogElement = class extends SourceElement {
2258
2308
  onIndependent: (payload) => this.#received(parseCatalog(payload, this.#parse)),
2259
2309
  onIncremental: (payload) => {
2260
2310
  if (!this.#catalog) throw new Error("A delta update arrived before any catalog");
2261
- this.#received(applyDelta(this.#catalog, payload, this.#parse));
2311
+ this.#received(applyDelta$1(this.#catalog, payload, this.#parse));
2262
2312
  },
2263
2313
  onStale: (reason) => this.#onStale(reason)
2264
2314
  });
@@ -2699,7 +2749,7 @@ function accessibleStart(track, timeline) {
2699
2749
  return timeline.timeToLocation(start);
2700
2750
  }
2701
2751
  /** The span `location` falls in, or the nearest one, and the location clamped into it. */
2702
- function clamp(location, spans) {
2752
+ function clamp$1(location, spans) {
2703
2753
  let best = {
2704
2754
  index: 0,
2705
2755
  location: spans[0].start,
@@ -3010,12 +3060,14 @@ var Delivery = class {
3010
3060
  #trackProperties(track, initData) {
3011
3061
  const duration = this.duration ?? (!track.isLive && track.trackDuration !== void 0 ? track.trackDuration / 1e3 : void 0);
3012
3062
  const latency = track.targetLatency ?? track.buffers?.target;
3063
+ const window = track.isLive ? track.accessibleWindowTime : void 0;
3013
3064
  return {
3014
3065
  track: renditionId(track, this.#context.catalog),
3015
3066
  mimeType: this.#packaging.mimeType(track),
3016
3067
  live: track.isLive,
3017
3068
  ...duration !== void 0 && { duration },
3018
3069
  ...latency !== void 0 && { targetLatency: latency / 1e3 },
3070
+ ...window !== void 0 && { accessibleWindow: window / 1e3 },
3019
3071
  ...this.#groupProperties(track),
3020
3072
  ...initData && { initData }
3021
3073
  };
@@ -3138,6 +3190,16 @@ var Delivery = class {
3138
3190
  const key = trackKey(track);
3139
3191
  const initData = this.#packaging.objectInitData(track, object);
3140
3192
  if (!initData && this.#packaging.initOnObjects(track) && this.#initFor !== key) return;
3193
+ const packet = this.#packaging.packet(track, object, initData ?? this.#properties?.initData);
3194
+ if (!packet) {
3195
+ const resume = new require_model.Location(object.location.group + 1n, 0n);
3196
+ this.#gaps.get(this.#current.accepted.requestId)?.push({
3197
+ from: object.location,
3198
+ resume
3199
+ });
3200
+ this.gap = true;
3201
+ return;
3202
+ }
3141
3203
  if (this.seeks > 0) {
3142
3204
  this.gap = false;
3143
3205
  await this.#answerSeeks("ok");
@@ -3157,7 +3219,7 @@ var Delivery = class {
3157
3219
  }
3158
3220
  await this.pad.write({
3159
3221
  type: "packet",
3160
- object
3222
+ object: packet
3161
3223
  });
3162
3224
  const previous = this.#last;
3163
3225
  this.#last = {
@@ -3166,7 +3228,7 @@ var Delivery = class {
3166
3228
  };
3167
3229
  this.delivered = true;
3168
3230
  if (previous?.location.group !== object.location.group || previous.track !== key) {
3169
- this.#recordTime(track, object);
3231
+ this.#recordTime(track, packet);
3170
3232
  await this.#setProperties(this.#groupProperties(track));
3171
3233
  }
3172
3234
  const changed = previous !== void 0 && previous.track !== key;
@@ -3585,7 +3647,7 @@ var Recovery = class {
3585
3647
  if (!location) return this.#delivery.failSeeks();
3586
3648
  let fetch = !track.isLive;
3587
3649
  if (this.#spans.length > 0) {
3588
- const clamped = clamp(mapLocation(location, track, this.#first, set), this.#spans);
3650
+ const clamped = clamp$1(mapLocation(location, track, this.#first, set), this.#spans);
3589
3651
  this.#span = clamped.index;
3590
3652
  location = mapLocation(clamped.location, this.#first, track, set);
3591
3653
  fetch = this.#spans[clamped.index].fetch;
@@ -3960,9 +4022,9 @@ var SwitchingSetSource = class extends SourceElement {
3960
4022
  constructor(context, options, plan = { spans: [] }) {
3961
4023
  super(context);
3962
4024
  this.options = options;
3963
- const start = context.tracks[0];
3964
4025
  this.#tracks = context.tracks;
3965
4026
  this.#selected = new Set(context.tracks.map((t) => this.#id(t)));
4027
+ const start = this.#start();
3966
4028
  this.pad = this.createPad("src", this.padCapabilities(start.role ?? "video"));
3967
4029
  this.#delivery = new Delivery(this.pad, context, options.requests, this);
3968
4030
  this.#delivery.duration = plan.duration;
@@ -4052,6 +4114,18 @@ var SwitchingSetSource = class extends SourceElement {
4052
4114
  this.#shown = shown;
4053
4115
  this.#switcher.upgrade();
4054
4116
  }
4117
+ /**
4118
+ * A live set starts at its middle bitrate, so ABR can move either way before it knows the link;
4119
+ * VOD, which gets no ABR controller, at its first track.
4120
+ */
4121
+ #start() {
4122
+ const first = this.#tracks[0];
4123
+ if (!first.isLive) return first;
4124
+ const heads = this.#tracks.filter((t) => this.#head(t) === t).sort((a, b) => bitrateOf(a) - bitrateOf(b));
4125
+ if (!heads.every((t) => bitrateOf(t) > 0)) return first;
4126
+ const middle = heads[heads.length - 1 >> 1];
4127
+ return ladderOf(middle, this.#tracks).reduce((a, b) => (b.keyframeSpacing ?? Infinity) < (a.keyframeSpacing ?? Infinity) ? b : a, middle);
4128
+ }
4055
4129
  /** The track `track`'s rendition stands for: the longest GoP of its ladder, which switches climb to. */
4056
4130
  #head(track) {
4057
4131
  return ladderOf(track, this.#tracks).reduce((a, b) => (b.keyframeSpacing ?? 0) > (a.keyframeSpacing ?? 0) ? b : a, track);
@@ -4061,10 +4135,13 @@ var SwitchingSetSource = class extends SourceElement {
4061
4135
  }
4062
4136
  /** `track` is the head of its ladder. */
4063
4137
  #rendition(track) {
4064
- return rendition(track, this.context.catalog, {
4065
- active: trackKey(track) === trackKey(this.#head(this.#recovery.active)),
4066
- selected: this.#selected.has(this.#id(track))
4067
- });
4138
+ return {
4139
+ ...rendition(track, this.context.catalog, {
4140
+ active: trackKey(track) === trackKey(this.#head(this.#recovery.active)),
4141
+ selected: this.#selected.has(this.#id(track))
4142
+ }),
4143
+ ladder: ladderOf(track, this.#tracks).map((t) => t.name)
4144
+ };
4068
4145
  }
4069
4146
  #id(track) {
4070
4147
  return renditionId(track, this.context.catalog);
@@ -4108,29 +4185,31 @@ async function planSource(context, options, element) {
4108
4185
  */
4109
4186
  /** The payload of the first box at `path`, each name nested in the previous one. */
4110
4187
  function findBox(data, path) {
4111
- const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
4112
- let [start, end] = [0, data.byteLength];
4188
+ let found = data;
4113
4189
  for (const name of path) {
4114
- let found = false;
4115
- while (start + 8 <= end) {
4116
- let size = view.getUint32(start);
4117
- let header = 8;
4118
- if (size === 1) {
4119
- if (start + 16 > end) return void 0;
4120
- size = Number(view.getBigUint64(start + 8));
4121
- header = 16;
4122
- } else if (size === 0) size = end - start;
4123
- if (size < header || start + size > end) return void 0;
4124
- if (String.fromCharCode(...data.subarray(start + 4, start + 8)) === name) {
4125
- [start, end] = [start + header, start + size];
4126
- found = true;
4127
- break;
4128
- }
4129
- start += size;
4130
- }
4190
+ found = [...children(found)].find((b) => b.type === name)?.body;
4131
4191
  if (!found) return void 0;
4132
4192
  }
4133
- return data.subarray(start, end);
4193
+ return found;
4194
+ }
4195
+ /** The boxes at the top level of `data`, up to the first malformed one. */
4196
+ function* children(data) {
4197
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
4198
+ for (let start = 0; start + 8 <= data.byteLength;) {
4199
+ let size = view.getUint32(start);
4200
+ let header = 8;
4201
+ if (size === 1) {
4202
+ if (start + 16 > data.byteLength) return;
4203
+ size = Number(view.getBigUint64(start + 8));
4204
+ header = 16;
4205
+ } else if (size === 0) size = data.byteLength - start;
4206
+ if (size < header || start + size > data.byteLength) return;
4207
+ yield {
4208
+ type: String.fromCharCode(...data.subarray(start + 4, start + 8)),
4209
+ body: data.subarray(start + header, start + size)
4210
+ };
4211
+ start += size;
4212
+ }
4134
4213
  }
4135
4214
  /** `moof/traf/tfdt` base media decode time, in timescale units. */
4136
4215
  function baseMediaDecodeTime(fragment) {
@@ -4229,6 +4308,9 @@ var CmafSource = class extends SwitchingSetSource {
4229
4308
  if (!object.payload) return void 0;
4230
4309
  return fragmentTime(object.payload, track.timescale ?? (initData && mediaTimescale(initData)));
4231
4310
  }
4311
+ packet(_track, object, _initData) {
4312
+ return object;
4313
+ }
4232
4314
  };
4233
4315
  // src/player/elements/cmaf/index.ts
4234
4316
  /**
@@ -4268,6 +4350,609 @@ function probeCmaf(identifiers) {
4268
4350
  if (packaging !== "cmaf" || role !== "video" && role !== "audio") return false;
4269
4351
  return identifiers["encryptionScheme"] === void 0 && identifiers["contentProtectionRefIDs"] === void 0;
4270
4352
  }
4353
+ // src/player/elements/locmaf/object.ts
4354
+ /**
4355
+ * Copyright 2026 The MOQtail Authors
4356
+ *
4357
+ * Licensed under the Apache License, Version 2.0 (the "License");
4358
+ * you may not use this file except in compliance with the License.
4359
+ * You may obtain a copy of the License at
4360
+ *
4361
+ * http://www.apache.org/licenses/LICENSE-2.0
4362
+ *
4363
+ * Unless required by applicable law or agreed to in writing, software
4364
+ * distributed under the License is distributed on an "AS IS" BASIS,
4365
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4366
+ * See the License for the specific language governing permissions and
4367
+ * limitations under the License.
4368
+ */
4369
+ /** The framing of a LOCMAF Object (draft-einarsson-moq-locmaf-01 §7–9): its elements and header fields. */
4370
+ /** A malformed object, or one that can't be decoded where it sits in its group. */
4371
+ var LocmafError = class extends Error {};
4372
+ /** Header field IDs (§10, Table 4). */
4373
+ const Field = {
4374
+ sampleSizes: 1,
4375
+ sampleDescriptionIndex: 2,
4376
+ sampleDurations: 3,
4377
+ defaultSampleDuration: 4,
4378
+ compositionTimeOffsets: 5,
4379
+ defaultSampleSize: 6,
4380
+ sampleFlags: 7,
4381
+ defaultSampleFlags: 8,
4382
+ initializationVector: 9,
4383
+ baseMediaDecodeTime: 10,
4384
+ subsampleCount: 11,
4385
+ firstSampleFlags: 12,
4386
+ bytesOfClearData: 13,
4387
+ sampleCount: 14,
4388
+ bytesOfProtectedData: 15,
4389
+ perSampleIVSize: 16,
4390
+ deleted: 27
4391
+ };
4392
+ const KNOWN = new Set(Object.values(Field).map(BigInt));
4393
+ const GEN_BOX = 1n;
4394
+ const FULL_HEADER = 2n;
4395
+ const DELTA_HEADER = 3n;
4396
+ const RAW_BOXES = 4n;
4397
+ /** @throws LocmafError when the object is malformed. */
4398
+ function parseObject(payload) {
4399
+ const buf = new require_model.FrozenByteBuffer(payload);
4400
+ const genBoxes = [];
4401
+ try {
4402
+ for (;;) {
4403
+ if (buf.remaining === 0) throw new LocmafError("The object ends before its header");
4404
+ const type = buf.getVI();
4405
+ if (type === GEN_BOX) genBoxes.push(genBox(buf));
4406
+ else if (type === FULL_HEADER || type === DELTA_HEADER) {
4407
+ const full = type === FULL_HEADER;
4408
+ return {
4409
+ genBoxes,
4410
+ full,
4411
+ fields: properties(buf.getBytes(length(buf)), full),
4412
+ mdat: payload.subarray(buf.offset)
4413
+ };
4414
+ } else if (type === RAW_BOXES && genBoxes.length === 0) return { raw: rawBoxes(payload.subarray(buf.offset)) };
4415
+ else throw new LocmafError(`Element type ${type} isn't allowed here`);
4416
+ }
4417
+ } catch (error) {
4418
+ if (error instanceof LocmafError) throw error;
4419
+ throw new LocmafError("The object is truncated", { cause: error });
4420
+ }
4421
+ }
4422
+ /** The vi64s of a list field, in order (§7.3). */
4423
+ function readList(bytes) {
4424
+ const buf = new require_model.FrozenByteBuffer(bytes);
4425
+ const values = [];
4426
+ try {
4427
+ while (buf.remaining > 0) values.push(buf.getVI());
4428
+ } catch (error) {
4429
+ throw new LocmafError("A list field is truncated", { cause: error });
4430
+ }
4431
+ return values;
4432
+ }
4433
+ /** The signed value of a zigzag vi64 (§7.4). */
4434
+ function unzigzag(z) {
4435
+ return z & 1n ? -(z + 1n) / 2n : z / 2n;
4436
+ }
4437
+ /** `box_size | box_name | payload` as the ISO box `uint32(4 + box_size) | box_name | payload` (§8.1, §8.3). */
4438
+ function genBox(buf) {
4439
+ const size = buf.getVI();
4440
+ if (size < 4n || size > 4294967291n) throw new LocmafError(`genBox size ${size} is out of range`);
4441
+ const body = buf.getBytes(Number(size));
4442
+ const box = new Uint8Array(4 + body.length);
4443
+ new DataView(box.buffer).setUint32(0, box.length);
4444
+ box.set(body, 4);
4445
+ return box;
4446
+ }
4447
+ function length(buf) {
4448
+ const value = buf.getVI();
4449
+ if (value > BigInt(buf.remaining)) throw new LocmafError(`A length of ${value} runs past the object`);
4450
+ return Number(value);
4451
+ }
4452
+ /** The known fields of a property block; unknown ones are skipped by their parity (§7.3). */
4453
+ function properties(block, full) {
4454
+ const buf = new require_model.FrozenByteBuffer(block);
4455
+ const seen = /* @__PURE__ */ new Set();
4456
+ const fields = /* @__PURE__ */ new Map();
4457
+ while (buf.remaining > 0) {
4458
+ const id = buf.getVI();
4459
+ if (seen.has(id)) throw new LocmafError(`Field ${id} repeats`);
4460
+ seen.add(id);
4461
+ const value = id % 2n === 0n ? buf.getVI() : buf.getBytes(length(buf));
4462
+ if (KNOWN.has(id)) fields.set(Number(id), value);
4463
+ }
4464
+ if (full && fields.has(Field.deleted)) throw new LocmafError("A full header lists deletions");
4465
+ if (!full && fields.has(Field.baseMediaDecodeTime)) throw new LocmafError("A delta header carries the BMDT");
4466
+ return fields;
4467
+ }
4468
+ /** Complete boxes, each with its actual 32-bit size, filling the rest of the object (§9.1, §18). */
4469
+ function rawBoxes(boxes) {
4470
+ if (boxes.length === 0) throw new LocmafError("A rawBoxes element is empty");
4471
+ const view = new DataView(boxes.buffer, boxes.byteOffset, boxes.byteLength);
4472
+ for (let at = 0; at < boxes.length;) {
4473
+ const size = at + 8 <= boxes.length ? view.getUint32(at) : 0;
4474
+ if (size < 8 || at + size > boxes.length) throw new LocmafError("rawBoxes holds an incomplete box");
4475
+ at += size;
4476
+ }
4477
+ return boxes;
4478
+ }
4479
+ // src/player/elements/locmaf/chunk.ts
4480
+ /** No real chunk comes close; it bounds what a header can make the receiver allocate (§18). */
4481
+ const MAX_SAMPLES = 1n << 16n;
4482
+ const SCALARS = [
4483
+ Field.sampleDescriptionIndex,
4484
+ Field.defaultSampleDuration,
4485
+ Field.defaultSampleSize,
4486
+ Field.defaultSampleFlags,
4487
+ Field.firstSampleFlags,
4488
+ Field.perSampleIVSize
4489
+ ];
4490
+ const CENC = [
4491
+ Field.initializationVector,
4492
+ Field.subsampleCount,
4493
+ Field.bytesOfClearData,
4494
+ Field.bytesOfProtectedData,
4495
+ Field.perSampleIVSize
4496
+ ];
4497
+ /** The in-group reference of one track: the previous chunk of its group, when it can be built on. */
4498
+ var Reference = class {
4499
+ #previous;
4500
+ /**
4501
+ * The effective values of the object at `location`, or the boxes of a rawBoxes object.
4502
+ * @throws LocmafError when it's malformed, or a delta with nothing to build on (§3, §9.3).
4503
+ */
4504
+ decode(location, payload, defaults) {
4505
+ const previous = this.#previous;
4506
+ const reference = previous?.location.group === location.group && previous.location.object + 1n === location.object ? previous : void 0;
4507
+ this.#previous = { location };
4508
+ const object = parseObject(payload);
4509
+ if ("raw" in object) return object.raw;
4510
+ if (!object.full && !reference?.fields) throw new LocmafError("A delta header has no in-group reference");
4511
+ const fields = object.full ? absolute(object.fields) : applyDelta(object.fields, reference.fields);
4512
+ const baseMediaDecodeTime = object.full ? fields.get(Field.baseMediaDecodeTime) : reference.nextBaseMediaDecodeTime;
4513
+ if (baseMediaDecodeTime >= 2n ** 64n) throw new LocmafError("The decode time overflows 64 bits");
4514
+ const chunk = effectiveValues(fields, defaults, {
4515
+ ...object,
4516
+ baseMediaDecodeTime
4517
+ });
4518
+ const next = baseMediaDecodeTime + chunk.durations.reduce((sum, d) => sum + BigInt(d), 0n);
4519
+ this.#previous = {
4520
+ location,
4521
+ fields,
4522
+ nextBaseMediaDecodeTime: next
4523
+ };
4524
+ return chunk;
4525
+ }
4526
+ };
4527
+ /** A full header's represented values (§11): absolute, except the zigzag ID 5. */
4528
+ function absolute(fields) {
4529
+ if (!fields.has(Field.sampleCount) || !fields.has(Field.baseMediaDecodeTime)) throw new LocmafError("A full header needs trunSampleCount and tfdtBaseMediaDecodeTime");
4530
+ const represented = /* @__PURE__ */ new Map();
4531
+ for (const [id, value] of fields) if (typeof value === "bigint" || id === Field.initializationVector) represented.set(id, value);
4532
+ else represented.set(id, id === Field.compositionTimeOffsets ? readList(value).map(unzigzag) : readList(value));
4533
+ return represented;
4534
+ }
4535
+ /** The reference with a delta header applied: deletions, then scalar and list deltas (§12). */
4536
+ function applyDelta(fields, reference) {
4537
+ const next = new Map(reference);
4538
+ const deleted = fields.get(Field.deleted);
4539
+ if (deleted instanceof Uint8Array) for (const id of readList(deleted)) next.delete(Number(id));
4540
+ for (const id of [Field.sampleCount, ...SCALARS]) {
4541
+ const delta = fields.get(id);
4542
+ if (delta === void 0) continue;
4543
+ const value = (next.get(id) ?? 0n) + unzigzag(delta);
4544
+ if (value < 0n) throw new LocmafError(`Field ${id} goes negative`);
4545
+ next.set(id, value);
4546
+ }
4547
+ const n = sampleCount(next);
4548
+ for (const id of [
4549
+ Field.sampleDurations,
4550
+ Field.sampleFlags,
4551
+ Field.subsampleCount
4552
+ ]) applyList(next, fields, id, n);
4553
+ applyList(next, fields, Field.sampleSizes, n === 0 ? 0 : n - 1);
4554
+ const subsamples = (next.get(Field.subsampleCount) ?? []).reduce((a, b) => a + b, 0n);
4555
+ if (subsamples > MAX_SAMPLES) throw new LocmafError(`${subsamples} subsamples is too many`);
4556
+ applyList(next, fields, Field.bytesOfClearData, Number(subsamples));
4557
+ applyList(next, fields, Field.bytesOfProtectedData, Number(subsamples));
4558
+ applyList(next, fields, Field.compositionTimeOffsets, n);
4559
+ const ivs = fields.get(Field.initializationVector);
4560
+ if (ivs) next.set(Field.initializationVector, ivs);
4561
+ return next;
4562
+ }
4563
+ /**
4564
+ * Element-wise deltas against the previous list, absolute past its end (§12.1.1). An inherited
4565
+ * list follows a shorter count by truncation; one too short for a longer count is malformed.
4566
+ */
4567
+ function applyList(next, fields, id, length) {
4568
+ const previous = next.get(id);
4569
+ const bytes = fields.get(id);
4570
+ if (!bytes) {
4571
+ if (previous && previous.length < length) throw new LocmafError(`Inherited field ${id} is too short`);
4572
+ if (previous) next.set(id, previous.slice(0, length));
4573
+ return;
4574
+ }
4575
+ const deltas = readList(bytes).map(unzigzag);
4576
+ if (deltas.length !== length) throw new LocmafError(`Field ${id} has ${deltas.length} entries, not ${length}`);
4577
+ const list = deltas.map((delta, i) => (previous?.[i] ?? 0n) + delta);
4578
+ if (id !== Field.compositionTimeOffsets && list.some((v) => v < 0n)) throw new LocmafError(`Field ${id} goes negative`);
4579
+ next.set(id, list);
4580
+ }
4581
+ /** The effective values from the represented fields, the CMAF Header and the object (§11.2, §15.1). */
4582
+ function effectiveValues(fields, defaults, object) {
4583
+ const n = sampleCount(fields);
4584
+ const scalar = (id, fallback) => {
4585
+ const value = fields.get(id);
4586
+ return value === void 0 ? fallback : uint(value, 32);
4587
+ };
4588
+ const list = (id, length) => {
4589
+ const values = fields.get(id);
4590
+ if (values && values.length !== length) throw new LocmafError(`Field ${id} has ${values.length} entries, not ${length}`);
4591
+ return values;
4592
+ };
4593
+ const durations = list(Field.sampleDurations, n)?.map((d) => uint(d, 32));
4594
+ const flags = list(Field.sampleFlags, n)?.map((f) => uint(f, 32));
4595
+ const firstFlags = fields.has(Field.firstSampleFlags) ? scalar(Field.firstSampleFlags, 0) : void 0;
4596
+ const defaultFlags = scalar(Field.defaultSampleFlags, defaults.sampleFlags);
4597
+ const ctos = list(Field.compositionTimeOffsets, n)?.map((c) => {
4598
+ if (c < -(2n ** 31n) || c >= 2n ** 31n) throw new LocmafError(`Composition time offset ${c} is out of range`);
4599
+ return Number(c);
4600
+ });
4601
+ const sizes = sampleSizes(fields, n, object.mdat.length, defaults);
4602
+ return {
4603
+ baseMediaDecodeTime: object.baseMediaDecodeTime,
4604
+ sampleDescriptionIndex: scalar(Field.sampleDescriptionIndex, defaults.sampleDescriptionIndex),
4605
+ durations: durations ?? Array(n).fill(scalar(Field.defaultSampleDuration, defaults.sampleDuration)),
4606
+ sizes,
4607
+ flags: flags ?? Array.from({ length: n }, (_, i) => i === 0 ? firstFlags ?? defaultFlags : defaultFlags),
4608
+ compositionTimeOffsets: ctos ?? Array(n).fill(0),
4609
+ ...cenc(fields, defaults, sizes),
4610
+ genBoxes: object.genBoxes,
4611
+ mdat: object.mdat
4612
+ };
4613
+ }
4614
+ /** Sample sizes (§11.2): the listed n − 1 and the rest of the mdat, a default, or the mdat for one sample. */
4615
+ function sampleSizes(fields, n, payload, defaults) {
4616
+ if (n === 0 && payload > 0) throw new LocmafError("A chunk without samples has an mdat payload");
4617
+ if (payload > 4294967287) throw new LocmafError("The mdat payload is too large");
4618
+ const listed = fields.get(Field.sampleSizes);
4619
+ if (listed) {
4620
+ if (listed.length !== Math.max(n - 1, 0)) throw new LocmafError(`${listed.length} sample sizes for ${n} samples`);
4621
+ const sizes = listed.map((s) => uint(s, 32));
4622
+ const sum = sizes.reduce((a, b) => a + b, 0);
4623
+ if (sum > payload) throw new LocmafError("The sample sizes exceed the mdat payload");
4624
+ return n === 0 ? [] : [...sizes, payload - sum];
4625
+ }
4626
+ const tfhd = fields.get(Field.defaultSampleSize);
4627
+ const size = tfhd !== void 0 ? uint(tfhd, 32) : n !== 1 && defaults.sampleSize !== 0 ? defaults.sampleSize : void 0;
4628
+ if (size !== void 0) {
4629
+ if (n * size !== payload) throw new LocmafError(`${n} samples of ${size} bytes don't fill ${payload}`);
4630
+ return Array(n).fill(size);
4631
+ }
4632
+ if (n === 1) return [payload];
4633
+ if (payload === 0) return Array(n).fill(0);
4634
+ throw new LocmafError(`No sample sizes for ${n} samples`);
4635
+ }
4636
+ /** CENC auxiliary information (§10.3, §13, §18), checked against the samples it describes. */
4637
+ function cenc(fields, defaults, sizes) {
4638
+ if (!defaults.isProtected && CENC.some((id) => fields.has(id))) throw new LocmafError("CENC fields on a track that isn’t protected");
4639
+ const n = sizes.length;
4640
+ const ivSize = fields.has(Field.perSampleIVSize) ? uint(fields.get(Field.perSampleIVSize), 8) : defaults.perSampleIVSize;
4641
+ const ivs = fields.get(Field.initializationVector) ?? /* @__PURE__ */ new Uint8Array();
4642
+ if (ivs.length > 0 ? ivs.length !== ivSize * n : ivSize > 0 && n > 0) throw new LocmafError(`${ivs.length} bytes of IVs for ${n} samples of ${ivSize}`);
4643
+ const counts = fields.get(Field.subsampleCount)?.map((c) => uint(c, 16));
4644
+ const clear = fields.get(Field.bytesOfClearData)?.map((c) => uint(c, 16)) ?? [];
4645
+ const protectedBytes = fields.get(Field.bytesOfProtectedData)?.map((p) => uint(p, 32)) ?? [];
4646
+ if (!counts) {
4647
+ if (clear.length > 0 || protectedBytes.length > 0) throw new LocmafError("Subsample bytes without counts");
4648
+ return {
4649
+ perSampleIVSize: ivSize,
4650
+ ivs
4651
+ };
4652
+ }
4653
+ const total = counts.reduce((a, b) => a + b, 0);
4654
+ if (counts.length !== n || clear.length !== total || protectedBytes.length !== total) throw new LocmafError("The subsample map doesn’t match the samples");
4655
+ let at = 0;
4656
+ counts.forEach((count, i) => {
4657
+ let covered = 0;
4658
+ for (const end = at + count; at < end; at++) covered += clear[at] + protectedBytes[at];
4659
+ if (count > 0 && covered !== sizes[i]) throw new LocmafError(`Subsamples cover ${covered} of ${sizes[i]} bytes`);
4660
+ });
4661
+ return {
4662
+ perSampleIVSize: ivSize,
4663
+ ivs,
4664
+ subsamples: {
4665
+ counts,
4666
+ clear,
4667
+ protected: protectedBytes
4668
+ }
4669
+ };
4670
+ }
4671
+ function sampleCount(fields) {
4672
+ const n = fields.get(Field.sampleCount);
4673
+ if (n === void 0 || n > MAX_SAMPLES) throw new LocmafError(`A sample count of ${n} can't be decoded`);
4674
+ return Number(n);
4675
+ }
4676
+ /** `value` as a number, when it fits an unsigned field of `bits`. */
4677
+ function uint(value, bits) {
4678
+ if (value >= 1n << BigInt(bits)) throw new LocmafError(`${value} doesn’t fit ${bits} bits`);
4679
+ return Number(value);
4680
+ }
4681
+ // src/player/elements/locmaf/init.ts
4682
+ /**
4683
+ * Copyright 2026 The MOQtail Authors
4684
+ *
4685
+ * Licensed under the Apache License, Version 2.0 (the "License");
4686
+ * you may not use this file except in compliance with the License.
4687
+ * You may obtain a copy of the License at
4688
+ *
4689
+ * http://www.apache.org/licenses/LICENSE-2.0
4690
+ *
4691
+ * Unless required by applicable law or agreed to in writing, software
4692
+ * distributed under the License is distributed on an "AS IS" BASIS,
4693
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4694
+ * See the License for the specific language governing permissions and
4695
+ * limitations under the License.
4696
+ */
4697
+ /** Bytes before the child boxes of a protected visual and audio sample entry (ISO 14496-12 12.1.3, 12.2.3). */
4698
+ const SAMPLE_ENTRY_FIELDS = {
4699
+ encv: 78,
4700
+ enca: 28
4701
+ };
4702
+ /** @throws LocmafError when `init` isn't a single-track CMAF Header with `trex`. */
4703
+ function trackDefaults(init) {
4704
+ const moov = findBox(init, ["moov"]);
4705
+ if (!moov || [...children(moov)].filter((b) => b.type === "trak").length !== 1) throw new LocmafError("The CMAF Header needs exactly one trak (§4.1)");
4706
+ const tkhd = view(findBox(moov, ["trak", "tkhd"]));
4707
+ const trex = view(findBox(moov, ["mvex", "trex"]));
4708
+ const trackIdAt = tkhd?.byteLength && tkhd.getUint8(0) === 1 ? 20 : 12;
4709
+ if (!tkhd || tkhd.byteLength < trackIdAt + 4 || !trex || trex.byteLength < 24) throw new LocmafError("The CMAF Header has no tkhd or trex");
4710
+ const tenc = view(protection(moov));
4711
+ return {
4712
+ trackId: tkhd.getUint32(trackIdAt),
4713
+ sampleDescriptionIndex: trex.getUint32(8),
4714
+ sampleDuration: trex.getUint32(12),
4715
+ sampleSize: trex.getUint32(16),
4716
+ sampleFlags: trex.getUint32(20),
4717
+ isProtected: tenc !== void 0 && tenc.byteLength >= 8 && tenc.getUint8(6) === 1,
4718
+ perSampleIVSize: tenc !== void 0 && tenc.byteLength >= 8 ? tenc.getUint8(7) : 0
4719
+ };
4720
+ }
4721
+ /** The `tenc` of the first sample entry, when it's a protected one. */
4722
+ function protection(moov) {
4723
+ const entry = findBox(moov, [
4724
+ "trak",
4725
+ "mdia",
4726
+ "minf",
4727
+ "stbl",
4728
+ "stsd"
4729
+ ])?.subarray(8);
4730
+ const skip = entry && entry.length >= 8 ? SAMPLE_ENTRY_FIELDS[String.fromCharCode(...entry.subarray(4, 8))] : void 0;
4731
+ if (skip === void 0) return void 0;
4732
+ return findBox(entry.subarray(8 + skip), [
4733
+ "sinf",
4734
+ "schi",
4735
+ "tenc"
4736
+ ]);
4737
+ }
4738
+ function view(data) {
4739
+ return data && new DataView(data.buffer, data.byteOffset, data.byteLength);
4740
+ }
4741
+ // src/player/elements/locmaf/moof.ts
4742
+ /** tfhd and trun flags (ISO 14496-12 8.8.7, 8.8.8). */
4743
+ const DEFAULT_BASE_IS_MOOF = 131072;
4744
+ const SAMPLE_DESCRIPTION_INDEX = 2;
4745
+ const DEFAULT_DURATION = 8;
4746
+ const DEFAULT_SIZE = 16;
4747
+ const DEFAULT_FLAGS = 32;
4748
+ const DATA_OFFSET = 1;
4749
+ const FIRST_SAMPLE_FLAGS = 4;
4750
+ const SAMPLE_DURATION = 256;
4751
+ const SAMPLE_SIZE = 512;
4752
+ const SAMPLE_FLAGS = 1024;
4753
+ const SAMPLE_CTO = 2048;
4754
+ /** moof header, mfhd and traf header, ahead of tfhd. */
4755
+ const TRAF_START = 32;
4756
+ /**
4757
+ * The canonical CMAF chunk (draft-einarsson-moq-locmaf-01 §15): genBoxes, moof, mdat.
4758
+ * @throws LocmafError when a sample's CENC auxiliary information doesn't fit `saiz`.
4759
+ */
4760
+ function canonicalChunk(chunk, defaults) {
4761
+ const n = chunk.sizes.length;
4762
+ const tfhdDefault = (values, trex) => values.length > 0 && allEqual(values) && values[0] !== trex ? values[0] : void 0;
4763
+ const durationsVary = !allEqual(chunk.durations);
4764
+ const sizesVary = !allEqual(chunk.sizes);
4765
+ const firstFlags = n > 1 && !allEqual(chunk.flags) && allEqual(chunk.flags.slice(1));
4766
+ const flagsVary = !allEqual(chunk.flags) && !firstFlags;
4767
+ const ctos = chunk.compositionTimeOffsets.some((c) => c !== 0);
4768
+ const optional = [
4769
+ [SAMPLE_DESCRIPTION_INDEX, chunk.sampleDescriptionIndex !== defaults.sampleDescriptionIndex ? chunk.sampleDescriptionIndex : void 0],
4770
+ [DEFAULT_DURATION, tfhdDefault(chunk.durations, defaults.sampleDuration)],
4771
+ [DEFAULT_SIZE, tfhdDefault(chunk.sizes, defaults.sampleSize)],
4772
+ [DEFAULT_FLAGS, flagsVary ? void 0 : tfhdDefault(chunk.flags.slice(firstFlags ? 1 : 0), defaults.sampleFlags)]
4773
+ ].filter((entry) => entry[1] !== void 0);
4774
+ const tfhd = box("tfhd", u32(optional.reduce((flags, [flag]) => flags | flag, DEFAULT_BASE_IS_MOOF), defaults.trackId, ...optional.map(([, value]) => value)));
4775
+ const tfdt = box("tfdt", u32(1 << 24), u64(chunk.baseMediaDecodeTime));
4776
+ const trFlags = DATA_OFFSET | (firstFlags ? FIRST_SAMPLE_FLAGS : 0) | (durationsVary ? SAMPLE_DURATION : 0) | (sizesVary ? SAMPLE_SIZE : 0) | (flagsVary ? SAMPLE_FLAGS : 0) | (ctos ? SAMPLE_CTO : 0);
4777
+ const version = chunk.compositionTimeOffsets.some((c) => c < 0) ? 1 : 0;
4778
+ const records = chunk.sizes.flatMap((size, i) => [
4779
+ ...durationsVary ? [chunk.durations[i]] : [],
4780
+ ...sizesVary ? [size] : [],
4781
+ ...flagsVary ? [chunk.flags[i]] : [],
4782
+ ...ctos ? [chunk.compositionTimeOffsets[i]] : []
4783
+ ]);
4784
+ const trun = box("trun", u32(version << 24 | trFlags, n, 0, ...firstFlags ? [chunk.flags[0]] : [], ...records));
4785
+ const traf = [
4786
+ tfhd,
4787
+ tfdt,
4788
+ trun,
4789
+ ...encryption(chunk, TRAF_START + tfhd.length + tfdt.length + trun.length)
4790
+ ];
4791
+ const moof = box("moof", box("mfhd", u32(0, 0)), box("traf", ...traf));
4792
+ new DataView(moof.buffer).setUint32(TRAF_START + tfhd.length + tfdt.length + 16, moof.length + 8);
4793
+ return concat(...chunk.genBoxes, moof, u32(8 + chunk.mdat.length), type("mdat"), chunk.mdat);
4794
+ }
4795
+ /** saiz, saio and senc (§15.8), when the chunk has CENC auxiliary information; `at` is where saiz starts in the moof. */
4796
+ function encryption(chunk, at) {
4797
+ const { perSampleIVSize: ivSize, subsamples } = chunk;
4798
+ if (ivSize === 0 && !subsamples) return [];
4799
+ const n = chunk.sizes.length;
4800
+ const auxSizes = chunk.sizes.map((_, i) => ivSize + (subsamples ? 2 + 6 * subsamples.counts[i] : 0));
4801
+ if (auxSizes.some((size) => size > 255)) throw new LocmafError("CENC auxiliary information exceeds saiz");
4802
+ const uniform = allEqual(auxSizes);
4803
+ const saiz = box("saiz", u32(0), new Uint8Array([uniform ? auxSizes[0] ?? 0 : 0]), u32(n), ...uniform ? [] : [new Uint8Array(auxSizes)]);
4804
+ const saio = box("saio", u32(0, 1, at + saiz.length + 20 + 16));
4805
+ const entries = [];
4806
+ let subsample = 0;
4807
+ for (let i = 0; i < n; i++) {
4808
+ entries.push(chunk.ivs.subarray(i * ivSize, (i + 1) * ivSize));
4809
+ if (!subsamples) continue;
4810
+ const count = subsamples.counts[i];
4811
+ const map = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(2 + 6 * count));
4812
+ map.setUint16(0, count);
4813
+ for (let j = 0; j < count; j++, subsample++) {
4814
+ map.setUint16(2 + 6 * j, subsamples.clear[subsample]);
4815
+ map.setUint32(4 + 6 * j, subsamples.protected[subsample]);
4816
+ }
4817
+ entries.push(new Uint8Array(map.buffer));
4818
+ }
4819
+ return [
4820
+ saiz,
4821
+ saio,
4822
+ box("senc", u32(subsamples ? 2 : 0, n), ...entries)
4823
+ ];
4824
+ }
4825
+ function allEqual(list) {
4826
+ return list.every((v) => v === list[0]);
4827
+ }
4828
+ function box(name, ...parts) {
4829
+ return concat(u32(8 + parts.reduce((size, part) => size + part.length, 0)), type(name), ...parts);
4830
+ }
4831
+ /** Big-endian 32-bit words; a negative one is written in two's complement. */
4832
+ function u32(...words) {
4833
+ const out = new Uint8Array(4 * words.length);
4834
+ const view = new DataView(out.buffer);
4835
+ words.forEach((word, i) => view.setUint32(4 * i, word >>> 0));
4836
+ return out;
4837
+ }
4838
+ function u64(value) {
4839
+ const out = /* @__PURE__ */ new Uint8Array(8);
4840
+ new DataView(out.buffer).setBigUint64(0, value);
4841
+ return out;
4842
+ }
4843
+ function type(name) {
4844
+ return new TextEncoder().encode(name);
4845
+ }
4846
+ function concat(...parts) {
4847
+ const out = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
4848
+ let at = 0;
4849
+ for (const part of parts) {
4850
+ out.set(part, at);
4851
+ at += part.length;
4852
+ }
4853
+ return out;
4854
+ }
4855
+ // src/player/elements/locmaf/source.ts
4856
+ /**
4857
+ * Copyright 2026 The MOQtail Authors
4858
+ *
4859
+ * Licensed under the Apache License, Version 2.0 (the "License");
4860
+ * you may not use this file except in compliance with the License.
4861
+ * You may obtain a copy of the License at
4862
+ *
4863
+ * http://www.apache.org/licenses/LICENSE-2.0
4864
+ *
4865
+ * Unless required by applicable law or agreed to in writing, software
4866
+ * distributed under the License is distributed on an "AS IS" BASIS,
4867
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4868
+ * See the License for the specific language governing permissions and
4869
+ * limitations under the License.
4870
+ */
4871
+ /** `LocmafSource`: a switching set source for LOCMAF tracks, whose pad carries the CMAF they rebuild to. */
4872
+ /** CMAF init data and timing, with each object rebuilt into its CMAF chunk (draft-einarsson-moq-locmaf-01 §16). */
4873
+ var LocmafSource = class extends CmafSource {
4874
+ #references = /* @__PURE__ */ new Map();
4875
+ #defaults;
4876
+ /** The group a rejected object was last reported for. */
4877
+ #reported;
4878
+ packet(track, object, initData) {
4879
+ const key = trackKey(track);
4880
+ const reference = this.#references.get(key) ?? new Reference();
4881
+ this.#references.set(key, reference);
4882
+ try {
4883
+ if (!initData) throw new LocmafError("No CMAF Header to rebuild the chunk with");
4884
+ const defaults = this.#defaultsOf(initData);
4885
+ const decoded = reference.decode(object.location, object.payload, defaults);
4886
+ const payload = decoded instanceof Uint8Array ? decoded : canonicalChunk(decoded, defaults);
4887
+ return require_model.MoqtObject.newWithPayload(object.fullTrackName, object.location, object.publisherPriority, object.objectForwardingPreference, object.subgroupId, object.properties, payload);
4888
+ } catch (error) {
4889
+ if (!(error instanceof LocmafError)) throw error;
4890
+ this.#report(key, object, error);
4891
+ return;
4892
+ }
4893
+ }
4894
+ /** The CMAF Header parameters of `init`, parsed once per header. */
4895
+ #defaultsOf(init) {
4896
+ if (this.#defaults?.init !== init) this.#defaults = {
4897
+ init,
4898
+ defaults: trackDefaults(init)
4899
+ };
4900
+ return this.#defaults.defaults;
4901
+ }
4902
+ /** A warning for the first object of a group that can't be rebuilt; the rest of it fails the same way. */
4903
+ #report(track, object, cause) {
4904
+ const group = `${track}|${object.location.group}`;
4905
+ if (this.#reported === group) return;
4906
+ this.#reported = group;
4907
+ const message = `LOCMAF object ${object.location.group}.${object.location.object} dropped: ${cause.message}`;
4908
+ this.context.player.emit("warning", new PlayerError("MEDIA_FAILURE", message, {
4909
+ element: "locmaf",
4910
+ cause
4911
+ }));
4912
+ }
4913
+ };
4914
+ // src/player/elements/locmaf/index.ts
4915
+ /**
4916
+ * Copyright 2026 The MOQtail Authors
4917
+ *
4918
+ * Licensed under the Apache License, Version 2.0 (the "License");
4919
+ * you may not use this file except in compliance with the License.
4920
+ * You may obtain a copy of the License at
4921
+ *
4922
+ * http://www.apache.org/licenses/LICENSE-2.0
4923
+ *
4924
+ * Unless required by applicable law or agreed to in writing, software
4925
+ * distributed under the License is distributed on an "AS IS" BASIS,
4926
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4927
+ * See the License for the specific language governing permissions and
4928
+ * limitations under the License.
4929
+ */
4930
+ /** The LOCMAF packaging version this element decodes (draft-einarsson-moq-locmaf-01 §5). */
4931
+ const LOCMAF_VERSION = "0.3";
4932
+ /**
4933
+ * The built-in media source for a LOCMAF switching set. It rebuilds CMAF chunks, so its pad
4934
+ * carries CMAF. The player registers it, and elements reach it through `context.probe()`. Its
4935
+ * lower priority prefers it over a CMAF set of the same media, since LOCMAF has less overhead.
4936
+ */
4937
+ const Locmaf = defineElement({
4938
+ type: "source",
4939
+ name: "locmaf",
4940
+ priority: 90,
4941
+ capabilities: [cmafCapabilities("out", "video"), cmafCapabilities("out", "audio")],
4942
+ provides: [MEDIA_SOURCE],
4943
+ probe: probeLocmaf,
4944
+ init: async (context, options) => new LocmafSource(context, options ?? {}, await planSource(context, options, "locmaf"))
4945
+ });
4946
+ /**
4947
+ * Accepts an unencrypted LOCMAF `video` or `audio` track of a version it decodes: a receiver
4948
+ * must not subscribe to another (§5). Encryption is out of scope, as for CMAF.
4949
+ */
4950
+ function probeLocmaf(identifiers) {
4951
+ const { packaging, role } = identifiers;
4952
+ if (packaging !== "locmaf" || role !== "video" && role !== "audio") return false;
4953
+ if (identifiers["locmafVersion"] !== LOCMAF_VERSION) return false;
4954
+ return identifiers["encryptionScheme"] === void 0 && identifiers["contentProtectionRefIDs"] === void 0;
4955
+ }
4271
4956
  // src/player/elements/saptimeline/index.ts
4272
4957
  /**
4273
4958
  * Copyright 2026 The MOQtail Authors
@@ -4317,6 +5002,7 @@ function isSapData(data, startsGroup) {
4317
5002
  const BUILT_IN_SOURCES = [
4318
5003
  CatalogSource,
4319
5004
  Cmaf,
5005
+ Locmaf,
4320
5006
  MediaTimeline,
4321
5007
  defineElement({
4322
5008
  type: "source",
@@ -4425,9 +5111,26 @@ function gapJumpTarget(currentTime, buffered, live, liveEdgeDelay) {
4425
5111
  if (length >= STALL_THRESHOLD$1 && length >= liveEdgeDelay) return start;
4426
5112
  }
4427
5113
  }
5114
+ /** How long playback may sit still with data ahead before a nudge, in seconds. */
5115
+ const NUDGE_AFTER = 1;
5116
+ /** The first nudge; each further one at the same spot doubles. */
5117
+ const NUDGE = .1;
5118
+ /**
5119
+ * Where to nudge playback stuck at `currentTime` inside a range for `stuckFor` seconds after
5120
+ * `attempts` nudges, or `undefined` to wait. Data after a hole can start without its keyframe,
5121
+ * so the decoder waits on frames that never come although the range says data is there; a jump
5122
+ * past them gets it going (hls.js does the same). Doubling reaches a GoP away in a few tries.
5123
+ */
5124
+ function nudgeTarget(currentTime, buffered, stuckFor, attempts) {
5125
+ const index = rangeAt(currentTime, buffered);
5126
+ if (index === -1 || stuckFor < NUDGE_AFTER) return void 0;
5127
+ const ahead = buffered.end(index) - currentTime;
5128
+ if (ahead < STALL_THRESHOLD$1) return void 0;
5129
+ return currentTime + Math.min(NUDGE * 2 ** attempts, ahead - STALL_THRESHOLD$1);
5130
+ }
4428
5131
  /** WebKit rounds `currentTime`, so a jump to a range's start can land a hair before it. */
4429
5132
  const START_TOLERANCE = .001;
4430
- /** Index of the range containing `time`, or -1. */
5133
+ /** @public Index of the range containing `time`, or -1. */
4431
5134
  function rangeAt(time, ranges) {
4432
5135
  for (let i = 0; i < ranges.length; i++) if (ranges.start(i) - START_TOLERANCE <= time && time <= ranges.end(i)) return i;
4433
5136
  return -1;
@@ -4456,15 +5159,17 @@ function vodDuration(pads) {
4456
5159
  return ends.length > 0 ? Math.max(...ends) : void 0;
4457
5160
  }
4458
5161
  /**
4459
- * Live: from the timeline start, else the buffered start, to the live edge minus the target
4460
- * latency, so seeking to the end never lands right at the edge (proposal 0007).
5162
+ * Live: from the timeline start, else the buffered start, no earlier than the accessible window
5163
+ * before the live edge (MSF 5.2.46), to the live edge minus the target latency, so seeking to the
5164
+ * end never lands right at the edge (proposal 0007).
4461
5165
  */
4462
5166
  function liveSeekable(buffered, pads) {
4463
5167
  const ranges = pads.flatMap((p) => p.seekable ?? []);
4464
5168
  const last = buffered.length - 1;
4465
5169
  if (ranges.length === 0 && last < 0) return void 0;
4466
- const start = ranges.length > 0 ? Math.max(...ranges.map((r) => r.start)) : buffered.start(0);
4467
5170
  const edge = Math.max(...ranges.map((r) => r.end), last >= 0 ? buffered.end(last) : -Infinity);
5171
+ const windows = pads.flatMap((p) => p.accessibleWindow ?? []);
5172
+ const start = Math.max(ranges.length > 0 ? Math.max(...ranges.map((r) => r.start)) : buffered.start(0), windows.length > 0 ? edge - Math.max(...windows) : -Infinity);
4468
5173
  return {
4469
5174
  start,
4470
5175
  end: Math.max(start, edge - targetLatency(pads))
@@ -4657,6 +5362,7 @@ const RELAYED_EVENTS = [
4657
5362
  "stalled",
4658
5363
  "waiting",
4659
5364
  "timeupdate",
5365
+ "seeking",
4660
5366
  "seeked",
4661
5367
  "ended"
4662
5368
  ];
@@ -4686,6 +5392,12 @@ var MSESink = class extends SinkElement {
4686
5392
  #live = false;
4687
5393
  /** The live seekable range last set. */
4688
5394
  #seekable;
5395
+ /** Where playback last sat still, since when (ms), and the nudges tried there. */
5396
+ #stuck = {
5397
+ time: NaN,
5398
+ since: 0,
5399
+ attempts: 0
5400
+ };
4689
5401
  /** Set once playback has its start position; a rebuild clears it. */
4690
5402
  #started = false;
4691
5403
  /** Where playback continues after a rebuild, instead of the start position. */
@@ -4753,6 +5465,10 @@ var MSESink = class extends SinkElement {
4753
5465
  if (!this.#live || !this.#seekable) return NaN;
4754
5466
  return liveEdgeStart(this.#seekable.end, this.#properties());
4755
5467
  }
5468
+ get dvrRange() {
5469
+ const windowed = this.#properties().some((p) => p.accessibleWindow !== void 0);
5470
+ return this.#live && windowed ? this.#seekable : void 0;
5471
+ }
4756
5472
  setPlaybackRate(rate) {
4757
5473
  this.#video.playbackRate = rate;
4758
5474
  }
@@ -4979,19 +5695,45 @@ var MSESink = class extends SinkElement {
4979
5695
  if (video.seeking) return this.#unstrand();
4980
5696
  const target = gapJumpTarget(video.currentTime, video.buffered, this.#live, this.#options.liveEdgeDelay);
4981
5697
  if (target !== void 0 && target > video.currentTime) this.#seekTracker.jump(target);
5698
+ else this.#unstrand();
5699
+ }
5700
+ /** Playback stranded where nothing will move it on: outside the data, or stuck inside it. */
5701
+ #unstrand() {
5702
+ const { currentTime, buffered } = this.#video;
5703
+ if (rangeAt(currentTime, buffered) === -1) this.#jumpToData(currentTime, buffered);
5704
+ else this.#nudgeStuck(currentTime, buffered);
4982
5705
  }
4983
5706
  /**
4984
5707
  * A seek that landed just before the data never completes: a group located a little late, or
4985
5708
  * tracks whose data starts at different times. Once no upstream seek is pending and every
4986
5709
  * buffer has data past it, nothing will fill the spot, so it jumps to where the data starts.
4987
5710
  */
4988
- #unstrand() {
4989
- const time = this.#video.currentTime;
4990
- const buffered = this.#video.buffered;
4991
- if (rangeAt(time, buffered) !== -1) return;
5711
+ #jumpToData(time, buffered) {
4992
5712
  for (const state of this.#pads.values()) if (state.seeks > 0 || !state.queue || (bufferedEnd(state.queue.buffer) ?? 0) <= time) return;
4993
5713
  for (let i = 0; i < buffered.length; i++) if (buffered.start(i) > time) return this.#seekTracker.jump(buffered.start(i));
4994
5714
  }
5715
+ /** Playback sitting still inside the data, past a hole whose data starts without its keyframe (`nudgeTarget`). */
5716
+ #nudgeStuck(time, buffered) {
5717
+ const video = this.#video;
5718
+ const now = performance.now();
5719
+ const previous = this.#stuck;
5720
+ if (video.paused || video.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA || time !== previous.time) {
5721
+ this.#stuck = {
5722
+ time,
5723
+ since: now,
5724
+ attempts: time === previous.time ? previous.attempts : 0
5725
+ };
5726
+ return;
5727
+ }
5728
+ const target = nudgeTarget(time, buffered, (now - previous.since) / 1e3, previous.attempts);
5729
+ if (target === void 0) return;
5730
+ this.#stuck = {
5731
+ time: target,
5732
+ since: now,
5733
+ attempts: previous.attempts + 1
5734
+ };
5735
+ this.#seekTracker.jump(target);
5736
+ }
4995
5737
  /**
4996
5738
  * After a switch, the old track's data plays out up to the new track's first group. Once
4997
5739
  * playback gets there, everything before it is removed, so a seek back never shows the old
@@ -5045,8 +5787,8 @@ var MSESink = class extends SinkElement {
5045
5787
  /**
5046
5788
  * Live only. Native `seekable` is the union of the live range and `buffered` (MSE 10.1), so its
5047
5789
  * end stays at the buffered end; `liveEdgeStart` is taken from this range. The live range is set
5048
- * only from a media timeline: without one, `seekable` starts at 0, and seeks before the buffer
5049
- * reach the relay's cache.
5790
+ * only from a media timeline or an accessible window: without either, `seekable` starts at 0,
5791
+ * and seeks before the buffer reach the relay's cache.
5050
5792
  */
5051
5793
  #updateSeekable() {
5052
5794
  const source = this.#source;
@@ -5055,7 +5797,7 @@ var MSESink = class extends SinkElement {
5055
5797
  const range = liveSeekable(this.#video.buffered, properties);
5056
5798
  if (!range || range.start === this.#seekable?.start && range.end === this.#seekable.end) return;
5057
5799
  this.#seekable = range;
5058
- if (properties.some((p) => p.seekable)) source.setLiveSeekableRange(range.start, range.end);
5800
+ if (properties.some((p) => p.seekable || p.accessibleWindow !== void 0)) source.setLiveSeekableRange(range.start, range.end);
5059
5801
  }
5060
5802
  #properties() {
5061
5803
  return [...this.#pads.values()].map((s) => s.properties);
@@ -5295,11 +6037,29 @@ async function open(s, origin, options) {
5295
6037
  ...transport.protocols && { protocols: [...transport.protocols] }
5296
6038
  } }
5297
6039
  });
5298
- client.on("sessionterminated", () => reconnect(s, client, origin, options));
5299
- await client.init();
6040
+ let next = origin;
6041
+ let left = false;
6042
+ client.on("goaway", (goaway) => {
6043
+ next = goaway.newSessionUri ?? origin;
6044
+ left = true;
6045
+ client.disconnect("GOAWAY");
6046
+ });
6047
+ client.on("sessionterminated", () => reconnect(s, client, next, options));
6048
+ await client.init().catch((error) => {
6049
+ if (!left) throw error;
6050
+ });
6051
+ if (left) throw new Moved(next);
5300
6052
  s.client = client;
5301
6053
  return client;
5302
6054
  }
6055
+ /** A GOAWAY arrived while the session was being set up; the next attempt goes to `uri`. */
6056
+ var Moved = class extends Error {
6057
+ uri;
6058
+ constructor(uri) {
6059
+ super(`GOAWAY during setup, moving to ${uri}`);
6060
+ this.uri = uri;
6061
+ }
6062
+ };
5303
6063
  /** Recreates a lost session for every player, or fails them all with `SESSION_LOST`. */
5304
6064
  function reconnect(s, client, origin, options) {
5305
6065
  if (s.disposing || s.client !== client) return;
@@ -5320,15 +6080,17 @@ function reconnect(s, client, origin, options) {
5320
6080
  async function retry(s, origin, options, onAttempt) {
5321
6081
  const signal = s.abort.signal;
5322
6082
  const attempts = options.reconnectAttempts ?? 5;
6083
+ let target = origin;
5323
6084
  for (let failed = 0;;) {
5324
6085
  onAttempt?.(failed + 1);
5325
6086
  await untilAvailable(signal);
5326
6087
  try {
5327
- return await open(s, origin, options);
6088
+ return await open(s, target, options);
5328
6089
  } catch (cause) {
5329
6090
  signal.throwIfAborted();
6091
+ if (cause instanceof Moved) target = cause.uri;
5330
6092
  if (!available()) continue;
5331
- if (++failed >= attempts) throw new PlayerError("SESSION_LOST", `Could not connect to ${origin}`, { cause });
6093
+ if (++failed >= attempts) throw new PlayerError("SESSION_LOST", `Could not connect to ${target}`, { cause });
5332
6094
  await sleep(backoffDelay(failed - 1), signal);
5333
6095
  }
5334
6096
  }
@@ -5860,6 +6622,55 @@ function isPinned(source) {
5860
6622
  const renditions = source.getRenditions();
5861
6623
  return renditions.length > 1 && renditions.filter((r) => r.selected).length === 1;
5862
6624
  }
6625
+ // src/player/follow.ts
6626
+ const decoder = new TextDecoder();
6627
+ /**
6628
+ * @public
6629
+ * Runs `attach` on the player's current client and on every later one (reconnects replace it),
6630
+ * calling the cleanup `attach` returned for the one before. Returns the function that stops.
6631
+ */
6632
+ function eachClient(player, attach) {
6633
+ let detach;
6634
+ const use = (client) => {
6635
+ detach?.();
6636
+ detach = attach(client);
6637
+ };
6638
+ if (player.client) use(player.client);
6639
+ player.on("client", use);
6640
+ return () => {
6641
+ player.off("client", use);
6642
+ detach?.();
6643
+ };
6644
+ }
6645
+ /**
6646
+ * @public
6647
+ * Calls `listener` with each incoming data event of the player's client, across reconnects, with
6648
+ * the name of the track its stream carries and the stream's header. A stream can open before the
6649
+ * response naming its track, so `track` stays undefined until a later event of that stream.
6650
+ * Streams opened before the call are skipped. Returns the function that stops listening.
6651
+ */
6652
+ function followData(player, listener) {
6653
+ const streams = /* @__PURE__ */ new Map();
6654
+ let client;
6655
+ const onData = (event) => {
6656
+ if (event.direction !== "in") return;
6657
+ if (event.kind === "header") streams.set(event.streamId, { header: event });
6658
+ const stream = streams.get(event.streamId);
6659
+ if (!stream) return;
6660
+ if (event.kind === "end") streams.delete(event.streamId);
6661
+ if (stream.track === void 0) {
6662
+ const name = client?.trackNameOf(stream.header);
6663
+ if (name) stream.track = decoder.decode(name.name);
6664
+ }
6665
+ listener(event, stream.track, stream.header);
6666
+ };
6667
+ return eachClient(player, (next) => {
6668
+ client = next;
6669
+ streams.clear();
6670
+ next.on("dataevent", onData);
6671
+ return () => next.off("dataevent", onData);
6672
+ });
6673
+ }
5863
6674
  // src/player/plugins/buffer/live.ts
5864
6675
  const CATCHUP_RATE = 1.1;
5865
6676
  /** How far the forward buffer may stray from its goal before the rate changes. */
@@ -5908,6 +6719,8 @@ var LiveBufferController = class {
5908
6719
  #timeline;
5909
6720
  /** Set once the controller changed the rate, so `detach()` gives 1 back. */
5910
6721
  #adjusted = false;
6722
+ /** Cleared by a seek behind the live edge, set again by one to it (proposal 0007). */
6723
+ #following = true;
5911
6724
  constructor(catchupRate, targetLatency) {
5912
6725
  this.#catchupRate = catchupRate;
5913
6726
  this.#targetLatency = targetLatency;
@@ -5922,6 +6735,7 @@ var LiveBufferController = class {
5922
6735
  player.on("catalog", this.#refresh);
5923
6736
  player.on("renditionchange", this.#refresh);
5924
6737
  sink.addEventListener("timeupdate", () => this.#tick(sink), { signal: abort.signal });
6738
+ sink.addEventListener("seeking", () => this.#seeking(sink), { signal: abort.signal });
5925
6739
  this.#refresh();
5926
6740
  }
5927
6741
  detach() {
@@ -5933,6 +6747,7 @@ var LiveBufferController = class {
5933
6747
  attached.player.off("renditionchange", this.#refresh);
5934
6748
  if (this.#adjusted) attached.sink.setPlaybackRate(1);
5935
6749
  this.#adjusted = false;
6750
+ this.#following = true;
5936
6751
  this.#targets = void 0;
5937
6752
  this.#timeline = void 0;
5938
6753
  }
@@ -5951,8 +6766,18 @@ var LiveBufferController = class {
5951
6766
  if (this.#attached === attached) this.#timeline = timeline;
5952
6767
  });
5953
6768
  };
6769
+ /**
6770
+ * Where a seek lands decides, whoever made it: the controller's and the sink's own jumps land at
6771
+ * the edge, a viewer's seek back leaves the rate at 1 until a seek to the edge (the Live button).
6772
+ */
6773
+ #seeking(sink) {
6774
+ this.#following = !(sink.currentTime < sink.liveEdgeStart);
6775
+ if (this.#following || !this.#adjusted) return;
6776
+ sink.setPlaybackRate(1);
6777
+ this.#adjusted = false;
6778
+ }
5954
6779
  #tick(sink) {
5955
- if (sink.paused || sink.seeking) return;
6780
+ if (sink.paused || sink.seeking || !this.#following) return;
5956
6781
  const { currentTime, buffered } = sink;
5957
6782
  const range = rangeAt(currentTime, buffered);
5958
6783
  if (range === -1) return;
@@ -6023,12 +6848,895 @@ const liveBuffer = definePlugin({
6023
6848
  item: controller
6024
6849
  }]
6025
6850
  });
6851
+ // src/player/plugins/abr/features.ts
6852
+ /** @public What the controller does with a tick. */
6853
+ const Action = {
6854
+ Down: 0,
6855
+ Stay: 1,
6856
+ Up: 2,
6857
+ Probe: 3
6858
+ };
6859
+ /** Seconds of forward buffer below which playback is about to stall. */
6860
+ const LOW_BUFFER = .5;
6861
+ /** A switch up goes to the highest rendition within this share of the probe's estimate. */
6862
+ const UP_MARGIN = .9;
6863
+ /** A switch down goes to the highest rendition within this share of `throughput`. */
6864
+ const DOWN_MARGIN = .8;
6865
+ /** Seconds without trouble or probes after which the probe backoff starts over. */
6866
+ const STABLE_RESET = 30;
6867
+ /** Seconds measured after a switch settled before the next decision. */
6868
+ const SETTLE_MEASURE = 1;
6869
+ /** The model's inputs, in order. Only their hash travels with a model. */
6870
+ const FEATURES = [
6871
+ "fwd",
6872
+ "rate",
6873
+ "stall",
6874
+ "qpos",
6875
+ "gap_up",
6876
+ "gap_dn",
6877
+ "recv",
6878
+ "arrival",
6879
+ "probe",
6880
+ "probe_age",
6881
+ "probe_busy",
6882
+ "since_sw",
6883
+ "gop"
6884
+ ];
6885
+ /** Seconds before probing again after 1, 2, and 3 or more probes in a row that found no room. */
6886
+ const PROBE_BACKOFF = [
6887
+ 5,
6888
+ 10,
6889
+ 15
6890
+ ];
6891
+ /** FNV-1a over the comma-joined feature names. */
6892
+ function featuresHash() {
6893
+ let hash = 2166136261;
6894
+ for (const byte of new TextEncoder().encode(FEATURES.join(","))) hash = Math.imul(hash ^ byte, 16777619) >>> 0;
6895
+ return hash;
6896
+ }
6897
+ /**
6898
+ * The model's inputs. Every one is a ratio, a log ratio, or a clipped duration, so none depends on
6899
+ * the ladder's bitrates or the link's absolute speed.
6900
+ */
6901
+ function features(o) {
6902
+ const { ladder, requested: k } = o;
6903
+ const top = ladder.length - 1;
6904
+ const bitrate = ladder[k];
6905
+ return [
6906
+ Math.log1p(clamp(o.forwardBuffer, 0, 30)),
6907
+ o.playbackRate - 1,
6908
+ clamp(o.stalledTime / 2, 0, 1),
6909
+ top > 0 ? Math.log(bitrate / ladder[0]) / Math.log(ladder[top] / ladder[0]) : 1,
6910
+ k < top ? Math.log(ladder[k + 1] / bitrate) : 0,
6911
+ k > 0 ? Math.log(bitrate / ladder[k - 1]) : 0,
6912
+ clamp(o.receivedBytes * 8 / 2 / o.activeBitrate, 0, 4),
6913
+ clamp(o.arrivalRate, 0, 4),
6914
+ o.probeEstimate === null ? 0 : clamp(Math.log(Math.max(o.probeEstimate, 1) * 8 / bitrate), -3, 3),
6915
+ o.probeAge === null ? 1 : clamp(o.probeAge / 30, 0, 1),
6916
+ o.probing ? 1 : 0,
6917
+ clamp(o.sinceSwitch / 10, 0, 1),
6918
+ o.groupInterval === null ? .25 : clamp(o.groupInterval, 0, 4) / 4
6919
+ ];
6920
+ }
6921
+ /**
6922
+ * Which actions are allowed, by `Action`. Every switch costs the viewer, so:
6923
+ * - only stay while a switch settles and for `SETTLE_MEASURE` after: until then the old track still
6924
+ * shares the link, and what arrives measures neither track;
6925
+ * - down only on trouble: a stall, frames arriving under `SHORT` of their rate, or an emptying buffer;
6926
+ * - up only when the median of `CONFIRMING` fresh probes shows room for the next rendition;
6927
+ * - a probe only below the top, from a known group, with none in flight, while not starved, and once
6928
+ * the backoff after probes that found no room has passed.
6929
+ */
6930
+ function legalActions(o) {
6931
+ if (o.settling || o.sinceSettled < SETTLE_MEASURE) return [
6932
+ false,
6933
+ true,
6934
+ false,
6935
+ false
6936
+ ];
6937
+ const k = o.requested;
6938
+ const top = o.ladder.length - 1;
6939
+ const trouble = o.stalledTime > 0 || o.arrivalRate < .8 || o.forwardBuffer < LOW_BUFFER;
6940
+ const room = k < top && o.evidence !== null && o.evidence * 8 * UP_MARGIN >= o.ladder[k + 1];
6941
+ const starved = o.stalledTime > 0 || o.arrivalRate < .5;
6942
+ const calm = o.sinceTrouble >= STABLE_RESET && (o.sinceProbe === null || o.sinceProbe >= STABLE_RESET);
6943
+ const backingOff = o.sinceProbe !== null && o.sinceProbe < probeBackoff(calm ? 0 : o.probeFailures);
6944
+ const canProbe = k < top && o.probeable && !o.probing && !starved && !backingOff && !room;
6945
+ return [
6946
+ k > 0 && trouble,
6947
+ true,
6948
+ room,
6949
+ canProbe
6950
+ ];
6951
+ }
6952
+ /** The highest rendition within `UP_MARGIN` of the evidence, at least one up. Only valid when up is allowed. */
6953
+ function climbTarget(o) {
6954
+ const budget = (o.evidence ?? 0) * 8 * UP_MARGIN;
6955
+ let target = o.requested + 1;
6956
+ for (let r = target; r < o.ladder.length; r++) if (o.ladder[r] <= budget) target = r;
6957
+ return target;
6958
+ }
6959
+ /**
6960
+ * The highest rendition within `DOWN_MARGIN` of `throughput`, at least one down: one switch rather
6961
+ * than one per rung, each waiting for the last to settle.
6962
+ */
6963
+ function downTarget(o) {
6964
+ const budget = o.throughput * 8 * DOWN_MARGIN;
6965
+ let target = 0;
6966
+ for (let r = 0; r < o.requested; r++) if (o.ladder[r] <= budget) target = r;
6967
+ return target;
6968
+ }
6969
+ /** Seconds to wait before the next probe after `failures` probes in a row found no room. */
6970
+ function probeBackoff(failures) {
6971
+ return failures > 0 ? PROBE_BACKOFF[Math.min(failures, PROBE_BACKOFF.length) - 1] : 0;
6972
+ }
6973
+ function clamp(value, min, max) {
6974
+ return Math.min(Math.max(value, min), max);
6975
+ }
6976
+ // src/player/plugins/abr/probe.ts
6977
+ /** A probe carries the difference to the next bitrate for this many seconds. */
6978
+ const PROBE_SECONDS = 1;
6979
+ /** Seconds a probe may take; what arrived by then is measured, the rest is cancelled. */
6980
+ const PROBE_TIMEOUT = 2;
6981
+ /** Seconds of a probe's round trip before its data can arrive. */
6982
+ const PROBE_ALLOWANCE = .25;
6983
+ /** Below this share of the pace that would show room, a probe can no longer show it, so it ends early. */
6984
+ const PROBE_BEHIND = .5;
6985
+ /** Below live media's 128: the relay sends a probe only when live leaves the link idle. */
6986
+ const PROBE_PRIORITY = 200;
6987
+ /** Bytes a probe for `next` needs on top of live delivery at `current`, both in bits per second. */
6988
+ function probeBytes(current, next) {
6989
+ return Math.floor((next - current) / 8 * PROBE_SECONDS);
6990
+ }
6991
+ /**
6992
+ * The FETCHes that carry closest to `targetBytes`. The known groups are walked oldest first as one
6993
+ * run, and the run stops at the object whose total lands closest to the target, at least one
6994
+ * object. A target beyond the whole run repeats it: the relay still has those objects cached.
6995
+ */
6996
+ function planProbe(groups, targetBytes) {
6997
+ const objects = groups.flatMap(({ group, objects }) => objects.map(({ id, bytes }) => ({
6998
+ group,
6999
+ id,
7000
+ bytes
7001
+ })));
7002
+ const total = objects.reduce((sum, { bytes }) => sum + bytes, 0);
7003
+ if (objects.length === 0 || total <= 0 || targetBytes <= 0) return [];
7004
+ const prefix = (count, bytes) => ({
7005
+ start: {
7006
+ group: objects[0].group,
7007
+ object: objects[0].id
7008
+ },
7009
+ end: {
7010
+ group: objects[count - 1].group,
7011
+ object: objects[count - 1].id
7012
+ },
7013
+ objects: count,
7014
+ bytes
7015
+ });
7016
+ const plan = Array.from({ length: Math.floor(targetBytes / total) }, () => prefix(objects.length, total));
7017
+ const rest = targetBytes - total * plan.length;
7018
+ let count = 0;
7019
+ let bytes = 0;
7020
+ while (count < objects.length && bytes + objects[count].bytes < rest) bytes += objects[count++].bytes;
7021
+ if (count < objects.length && bytes + objects[count].bytes - rest <= rest - bytes) bytes += objects[count++].bytes;
7022
+ if (count === 0 && plan.length === 0) bytes += objects[count++].bytes;
7023
+ if (count > 0) plan.push(prefix(count, bytes));
7024
+ return plan;
7025
+ }
7026
+ /**
7027
+ * Link capacity a probe saw, in bytes per second: every byte that arrived from the request to the
7028
+ * last probe object, the probe's and `others`', over that time. Timing from the request, not the
7029
+ * first object, keeps bursts out: loss recovery releases held stream data at once, which squeezes
7030
+ * arrivals together. It costs about one RTT of underestimate.
7031
+ */
7032
+ function probeEstimate(probe, others, requestedAt) {
7033
+ if (probe.length === 0) return 0;
7034
+ const last = probe.reduce((latest, { at }) => Math.max(latest, at), -Infinity);
7035
+ const within = others.filter(({ at }) => at > requestedAt && at <= last);
7036
+ return [...probe, ...within].reduce((sum, arrival) => sum + arrival.bytes, 0) / Math.max(last - requestedAt, .001);
7037
+ }
7038
+ /** Runs one probe at a time and keeps what the last `CONFIRMING` probes found. */
7039
+ var Prober = class {
7040
+ #inFlight;
7041
+ #estimates = [];
7042
+ /** When the last probe ended with an estimate; unlike `#endedAt`, forgotten with the estimates. */
7043
+ #estimatedAt;
7044
+ #failures = 0;
7045
+ #endedAt;
7046
+ get probing() {
7047
+ return this.#inFlight !== void 0;
7048
+ }
7049
+ /** The median of the recent estimates in bytes per second, if not forgotten. */
7050
+ get estimate() {
7051
+ return this.#estimates.length > 0 ? median(this.#estimates.map((e) => e.bytesPerSecond)) : void 0;
7052
+ }
7053
+ start(client, target, ranges, now) {
7054
+ const inFlight = {
7055
+ client,
7056
+ track: target.name,
7057
+ requestedAt: now,
7058
+ requestIds: /* @__PURE__ */ new Set(),
7059
+ fetches: ranges.length,
7060
+ abort: new AbortController(),
7061
+ arrivals: [],
7062
+ expectedObjects: ranges.reduce((sum, range) => sum + range.objects, 0),
7063
+ expectedBytes: ranges.reduce((sum, range) => sum + range.bytes, 0)
7064
+ };
7065
+ this.#inFlight = inFlight;
7066
+ for (const range of ranges) this.#fetch(inFlight, target.fullTrackName, range);
7067
+ }
7068
+ /**
7069
+ * Counts an object of a fetch stream: by request id, and by track until every FETCH_OK named its
7070
+ * request, since on a congested link FETCH_OK can come after the objects. Fill FETCHes of the same
7071
+ * track are not the probe's.
7072
+ */
7073
+ received(track, requestId, arrival) {
7074
+ const inFlight = this.#inFlight;
7075
+ if (!inFlight) return;
7076
+ const ours = requestId !== void 0 && inFlight.requestIds.has(requestId);
7077
+ const unnamed = inFlight.requestIds.size < inFlight.fetches && track !== void 0 && track === inFlight.track;
7078
+ if (ours || unnamed) inFlight.arrivals.push(arrival);
7079
+ }
7080
+ /**
7081
+ * Ends the probe in flight once its objects all arrived, it fell behind its pace, or it timed out,
7082
+ * and returns its estimate. `others` are the live objects received meanwhile; `nextBitrate` is the
7083
+ * one probed for, undefined at the top of the ladder.
7084
+ */
7085
+ settle(now, others, nextBitrate) {
7086
+ const inFlight = this.#inFlight;
7087
+ if (!inFlight) return void 0;
7088
+ const deadline = inFlight.requestedAt + PROBE_TIMEOUT;
7089
+ const arrivals = inFlight.arrivals.filter(({ at }) => at <= deadline);
7090
+ if (!(arrivals.length >= inFlight.expectedObjects) && !behindPace(inFlight, arrivals, now) && now < deadline) return void 0;
7091
+ this.cancel();
7092
+ const bytesPerSecond = probeEstimate(arrivals, others, inFlight.requestedAt);
7093
+ const room = nextBitrate === void 0 || bytesPerSecond * 8 >= nextBitrate;
7094
+ this.#failures = room ? 0 : this.#failures + 1;
7095
+ this.#estimates = [...this.#estimates, {
7096
+ bytesPerSecond,
7097
+ age: 0
7098
+ }].slice(-3);
7099
+ this.#estimatedAt = now;
7100
+ this.#endedAt = now;
7101
+ return bytesPerSecond;
7102
+ }
7103
+ /** Drops estimates the link has since contradicted. The failures, and so the backoff, stay. */
7104
+ forgetEstimates() {
7105
+ this.#estimates = [];
7106
+ this.#estimatedAt = void 0;
7107
+ }
7108
+ /** Ages the estimates as evidence; the controller skips it while a switch settles. */
7109
+ age(seconds) {
7110
+ for (const estimate of this.#estimates) estimate.age += seconds;
7111
+ }
7112
+ /** A move down: the link dropped, so probing again waits, without escalating the backoff. */
7113
+ steppedDown(now) {
7114
+ this.#failures = Math.max(this.#failures, 1);
7115
+ this.#endedAt = now;
7116
+ }
7117
+ /** A move up the ladder: what failed below says nothing about the next rendition. */
7118
+ forgetFailures() {
7119
+ this.#failures = 0;
7120
+ }
7121
+ /**
7122
+ * Cancels the probe in flight: the relay stops serving its FETCHes, and the client stops reading
7123
+ * their streams, so data already on its way stops too.
7124
+ */
7125
+ cancel() {
7126
+ const inFlight = this.#inFlight;
7127
+ if (!inFlight) return;
7128
+ this.#inFlight = void 0;
7129
+ inFlight.abort.abort();
7130
+ for (const id of inFlight.requestIds) Promise.resolve(inFlight.client.fetchCancel(id)).catch(() => {});
7131
+ }
7132
+ observe(now) {
7133
+ const fresh = this.#estimates.filter(({ age }) => age < 10).map((e) => e.bytesPerSecond);
7134
+ return {
7135
+ probeEstimate: this.estimate ?? null,
7136
+ probeAge: this.#estimatedAt === void 0 ? null : now - this.#estimatedAt,
7137
+ evidence: fresh.length === 3 ? median(fresh) : null,
7138
+ probing: this.probing,
7139
+ probeFailures: this.#failures,
7140
+ sinceProbe: this.#endedAt === void 0 ? null : now - this.#endedAt
7141
+ };
7142
+ }
7143
+ async #fetch(inFlight, fullTrackName, { start, end }) {
7144
+ const locationFilter = new require_model.LocationFilter(4, start.group, start.object, end.group, end.object);
7145
+ try {
7146
+ const result = await inFlight.client.fetch({
7147
+ priority: PROBE_PRIORITY,
7148
+ groupOrder: 1,
7149
+ fullTrackName,
7150
+ locationFilter
7151
+ });
7152
+ if (!("stream" in result)) return;
7153
+ if (this.#inFlight !== inFlight) {
7154
+ result.stream.cancel().catch(() => {});
7155
+ Promise.resolve(inFlight.client.fetchCancel(result.requestId)).catch(() => {});
7156
+ return;
7157
+ }
7158
+ inFlight.requestIds.add(result.requestId);
7159
+ await result.stream.pipeTo(new WritableStream(), { signal: inFlight.abort.signal });
7160
+ } catch {}
7161
+ }
7162
+ };
7163
+ /** Under `PROBE_BEHIND` of the pace that would show room, once the round trip is allowed for. */
7164
+ function behindPace(inFlight, arrivals, now) {
7165
+ const elapsed = now - inFlight.requestedAt - PROBE_ALLOWANCE;
7166
+ const delivered = arrivals.reduce((sum, { bytes }) => sum + bytes, 0);
7167
+ return elapsed > 0 && delivered < PROBE_BEHIND * inFlight.expectedBytes / PROBE_SECONDS * elapsed;
7168
+ }
7169
+ function median(values) {
7170
+ const ordered = [...values].sort((a, b) => a - b);
7171
+ const middle = Math.floor(ordered.length / 2);
7172
+ return ordered.length % 2 === 1 ? ordered[middle] : (ordered[middle - 1] + ordered[middle]) / 2;
7173
+ }
7174
+ // src/player/plugins/abr/signals.ts
7175
+ /** Seconds of history kept. */
7176
+ const KEEP = 8;
7177
+ /** Seconds of per-second object counts a frame rate is inferred from, when the catalog has none. */
7178
+ const RATE_HISTORY = 30;
7179
+ /** Seconds a start may take before waiting for it counts as a stall. */
7180
+ const STARTUP_GRACE = 2;
7181
+ /** The shortest window a rate is measured over, one tick: a settle can shorten the window to it. */
7182
+ const SHORTEST_WINDOW = .5;
7183
+ /**
7184
+ * What the controller learns from the player's data events, its states, and the sink's buffer,
7185
+ * over the last few seconds. Times are in seconds, from `performance.now()`.
7186
+ */
7187
+ var Signals = class {
7188
+ /** Video objects received in each whole second, for inferring the frame rate. */
7189
+ #perSecond = /* @__PURE__ */ new Map();
7190
+ /** The group each video track is receiving, by track name. */
7191
+ #receiving = /* @__PURE__ */ new Map();
7192
+ /** Open live streams of the video tracks: stream id → track. */
7193
+ #openStreams = /* @__PURE__ */ new Map();
7194
+ /** When each video track last delivered an object. */
7195
+ #lastObject = /* @__PURE__ */ new Map();
7196
+ #videoTracks = /* @__PURE__ */ new Map();
7197
+ #video = [];
7198
+ /** Every other live object, such as audio: it shares the link. */
7199
+ #others = [];
7200
+ #firstVideo;
7201
+ #known = [];
7202
+ #groupStarts = [];
7203
+ #stalls = [];
7204
+ #autoplayBlocked = false;
7205
+ /** Windowed signals count from here on: the last settled switch. */
7206
+ #measuredFrom = -Infinity;
7207
+ /** The tracks that carry video, each to the rendition it delivers: only their objects are measured as live media. */
7208
+ set videoTracks(heads) {
7209
+ this.#videoTracks = heads;
7210
+ }
7211
+ /** Stream ids are per client: after a reconnect the old client's streams never end. */
7212
+ forgetStreams() {
7213
+ this.#openStreams.clear();
7214
+ }
7215
+ /** A data event of a live stream, of `track` once the client knows it. */
7216
+ received(event, track) {
7217
+ if (event.kind === "end") this.#openStreams.delete(event.streamId);
7218
+ if (event.kind !== "object") return;
7219
+ const arrival = {
7220
+ at: event.at / 1e3,
7221
+ bytes: event.payloadLength
7222
+ };
7223
+ const head = track === void 0 ? void 0 : this.#videoTracks.get(track);
7224
+ if (head === void 0) {
7225
+ this.#others.push(arrival);
7226
+ return;
7227
+ }
7228
+ this.#video.push(arrival);
7229
+ this.#firstVideo ??= arrival.at;
7230
+ this.#openStreams.set(event.streamId, head);
7231
+ this.#lastObject.set(head, arrival.at);
7232
+ const second = Math.floor(arrival.at);
7233
+ this.#perSecond.set(second, (this.#perSecond.get(second) ?? 0) + 1);
7234
+ if (track !== head) return;
7235
+ const receiving = this.#receiving.get(track);
7236
+ if (receiving && event.groupId < receiving.group) {
7237
+ this.#lateObject(track, event);
7238
+ return;
7239
+ }
7240
+ if (receiving?.group !== event.groupId) this.#startGroup(track, event.groupId, arrival.at);
7241
+ this.#receiving.get(track).objects.set(event.objectId, event.payloadLength);
7242
+ }
7243
+ /**
7244
+ * Stalls by the player's state. Waiting to start counts too, after a grace period: a start the
7245
+ * link can't feed would otherwise leave the controller waiting for playback, and playback for it.
7246
+ */
7247
+ playerState(state, now) {
7248
+ if (state === "playing") this.#autoplayBlocked = false;
7249
+ const waiting = state === "stalled" || state === "ready" && !this.#autoplayBlocked;
7250
+ const current = this.#stalls.at(-1);
7251
+ const open = current?.end === Infinity;
7252
+ if (waiting && !open) this.#stalls.push({
7253
+ start: state === "ready" ? now + STARTUP_GRACE : now,
7254
+ end: Infinity
7255
+ });
7256
+ if (!waiting && open) current.end = Math.max(now, current.start);
7257
+ }
7258
+ /** The viewer has to press play: waiting for that is not the network's doing. */
7259
+ autoplayBlocked(state, now) {
7260
+ this.#autoplayBlocked = true;
7261
+ this.playerState(state, now);
7262
+ }
7263
+ /** Forgets what is older than any signal looks back. */
7264
+ prune(now) {
7265
+ const recent = ({ at }) => at > now - KEEP;
7266
+ this.#video = this.#video.filter(recent);
7267
+ this.#others = this.#others.filter(recent);
7268
+ for (const second of this.#perSecond.keys()) if (second < now - RATE_HISTORY) this.#perSecond.delete(second);
7269
+ this.#stalls = this.#stalls.filter(({ end }) => end > now - KEEP);
7270
+ }
7271
+ /** Whether `WINDOW` seconds of live video arrived: until then, startup reads as congestion. */
7272
+ warmedUp(now) {
7273
+ return this.#firstVideo !== void 0 && now - this.#firstVideo >= 2;
7274
+ }
7275
+ stalledTime(now) {
7276
+ const from = now - 2;
7277
+ return this.#stalls.reduce((sum, { start, end }) => sum + Math.max(0, Math.min(end, now) - Math.max(start, from)), 0);
7278
+ }
7279
+ /** Whether `track` still has a live stream open: it hasn't delivered its last group yet. */
7280
+ streaming(track) {
7281
+ return [...this.#openStreams.values()].includes(track);
7282
+ }
7283
+ /** When `track` last delivered an object; -Infinity before it did. */
7284
+ lastObjectAt(track) {
7285
+ return this.#lastObject.get(track) ?? -Infinity;
7286
+ }
7287
+ /** Windowed signals count from `now` on: a switch settled, and what came before measured another track. */
7288
+ measureFrom(now) {
7289
+ this.#measuredFrom = now;
7290
+ }
7291
+ /** Live video bytes received in the measured window, scaled to a whole `WINDOW`. */
7292
+ receivedBytes(now) {
7293
+ return this.#bytesPerSecond(now, 2) * 2;
7294
+ }
7295
+ /**
7296
+ * Video objects received in the measured window over what `frameRate` delivers in it. Without a
7297
+ * frame rate from the catalog it uses the rate they usually arrive at, so only a slowdown reads as one.
7298
+ */
7299
+ arrivalRate(now, frameRate) {
7300
+ const { start, length } = this.#window(now, 2);
7301
+ const expected = (frameRate ?? this.#usualRate(now)) * length;
7302
+ const received = this.#video.filter(({ at }) => at > start && at <= now).length;
7303
+ return expected > 0 ? received / expected : 1;
7304
+ }
7305
+ /**
7306
+ * Live video bytes per second, the slower of the last `RECENT` seconds and its second half: a drop
7307
+ * shows in the recent half first, and the whole second keeps a short gap between objects from
7308
+ * reading as one.
7309
+ */
7310
+ throughput(now) {
7311
+ return Math.min(...[1, 1 / 2].map((seconds) => this.#bytesPerSecond(now, seconds)));
7312
+ }
7313
+ /** Frames arriving at under half their rate: the link is far behind. */
7314
+ starved(now, frameRate) {
7315
+ return this.warmedUp(now) && this.arrivalRate(now, frameRate) < .5;
7316
+ }
7317
+ /** Mean time between group starts; null until two are seen. */
7318
+ groupInterval() {
7319
+ const starts = this.#groupStarts;
7320
+ return starts.length > 1 ? (starts.at(-1) - starts[0]) / (starts.length - 1) : null;
7321
+ }
7322
+ /** The last one or two complete groups of the track that completed one last, oldest first. */
7323
+ knownGroups() {
7324
+ const last = this.#known.at(-1);
7325
+ return last ? this.#known.slice(-2).filter(({ track }) => track === last.track) : [];
7326
+ }
7327
+ /** Every live object, video and others, for measuring a probe against. */
7328
+ arrivals() {
7329
+ return [...this.#video, ...this.#others];
7330
+ }
7331
+ /** The last `seconds`, from the last settled switch on, and its length, at least `SHORTEST_WINDOW`. */
7332
+ #window(now, seconds) {
7333
+ const start = Math.max(now - seconds, this.#measuredFrom);
7334
+ return {
7335
+ start,
7336
+ length: Math.max(now - start, SHORTEST_WINDOW)
7337
+ };
7338
+ }
7339
+ #bytesPerSecond(now, seconds) {
7340
+ const { start, length } = this.#window(now, seconds);
7341
+ return this.#video.reduce((sum, { at, bytes }) => at > start && at <= now ? sum + bytes : sum, 0) / length;
7342
+ }
7343
+ /** A new group closes the one the track was receiving: its objects' sizes are now known. */
7344
+ #startGroup(track, group, at) {
7345
+ const previous = this.#receiving.get(track);
7346
+ if (previous) {
7347
+ const objects = [...previous.objects].map(([id, bytes]) => ({
7348
+ id,
7349
+ bytes
7350
+ })).sort(byId);
7351
+ this.#known = [...this.#known, {
7352
+ track,
7353
+ group: previous.group,
7354
+ objects
7355
+ }].slice(-2);
7356
+ }
7357
+ this.#receiving.set(track, {
7358
+ group,
7359
+ objects: /* @__PURE__ */ new Map()
7360
+ });
7361
+ this.#groupStarts = [...this.#groupStarts, at].slice(-5);
7362
+ }
7363
+ /** An object of a group a newer one already closed: added to it, if it is still known. */
7364
+ #lateObject(track, { groupId, objectId, payloadLength }) {
7365
+ this.#known = this.#known.map((known) => known.track === track && known.group === groupId ? {
7366
+ ...known,
7367
+ objects: [...known.objects, {
7368
+ id: objectId,
7369
+ bytes: payloadLength
7370
+ }].sort(byId)
7371
+ } : known);
7372
+ }
7373
+ /**
7374
+ * Objects per second in a typical whole second of the last `RATE_HISTORY`: the 75th percentile,
7375
+ * so a congested stretch doesn't drag it down and a catch-up burst doesn't lift it.
7376
+ */
7377
+ #usualRate(now) {
7378
+ const counts = [...this.#perSecond].filter(([second]) => second < Math.floor(now)).map(([, count]) => count).sort((a, b) => a - b);
7379
+ return counts.length > 0 ? counts[Math.floor((counts.length - 1) * .75)] : 0;
7380
+ }
7381
+ };
7382
+ function byId(a, b) {
7383
+ return a.id < b.id ? -1 : 1;
7384
+ }
6026
7385
  // src/player/plugins/abr/controller.ts
6027
- /** @public The `abr()` controller. For now it keeps the current quality: it never switches. */
6028
- var DefaultAbrController = class {
6029
- attach(_player, _sink) {}
6030
- detach() {}
7386
+ /** Seconds after a switch before the requested rendition follows the one playing. */
7387
+ const RESYNC = 4;
7388
+ /**
7389
+ * @public
7390
+ * ABR for live playback: every tick a small neural network picks a switch down, a switch up, a probe
7391
+ * or nothing, among the actions `legalActions` allows.
7392
+ */
7393
+ var MlAbrController = class {
7394
+ #tickMs;
7395
+ #onDecision;
7396
+ /** By rendition `src`. */
7397
+ #targets = /* @__PURE__ */ new Map();
7398
+ #policy;
7399
+ #session;
7400
+ constructor(tickMs, policy, onDecision) {
7401
+ this.#tickMs = tickMs;
7402
+ this.#onDecision = onDecision;
7403
+ policy.then((loaded) => {
7404
+ this.#policy = loaded;
7405
+ }, (error) => require_emitter.logger.error("abr", "the model failed to load, so ABR stays idle", error));
7406
+ }
7407
+ attach(player, sink) {
7408
+ this.detach();
7409
+ const signals = new Signals();
7410
+ const prober = new Prober();
7411
+ const onState = (state) => signals.playerState(state, seconds());
7412
+ const onAutoplayBlocked = () => signals.autoplayBlocked(player.state, seconds());
7413
+ player.on("statechange", onState);
7414
+ player.on("autoplayblocked", onAutoplayBlocked);
7415
+ onState(player.state);
7416
+ signals.videoTracks = this.#videoTracks(player);
7417
+ const unfollow = followData(player, (event, track, header) => {
7418
+ if (header.stream === "subgroup") signals.received(event, track);
7419
+ else if (event.kind === "object") prober.received(track, header.requestId, {
7420
+ at: event.at / 1e3,
7421
+ bytes: event.payloadLength
7422
+ });
7423
+ });
7424
+ const unclient = eachClient(player, () => {
7425
+ signals.forgetStreams();
7426
+ prober.cancel();
7427
+ return () => {};
7428
+ });
7429
+ const timer = setInterval(() => this.#tick(), this.#tickMs);
7430
+ this.#session = {
7431
+ player,
7432
+ sink,
7433
+ signals,
7434
+ prober,
7435
+ requested: void 0,
7436
+ switchedAt: -Infinity,
7437
+ settling: void 0,
7438
+ settledAt: -Infinity,
7439
+ troubleAt: -Infinity,
7440
+ stop: () => {
7441
+ clearInterval(timer);
7442
+ unfollow();
7443
+ unclient();
7444
+ player.off("statechange", onState);
7445
+ player.off("autoplayblocked", onAutoplayBlocked);
7446
+ }
7447
+ };
7448
+ }
7449
+ detach() {
7450
+ const session = this.#session;
7451
+ if (!session) return;
7452
+ this.#session = void 0;
7453
+ session.stop();
7454
+ session.prober.cancel();
7455
+ }
7456
+ #tick() {
7457
+ const session = this.#session;
7458
+ const policy = this.#policy;
7459
+ if (!session || !policy || session.player.state === "paused") return;
7460
+ const ladder = videoLadder(session.player);
7461
+ if (!ladder) return;
7462
+ const now = seconds();
7463
+ const { signals, prober } = session;
7464
+ signals.videoTracks = this.#videoTracks(session.player);
7465
+ signals.prune(now);
7466
+ if (!session.settling) prober.age(this.#tickMs / 1e3);
7467
+ const active = ladder.renditions.findIndex((r) => r.active);
7468
+ this.#settle(session, now);
7469
+ const stalledTime = signals.stalledTime(now);
7470
+ const requested = this.#requested(session, ladder, active, stalledTime, now);
7471
+ session.requested = requested;
7472
+ const playing = ladder.renditions[active === -1 ? requested : active];
7473
+ const arrivalRate = signals.arrivalRate(now, playing.frameRate);
7474
+ if (this.#contradicted(session, playing, stalledTime, now)) prober.forgetEstimates();
7475
+ const probeResult = prober.settle(now, signals.arrivals(), ladder.renditions[requested + 1]?.bitrate);
7476
+ if (stalledTime > 0 || arrivalRate < .8) session.troubleAt = now;
7477
+ const observation = this.#observe(session, ladder, requested, playing, {
7478
+ stalledTime,
7479
+ arrivalRate
7480
+ }, now);
7481
+ const inputs = features(observation);
7482
+ const reported = {
7483
+ observation,
7484
+ features: inputs,
7485
+ ...probeResult !== void 0 && { probeResult }
7486
+ };
7487
+ if (!signals.warmedUp(now) && observation.stalledTime === 0) {
7488
+ this.#onDecision?.({
7489
+ ...reported,
7490
+ action: Action.Stay,
7491
+ warmingUp: true
7492
+ });
7493
+ return;
7494
+ }
7495
+ const action = policy.choose(inputs, legalActions(observation));
7496
+ const switchedTo = action === Action.Up ? climbTarget(observation) : action === Action.Down ? downTarget(observation) : void 0;
7497
+ if (switchedTo !== void 0) this.#switch(session, ladder, requested, switchedTo, now);
7498
+ if (action === Action.Probe) this.#probe(session, ladder, requested, now);
7499
+ this.#onDecision?.({
7500
+ ...reported,
7501
+ action,
7502
+ ...switchedTo !== void 0 && { switchedTo }
7503
+ });
7504
+ }
7505
+ /**
7506
+ * The rendition to count from. A superseded switch can land after the one that replaced it, so
7507
+ * once switches had time to land, it follows the one playing; not while stalled, where no switch
7508
+ * lands and asking again only supersedes more requests.
7509
+ */
7510
+ #requested(session, ladder, active, stalledTime, now) {
7511
+ const { requested, signals } = session;
7512
+ if (requested === void 0 || requested >= ladder.renditions.length) return Math.max(active, 0);
7513
+ const settled = now - session.switchedAt > Math.max(RESYNC, 2 * (signals.groupInterval() ?? 0));
7514
+ return active !== -1 && settled && stalledTime === 0 ? active : requested;
7515
+ }
7516
+ /**
7517
+ * A switch settled once every stream of the old track ended and the new track delivered. From then
7518
+ * on the windows measure the new track alone.
7519
+ */
7520
+ #settle(session, now) {
7521
+ const { settling, signals } = session;
7522
+ if (!settling) return;
7523
+ if (!(!signals.streaming(settling.from) && signals.lastObjectAt(settling.to) > settling.since) && now - settling.since < 10) return;
7524
+ session.settling = void 0;
7525
+ session.settledAt = now;
7526
+ signals.measureFrom(now);
7527
+ }
7528
+ /**
7529
+ * A stall, or frames arriving at under half their rate, shows the link no longer carries a probe
7530
+ * estimate above the bitrate being received. One below it agrees, and keeps its backoff.
7531
+ */
7532
+ #contradicted({ signals, prober }, playing, stalledTime, now) {
7533
+ const estimate = prober.estimate;
7534
+ return (stalledTime > 0 || signals.starved(now, playing.frameRate)) && estimate !== void 0 && estimate * 8 > playing.bitrate;
7535
+ }
7536
+ #observe(session, ladder, requested, playing, { stalledTime, arrivalRate }, now) {
7537
+ const { player, sink, signals, prober } = session;
7538
+ const { currentTime, buffered } = sink;
7539
+ const range = rangeAt(currentTime, buffered);
7540
+ return {
7541
+ forwardBuffer: range === -1 ? 0 : buffered.end(range) - currentTime,
7542
+ playbackRate: player.state === "playing" ? sink.playbackRate : 0,
7543
+ stalledTime,
7544
+ ladder: ladder.renditions.map((r) => r.bitrate),
7545
+ requested,
7546
+ activeBitrate: playing.bitrate,
7547
+ receivedBytes: signals.receivedBytes(now),
7548
+ throughput: signals.throughput(now),
7549
+ arrivalRate,
7550
+ ...prober.observe(now),
7551
+ sinceSwitch: now - session.switchedAt,
7552
+ groupInterval: signals.groupInterval(),
7553
+ probeable: signals.knownGroups().length > 0,
7554
+ settling: session.settling !== void 0,
7555
+ sinceSettled: now - session.settledAt,
7556
+ sinceTrouble: now - session.troubleAt
7557
+ };
7558
+ }
7559
+ #switch(session, { source, renditions }, from, to, now) {
7560
+ session.requested = to;
7561
+ session.switchedAt = now;
7562
+ session.settling = {
7563
+ from: this.#target(renditions[from]).name,
7564
+ to: this.#target(renditions[to]).name,
7565
+ since: now
7566
+ };
7567
+ if (to > from) session.prober.forgetFailures();
7568
+ else session.prober.steppedDown(now);
7569
+ source.switch(renditions[to].id).catch(() => {});
7570
+ }
7571
+ #probe({ player, signals, prober }, { source, renditions }, requested, now) {
7572
+ const groups = signals.knownGroups();
7573
+ const probed = source.getRenditions().find((r) => this.#target(r).name === groups[0]?.track);
7574
+ const client = player.client;
7575
+ if (!client || !probed) return;
7576
+ const bytes = probeBytes(renditions[requested].bitrate, renditions[requested + 1].bitrate);
7577
+ prober.start(client, this.#target(probed), planProbe(groups, bytes), now);
7578
+ }
7579
+ #videoTracks(player) {
7580
+ const heads = /* @__PURE__ */ new Map();
7581
+ for (const r of videoSource(player)?.getRenditions() ?? []) {
7582
+ const head = this.#target(r).name;
7583
+ for (const member of r.ladder ?? [head]) heads.set(member, head);
7584
+ }
7585
+ return heads;
7586
+ }
7587
+ /** The track behind `rendition`, as a probe FETCHes it. */
7588
+ #target(rendition) {
7589
+ let target = this.#targets.get(rendition.src);
7590
+ if (!target) {
7591
+ const { track, namespace, trackBytes } = parseMsfUrl(rendition.src);
7592
+ target = {
7593
+ name: track,
7594
+ fullTrackName: require_model.FullTrackName.tryNew(namespace, trackBytes)
7595
+ };
7596
+ this.#targets.set(rendition.src, target);
7597
+ }
7598
+ return target;
7599
+ }
7600
+ };
7601
+ /** The source with video renditions, else the one with the most renditions. */
7602
+ function videoSource(player) {
7603
+ const sources = player.mediaSources;
7604
+ return sources.find((s) => s.getRenditions().some((r) => r.width !== void 0 || r.height !== void 0)) ?? [...sources].sort((a, b) => b.getRenditions().length - a.getRenditions().length)[0];
7605
+ }
7606
+ /** Undefined when there is nothing to choose between, or a bitrate is unknown. */
7607
+ function videoLadder(player) {
7608
+ const source = videoSource(player);
7609
+ const renditions = (source?.getRenditions() ?? []).filter((r) => r.selected).sort((a, b) => a.bitrate - b.bitrate);
7610
+ if (!source || renditions.length < 2 || renditions.some((r) => !(r.bitrate > 0))) return void 0;
7611
+ return {
7612
+ source,
7613
+ renditions
7614
+ };
7615
+ }
7616
+ function seconds() {
7617
+ return performance.now() / 1e3;
7618
+ }
7619
+ // src/player/plugins/abr/model.ts
7620
+ /** The bundled model: int4 weights, 220 characters. */
7621
+ const BUNDLED_MODEL = {
7622
+ codec: "raw",
7623
+ data: "ASb+evACDRCGNC4xEASlMocp4fLw8QHzEPHv8D7uATAAAP8ADgAhEAEQPwCh9v7vAw3/0PAAwOLx0AHwAfASEDvf4TzR8i8jIiAtAiBPEA8yPg7Q/fAA8Q4vIiAAEl4PL08jHx/+MdYyAnM7HQAdH/8BDQDNAP8A7wAB/gJDD9+5AD7yIT/PwtY13y/+3iMwdP9UJ/RO+TMcFSD+EhL+4bwP+Us="
7624
+ };
7625
+ // src/player/plugins/abr/policy.ts
7626
+ /**
7627
+ * Copyright 2026 The MOQtail Authors
7628
+ *
7629
+ * Licensed under the Apache License, Version 2.0 (the "License");
7630
+ * you may not use this file except in compliance with the License.
7631
+ * You may obtain a copy of the License at
7632
+ *
7633
+ * http://www.apache.org/licenses/LICENSE-2.0
7634
+ *
7635
+ * Unless required by applicable law or agreed to in writing, software
7636
+ * distributed under the License is distributed on an "AS IS" BASIS,
7637
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7638
+ * See the License for the specific language governing permissions and
7639
+ * limitations under the License.
7640
+ */
7641
+ /**
7642
+ * The model: a small multilayer perceptron with tanh hidden layers and int4 weights, shipped as a
7643
+ * few hundred bytes of base64. The packed form is
7644
+ *
7645
+ * u8 FEATURES_VERSION | u32le featuresHash() | u8 layer count
7646
+ * | per layer: u8 inputs, u8 outputs, f16le weight scale, f16le bias scale
7647
+ * | int4 codes, two per byte, low nibble first: per layer the weights row by row, then the biases
7648
+ *
7649
+ * optionally deflate-raw compressed, whichever is smaller.
7650
+ */
7651
+ /** A decoded model: logits over `Action` for a feature vector. */
7652
+ var Policy = class Policy {
7653
+ #layers;
7654
+ constructor(layers) {
7655
+ this.#layers = layers;
7656
+ }
7657
+ /**
7658
+ * Decodes a blob.
7659
+ * @throws TypeError for a model trained on another feature list, which would read the inputs wrong.
7660
+ */
7661
+ static async load(blob) {
7662
+ const packed = base64Bytes(blob.data);
7663
+ return new Policy(parseLayers(blob.codec === "deflate-raw" ? await inflate(packed) : packed));
7664
+ }
7665
+ logits(features) {
7666
+ let values = features;
7667
+ this.#layers.forEach((layer, index) => {
7668
+ const hidden = index < this.#layers.length - 1;
7669
+ values = applyLayer(layer, values).map((v) => hidden ? Math.tanh(v) : v);
7670
+ });
7671
+ return [...values];
7672
+ }
7673
+ /**
7674
+ * Draws an allowed action by the model's odds instead of taking the likeliest: some choices, such
7675
+ * as an occasional probe on a calm link, it learned only as odds. `random` returns numbers in [0, 1).
7676
+ */
7677
+ choose(features, legal, random = Math.random) {
7678
+ const logits = this.logits(features);
7679
+ const top = Math.max(...logits.filter((_, action) => legal[action]));
7680
+ const weights = logits.map((logit, action) => legal[action] ? Math.exp(logit - top) : 0);
7681
+ let draw = random() * weights.reduce((sum, weight) => sum + weight, 0);
7682
+ for (let action = 0; action < weights.length; action++) {
7683
+ draw -= weights[action];
7684
+ if (draw < 0 && weights[action] > 0) return action;
7685
+ }
7686
+ return Action.Stay;
7687
+ }
6031
7688
  };
7689
+ function applyLayer({ inputs, outputs, weights, biases }, values) {
7690
+ return Array.from({ length: outputs }, (_, row) => {
7691
+ let sum = biases[row];
7692
+ for (let column = 0; column < inputs; column++) sum += weights[row * inputs + column] * values[column];
7693
+ return sum;
7694
+ });
7695
+ }
7696
+ function base64Bytes(data) {
7697
+ return Uint8Array.from(atob(data), (char) => char.charCodeAt(0));
7698
+ }
7699
+ async function inflate(bytes) {
7700
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
7701
+ return new Uint8Array(await new Response(stream).arrayBuffer());
7702
+ }
7703
+ function parseLayers(bytes) {
7704
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
7705
+ if (view.getUint8(0) !== 1 || view.getUint32(1, true) !== featuresHash()) throw new TypeError("The model was trained on another feature list");
7706
+ const shapes = Array.from({ length: view.getUint8(5) }, (_, index) => {
7707
+ const at = 6 + index * 6;
7708
+ return {
7709
+ inputs: view.getUint8(at),
7710
+ outputs: view.getUint8(at + 1),
7711
+ weightScale: float16(view.getUint16(at + 2, true)),
7712
+ biasScale: float16(view.getUint16(at + 4, true))
7713
+ };
7714
+ });
7715
+ const codes = int4Codes(bytes, 6 + shapes.length * 6);
7716
+ return shapes.map(({ inputs, outputs, weightScale, biasScale }) => ({
7717
+ inputs,
7718
+ outputs,
7719
+ weights: Float64Array.from({ length: inputs * outputs }, () => codes.next() * weightScale),
7720
+ biases: Float64Array.from({ length: outputs }, () => codes.next() * biasScale)
7721
+ }));
7722
+ }
7723
+ /** Reads signed 4-bit codes from `offset` on, two per byte, low nibble first. */
7724
+ function int4Codes(bytes, offset) {
7725
+ let nibble = offset * 2;
7726
+ return { next() {
7727
+ const byte = bytes[nibble >> 1];
7728
+ const code = nibble % 2 === 0 ? byte & 15 : byte >> 4;
7729
+ nibble++;
7730
+ return code >= 8 ? code - 16 : code;
7731
+ } };
7732
+ }
7733
+ /** IEEE 754 half precision; `DataView.getFloat16` is too new to rely on. Scales are finite. */
7734
+ function float16(bits) {
7735
+ const sign = bits & 32768 ? -1 : 1;
7736
+ const exponent = bits >> 10 & 31;
7737
+ const fraction = bits & 1023;
7738
+ return exponent === 0 ? sign * fraction * 2 ** -24 : sign * (1 + fraction / 1024) * 2 ** (exponent - 15);
7739
+ }
6032
7740
  // src/player/plugins/abr/index.ts
6033
7741
  /**
6034
7742
  * Copyright 2026 The MOQtail Authors
@@ -6045,15 +7753,20 @@ var DefaultAbrController = class {
6045
7753
  * See the License for the specific language governing permissions and
6046
7754
  * limitations under the License.
6047
7755
  */
7756
+ /** Decoded once, then shared by every player. */
7757
+ let bundled;
6048
7758
  /**
6049
7759
  * @public
6050
- * An ABR controller for media sources that don't switch themselves. Priority `Infinity`, so any
7760
+ * An ABR controller driven by a small neural network, for live streams. Priority `Infinity`, so any
6051
7761
  * other active ABR plugin wins over it.
6052
7762
  */
6053
7763
  const abr = definePlugin({
6054
7764
  name: "abr",
6055
7765
  priority: Infinity,
6056
- init: () => new DefaultAbrController(),
7766
+ init: ({ tickMs = 500, model, onDecision } = {}) => {
7767
+ if (!(tickMs > 0 && tickMs < Infinity)) throw new TypeError("tickMs must be a positive number");
7768
+ return new MlAbrController(tickMs, model ? Policy.load(model) : bundled ??= Policy.load(BUNDLED_MODEL), onDecision);
7769
+ },
6057
7770
  features: (controller) => [{
6058
7771
  type: "abr-controller",
6059
7772
  item: controller
@@ -6300,10 +8013,11 @@ var SstsSource = class extends SourceElement {
6300
8013
  this.#selected = new Set(context.tracks.map((t) => this.#id(t)));
6301
8014
  this.algorithms = sstsAlgorithms(context.client.serverSetup, preferred);
6302
8015
  this.#algorithm = this.algorithms[0] ?? 0n;
8016
+ const packaging = options.child.capabilities.flat().find((c) => c.direction === "out" && c.code === 0)?.value;
6303
8017
  this.pad = this.createPad("src", [{
6304
8018
  direction: "out",
6305
8019
  code: 0,
6306
- value: first.packaging
8020
+ value: packaging ?? first.packaging
6307
8021
  }, {
6308
8022
  direction: "out",
6309
8023
  code: 1,
@@ -6604,6 +8318,12 @@ Object.defineProperty(exports, "ABR", {
6604
8318
  return ABR;
6605
8319
  }
6606
8320
  });
8321
+ Object.defineProperty(exports, "Action", {
8322
+ enumerable: true,
8323
+ get: function() {
8324
+ return Action;
8325
+ }
8326
+ });
6607
8327
  Object.defineProperty(exports, "BaseElement", {
6608
8328
  enumerable: true,
6609
8329
  get: function() {
@@ -6628,12 +8348,6 @@ Object.defineProperty(exports, "DEFAULT_PRIORITY", {
6628
8348
  return DEFAULT_PRIORITY;
6629
8349
  }
6630
8350
  });
6631
- Object.defineProperty(exports, "DefaultAbrController", {
6632
- enumerable: true,
6633
- get: function() {
6634
- return DefaultAbrController;
6635
- }
6636
- });
6637
8351
  Object.defineProperty(exports, "MEDIA_SINK", {
6638
8352
  enumerable: true,
6639
8353
  get: function() {
@@ -6658,6 +8372,12 @@ Object.defineProperty(exports, "MSE", {
6658
8372
  return MSE;
6659
8373
  }
6660
8374
  });
8375
+ Object.defineProperty(exports, "MlAbrController", {
8376
+ enumerable: true,
8377
+ get: function() {
8378
+ return MlAbrController;
8379
+ }
8380
+ });
6661
8381
  Object.defineProperty(exports, "Pad", {
6662
8382
  enumerable: true,
6663
8383
  get: function() {
@@ -6718,6 +8438,18 @@ Object.defineProperty(exports, "definePlugin", {
6718
8438
  return definePlugin;
6719
8439
  }
6720
8440
  });
8441
+ Object.defineProperty(exports, "eachClient", {
8442
+ enumerable: true,
8443
+ get: function() {
8444
+ return eachClient;
8445
+ }
8446
+ });
8447
+ Object.defineProperty(exports, "followData", {
8448
+ enumerable: true,
8449
+ get: function() {
8450
+ return followData;
8451
+ }
8452
+ });
6721
8453
  Object.defineProperty(exports, "formatMsfUrl", {
6722
8454
  enumerable: true,
6723
8455
  get: function() {
@@ -6742,6 +8474,12 @@ Object.defineProperty(exports, "parseMsfUrl", {
6742
8474
  return parseMsfUrl;
6743
8475
  }
6744
8476
  });
8477
+ Object.defineProperty(exports, "rangeAt", {
8478
+ enumerable: true,
8479
+ get: function() {
8480
+ return rangeAt;
8481
+ }
8482
+ });
6745
8483
  Object.defineProperty(exports, "ssts", {
6746
8484
  enumerable: true,
6747
8485
  get: function() {