mattebox 0.9.0 → 0.10.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.
Files changed (59) hide show
  1. package/dist/cdn/mattebox.dash-drm.min.js +3 -3
  2. package/dist/cdn/mattebox.dash.min.js +3 -3
  3. package/dist/cdn/mattebox.dual-drm.min.js +3 -3
  4. package/dist/cdn/mattebox.dual-ts-drm.min.js +3 -3
  5. package/dist/cdn/mattebox.dual-ts.min.js +3 -3
  6. package/dist/cdn/mattebox.dual.min.js +3 -3
  7. package/dist/cdn/mattebox.hls-drm.min.js +3 -3
  8. package/dist/cdn/mattebox.hls-ts-drm.min.js +3 -3
  9. package/dist/cdn/mattebox.hls-ts.min.js +3 -3
  10. package/dist/cdn/mattebox.hls.min.js +3 -3
  11. package/dist/cdn/mattebox.kernel.min.js +1 -1
  12. package/dist/cdn/mattebox.min.js +2 -2
  13. package/dist/es2015/index.js +2 -1
  14. package/dist/es2015/kernel/reducer.js +44 -6
  15. package/dist/es2015/kernel/track-registry.js +18 -1
  16. package/dist/es2015/protocols/dash-cmaf/parse.js +68 -20
  17. package/dist/es2015/protocols/hls-cmaf/parse.js +33 -2
  18. package/dist/es2015/stages/alt-audio/index.js +31 -11
  19. package/dist/es2015/stages/text-cea608/index.js +84 -15
  20. package/dist/es2015/stages/text-webvtt/index.js +8 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +3 -0
  23. package/dist/index.js.map +1 -1
  24. package/dist/kernel/reducer.d.ts +3 -0
  25. package/dist/kernel/reducer.d.ts.map +1 -1
  26. package/dist/kernel/reducer.js +40 -4
  27. package/dist/kernel/reducer.js.map +1 -1
  28. package/dist/kernel/track-registry.d.ts +8 -8
  29. package/dist/kernel/track-registry.d.ts.map +1 -1
  30. package/dist/kernel/track-registry.js +27 -4
  31. package/dist/kernel/track-registry.js.map +1 -1
  32. package/dist/protocols/dash-cmaf/parse.d.ts.map +1 -1
  33. package/dist/protocols/dash-cmaf/parse.js +55 -0
  34. package/dist/protocols/dash-cmaf/parse.js.map +1 -1
  35. package/dist/protocols/hls-cmaf/parse.d.ts.map +1 -1
  36. package/dist/protocols/hls-cmaf/parse.js +38 -4
  37. package/dist/protocols/hls-cmaf/parse.js.map +1 -1
  38. package/dist/stages/alt-audio/index.d.ts +5 -2
  39. package/dist/stages/alt-audio/index.d.ts.map +1 -1
  40. package/dist/stages/alt-audio/index.js +31 -11
  41. package/dist/stages/alt-audio/index.js.map +1 -1
  42. package/dist/stages/text-cea608/index.d.ts +9 -2
  43. package/dist/stages/text-cea608/index.d.ts.map +1 -1
  44. package/dist/stages/text-cea608/index.js +90 -16
  45. package/dist/stages/text-cea608/index.js.map +1 -1
  46. package/dist/stages/text-webvtt/index.d.ts +3 -0
  47. package/dist/stages/text-webvtt/index.d.ts.map +1 -1
  48. package/dist/stages/text-webvtt/index.js +9 -4
  49. package/dist/stages/text-webvtt/index.js.map +1 -1
  50. package/dist/types/facade.d.ts +6 -0
  51. package/dist/types/facade.d.ts.map +1 -1
  52. package/dist/types/ir.d.ts +6 -0
  53. package/dist/types/ir.d.ts.map +1 -1
  54. package/dist/types/kernel.d.ts +3 -1
  55. package/dist/types/kernel.d.ts.map +1 -1
  56. package/dist/types/kernel.js.map +1 -1
  57. package/dist/types/messages.d.ts +11 -1
  58. package/dist/types/messages.d.ts.map +1 -1
  59. package/package.json +1 -1
@@ -136,7 +136,8 @@ function mattebox(options) {
136
136
  getState: () => bus.getState(),
137
137
  dispatch: (cmd) => bus.dispatch(cmd),
138
138
  emitEvent: (event, payload) => bus.emitEvent(event, payload),
139
- hasSink: (contentType) => bus.sinkFor(contentType) !== void 0
139
+ hasSink: (contentType) => bus.sinkFor(contentType) !== void 0,
140
+ plays: (contentType, mimeType) => bus.capabilities().some((c) => typeof c !== "string" && c.contentType === contentType && c.mimeType === mimeType)
140
141
  });
141
142
  const arbiter = createArbiter();
142
143
  const hooks = {
@@ -353,11 +353,10 @@ function reduceCommand(state, msg, cfg, hooks) {
353
353
  }]];
354
354
  }
355
355
  case "SELECT_TRACK": {
356
- var _state$quality$constr, _state$quality$constr2, _segmentedAt, _previousTrack$rendit;
356
+ var _segmentedAt, _previousTrack$rendit;
357
357
  const track = findTrack(state.presentation, msg.trackId);
358
358
  if (track === null) return reject(state, msg.type, `unknown track: ${msg.trackId}`);
359
- const undecodableIds = (_state$quality$constr = (_state$quality$constr2 = state.quality.constraints.get(CODECS)) === null || _state$quality$constr2 === void 0 ? void 0 : _state$quality$constr2.excludeIds) !== null && _state$quality$constr !== void 0 ? _state$quality$constr : [];
360
- if (track.renditions.length > 0 && track.renditions.every((r) => undecodableIds.includes(r.id))) return reject(state, msg.type, `undecodable track: ${msg.trackId}`);
359
+ if (isUndecodable(state, track)) return reject(state, msg.type, `undecodable track: ${msg.trackId}`);
361
360
  const previous = state.tracks.active.get(track.contentType);
362
361
  const active = new Map(state.tracks.active);
363
362
  active.set(track.contentType, track.id);
@@ -521,10 +520,47 @@ function reduceCommand(state, msg, cfg, hooks) {
521
520
  }), []];
522
521
  }
523
522
  case "ABORT_INFLIGHT": return abortInflight(state, msg.trackId);
523
+ case "ADD_TRACK": {
524
+ var _state$tracks$added;
525
+ if (state.presentation === null) return reject(state, msg.type, "no source");
526
+ if (findTrack(state.presentation, msg.track.id) !== null) return reject(state, msg.type, `track exists: ${msg.track.id}`);
527
+ const added = [...(_state$tracks$added = state.tracks.added) !== null && _state$tracks$added !== void 0 ? _state$tracks$added : [], msg.track];
528
+ const presentation = withAdded(state.presentation, added);
529
+ const available = presentation.periods.flatMap((period) => period.tracks.map((t) => t.id));
530
+ return [_objectSpread2(_objectSpread2({}, state), {}, {
531
+ presentation,
532
+ tracks: _objectSpread2(_objectSpread2({}, state.tracks), {}, {
533
+ added,
534
+ available
535
+ })
536
+ }), [{
537
+ kind: "emit",
538
+ event: "tracks:changed",
539
+ payload: { available }
540
+ }]];
541
+ }
524
542
  }
525
543
  }
544
+ /**
545
+ * Joins the tracks ADD_TRACK added to every period that lacks them. A
546
+ * playlist merge hands the reducer the adapter's presentation, which knows
547
+ * nothing of them.
548
+ */
549
+ function withAdded(presentation, added) {
550
+ if (added === void 0 || added.length === 0) return presentation;
551
+ return _objectSpread2(_objectSpread2({}, presentation), {}, { periods: presentation.periods.map((period) => {
552
+ const missing = added.filter((track) => !period.tracks.some((t) => t.id === track.id));
553
+ return missing.length === 0 ? period : _objectSpread2(_objectSpread2({}, period), {}, { tracks: [...period.tracks, ...missing] });
554
+ }) });
555
+ }
526
556
  /** The constraint source for renditions this browser cannot decode. */
527
557
  const CODECS = "codecs";
558
+ /** Whether the browser decodes none of a track's renditions, from the codec filter. */
559
+ function isUndecodable(state, track) {
560
+ var _state$quality$constr, _state$quality$constr2;
561
+ const excluded = (_state$quality$constr = (_state$quality$constr2 = state.quality.constraints.get(CODECS)) === null || _state$quality$constr2 === void 0 ? void 0 : _state$quality$constr2.excludeIds) !== null && _state$quality$constr !== void 0 ? _state$quality$constr : [];
562
+ return track.renditions.length > 0 && track.renditions.every((r) => excluded.includes(r.id));
563
+ }
528
564
  /**
529
565
  * The renditions this browser cannot play: a declared codec it does not
530
566
  * decode, and a video variant whose audio group it cannot decode at all.
@@ -544,7 +580,8 @@ function undecodable(presentation, decodable) {
544
580
  * A presentation replaces the one held: a manifest landed, or a playlist
545
581
  * merged into it. Activates default tracks and reports what changed.
546
582
  */
547
- function loadPresentation(state, presentation, undecodableIds = /* @__PURE__ */ new Set()) {
583
+ function loadPresentation(state, merged, undecodableIds = /* @__PURE__ */ new Set()) {
584
+ const presentation = withAdded(merged, state.tracks.added);
548
585
  const available = [];
549
586
  for (const period of presentation.periods) for (const track of period.tracks) available.push(track.id);
550
587
  const inflight = new Map(state.scheduling.inflight);
@@ -1205,7 +1242,8 @@ const COMMAND_TYPES = {
1205
1242
  RELEASE_CONSTRAINT: true,
1206
1243
  SET_BUFFER_GOAL: true,
1207
1244
  RESOLVE_RENDITION: true,
1208
- ABORT_INFLIGHT: true
1245
+ ABORT_INFLIGHT: true,
1246
+ ADD_TRACK: true
1209
1247
  };
1210
1248
  function isCommand(msg) {
1211
1249
  return msg.type in COMMAND_TYPES;
@@ -1276,4 +1314,4 @@ function createReducer(slices, config, hooks = {}) {
1276
1314
  };
1277
1315
  }
1278
1316
  //#endregion
1279
- export { DEFAULT_KERNEL_CONFIG, createReducer, initialState, isCommand, resolveConfig };
1317
+ export { DEFAULT_KERNEL_CONFIG, createReducer, initialState, isCommand, isUndecodable, resolveConfig };
@@ -1,5 +1,15 @@
1
1
  import { findTrackSite, isTrick } from "./presentation.js";
2
+ import { isUndecodable } from "./reducer.js";
2
3
  //#region src/kernel/track-registry.ts
4
+ /**
5
+ * Cue tracks need a stage for their format, not only a sink: one text sink
6
+ * serves every subtitle format, and a WebVTT stage cannot read TTML. Media
7
+ * formats are the browser's to decode, which the codec filter answers.
8
+ */
9
+ function formatPlays(deps, track) {
10
+ if (track.contentType !== "text" && track.contentType !== "metadata") return true;
11
+ return deps.plays(track.contentType, track.mimeType);
12
+ }
3
13
  function allTracks(state) {
4
14
  if (state.presentation === null) return [];
5
15
  return state.presentation.periods.flatMap((period) => period.tracks);
@@ -20,7 +30,7 @@ function createTrackRegistry(deps) {
20
30
  },
21
31
  selectable(trackId) {
22
32
  const track = find(trackId);
23
- return track !== null && deps.hasSink(track.contentType);
33
+ return track !== null && !isTrick(track) && deps.hasSink(track.contentType) && formatPlays(deps, track) && !isUndecodable(deps.getState(), track);
24
34
  },
25
35
  select(trackId) {
26
36
  const track = find(trackId);
@@ -38,6 +48,13 @@ function createTrackRegistry(deps) {
38
48
  });
39
49
  return;
40
50
  }
51
+ if (track !== null && !formatPlays(deps, track)) {
52
+ deps.emitEvent("command:rejected", {
53
+ command: "SELECT_TRACK",
54
+ reason: `no stage plays '${track.mimeType}'`
55
+ });
56
+ return;
57
+ }
41
58
  deps.dispatch({
42
59
  type: "SELECT_TRACK",
43
60
  trackId
@@ -136,6 +136,39 @@ function audioCharacteristics(adaptationSet) {
136
136
  }
137
137
  return tags;
138
138
  }
139
+ const CEA608_SCHEME = "urn:scte:dash:cc:cea-608:2015";
140
+ /**
141
+ * SCTE 214-1: an Accessibility descriptor with the CEA-608 scheme names the
142
+ * in-band caption channels of a video AdaptationSet, as "CC1=eng;CC3=fre",
143
+ * "1=eng", or bare languages. Bare languages take CC1 and CC3 when there
144
+ * are two, else CC1 to CC4 in order; an empty value means CC1. This is the
145
+ * reading Shaka Player applies.
146
+ */
147
+ function captionChannels(adaptationSet) {
148
+ const out = [];
149
+ for (const descriptor of children(adaptationSet, "Accessibility")) {
150
+ var _attr6;
151
+ if (attr(descriptor, "schemeIdUri") !== CEA608_SCHEME) continue;
152
+ const value = ((_attr6 = attr(descriptor, "value")) !== null && _attr6 !== void 0 ? _attr6 : "").trim();
153
+ if (value === "") {
154
+ out.push(["CC1", null]);
155
+ continue;
156
+ }
157
+ const entries = value.split(";");
158
+ let next = 1;
159
+ for (const entry of entries) {
160
+ const [left, right] = entry.split("=");
161
+ if (right === void 0) {
162
+ out.push([`CC${next}`, left.trim() || null]);
163
+ next += entries.length === 2 ? 2 : 1;
164
+ } else {
165
+ const channel = left.trim().startsWith("CC") ? left.trim() : `CC${left.trim()}`;
166
+ out.push([channel, right.trim() || null]);
167
+ }
168
+ }
169
+ }
170
+ return out;
171
+ }
139
172
  /**
140
173
  * A trick-mode AdaptationSet: the DASH-IF trickmode EssentialProperty, or a
141
174
  * representation declaring a playout rate other than 1. Both mark an
@@ -144,8 +177,8 @@ function audioCharacteristics(adaptationSet) {
144
177
  */
145
178
  function isTrickMode(adaptationSet) {
146
179
  for (const property of children(adaptationSet, "EssentialProperty")) {
147
- var _attr6;
148
- if (((_attr6 = attr(property, "schemeIdUri")) !== null && _attr6 !== void 0 ? _attr6 : "").includes("trickmode")) return true;
180
+ var _attr7;
181
+ if (((_attr7 = attr(property, "schemeIdUri")) !== null && _attr7 !== void 0 ? _attr7 : "").includes("trickmode")) return true;
149
182
  }
150
183
  if (numberAttr(adaptationSet, "maxPlayoutRate") !== null) return true;
151
184
  for (const representation of children(adaptationSet, "Representation")) {
@@ -164,8 +197,8 @@ function tileGridOf(representation, adaptationSet, width, height) {
164
197
  if (width === null || height === null) return null;
165
198
  const properties = [...children(representation, "EssentialProperty"), ...children(adaptationSet, "EssentialProperty")];
166
199
  for (const property of properties) {
167
- var _attr7;
168
- if (!((_attr7 = attr(property, "schemeIdUri")) !== null && _attr7 !== void 0 ? _attr7 : "").includes("thumbnail_tile")) continue;
200
+ var _attr8;
201
+ if (!((_attr8 = attr(property, "schemeIdUri")) !== null && _attr8 !== void 0 ? _attr8 : "").includes("thumbnail_tile")) continue;
169
202
  const grid = dimensions(attr(property, "value"));
170
203
  if (grid === null) continue;
171
204
  const [columns, rows] = grid;
@@ -190,12 +223,12 @@ function mergeTemplates(levels) {
190
223
  let timelineElement = null;
191
224
  let found = false;
192
225
  for (const level of levels) {
193
- var _attr8, _attr9, _numberAttr, _numberAttr2, _numberAttr3, _numberAttr4, _children$2;
226
+ var _attr9, _attr10, _numberAttr, _numberAttr2, _numberAttr3, _numberAttr4, _children$2;
194
227
  const template = children(level, "SegmentTemplate")[0];
195
228
  if (template === void 0) continue;
196
229
  found = true;
197
- media = (_attr8 = attr(template, "media")) !== null && _attr8 !== void 0 ? _attr8 : media;
198
- initialization = (_attr9 = attr(template, "initialization")) !== null && _attr9 !== void 0 ? _attr9 : initialization;
230
+ media = (_attr9 = attr(template, "media")) !== null && _attr9 !== void 0 ? _attr9 : media;
231
+ initialization = (_attr10 = attr(template, "initialization")) !== null && _attr10 !== void 0 ? _attr10 : initialization;
199
232
  timescale = (_numberAttr = numberAttr(template, "timescale")) !== null && _numberAttr !== void 0 ? _numberAttr : timescale;
200
233
  startNumber = (_numberAttr2 = numberAttr(template, "startNumber")) !== null && _numberAttr2 !== void 0 ? _numberAttr2 : startNumber;
201
234
  duration = (_numberAttr3 = numberAttr(template, "duration")) !== null && _numberAttr3 !== void 0 ? _numberAttr3 : duration;
@@ -262,7 +295,7 @@ function contentTypeOf(adaptationSet, mimeType) {
262
295
  }
263
296
  /** parse an MPD document into a Presentation. Never throws. */
264
297
  function parse(text, baseUrl) {
265
- var _parseDuration, _parseDuration2, _attr17;
298
+ var _parseDuration, _parseDuration2, _attr18;
266
299
  let doc;
267
300
  try {
268
301
  doc = new DOMParser().parseFromString(text, "text/xml");
@@ -282,15 +315,15 @@ function parse(text, baseUrl) {
282
315
  const mpdBase = applyBaseUrl(mpd, baseUrl);
283
316
  let live;
284
317
  if (isLive) {
285
- var _attr10, _attr11, _attr12;
286
- const availabilityStart = Date.parse((_attr10 = attr(mpd, "availabilityStartTime")) !== null && _attr10 !== void 0 ? _attr10 : "");
318
+ var _attr11, _attr12, _attr13;
319
+ const availabilityStart = Date.parse((_attr11 = attr(mpd, "availabilityStartTime")) !== null && _attr11 !== void 0 ? _attr11 : "");
287
320
  const updatePeriod = parseDuration(attr(mpd, "minimumUpdatePeriod"));
288
321
  const timeShiftDepth = parseDuration(attr(mpd, "timeShiftBufferDepth"));
289
322
  const holdBack = parseDuration(attr(mpd, "suggestedPresentationDelay"));
290
323
  const timing = children(mpd, "UTCTiming")[0];
291
324
  live = _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, Number.isFinite(availabilityStart) ? { availabilityStart: availabilityStart / 1e3 } : {}), updatePeriod !== null ? { updatePeriod } : {}), timeShiftDepth !== null ? { timeShiftDepth } : {}), holdBack !== null ? { holdBack } : {}), timing !== void 0 ? { timeServer: {
292
- scheme: (_attr11 = attr(timing, "schemeIdUri")) !== null && _attr11 !== void 0 ? _attr11 : "",
293
- value: (_attr12 = attr(timing, "value")) !== null && _attr12 !== void 0 ? _attr12 : ""
325
+ scheme: (_attr12 = attr(timing, "schemeIdUri")) !== null && _attr12 !== void 0 ? _attr12 : "",
326
+ value: (_attr13 = attr(timing, "value")) !== null && _attr13 !== void 0 ? _attr13 : ""
294
327
  } } : {});
295
328
  }
296
329
  let steering;
@@ -340,16 +373,16 @@ function parse(text, baseUrl) {
340
373
  const renditions = [];
341
374
  let trackMime = null;
342
375
  for (const representation of children(adaptationSet, "Representation")) {
343
- var _ref, _attr13, _trackMime, _parseFrameRate2, _numberAttr8, _attr16;
376
+ var _ref, _attr14, _trackMime, _parseFrameRate2, _numberAttr8, _attr17;
344
377
  const id = attr(representation, "id");
345
378
  const bandwidth = numberAttr(representation, "bandwidth");
346
379
  if (id === null || bandwidth === null) continue;
347
380
  const repBase = applyBaseUrl(representation, asBase);
348
- const mimeType = (_ref = (_attr13 = attr(representation, "mimeType")) !== null && _attr13 !== void 0 ? _attr13 : asMime) !== null && _ref !== void 0 ? _ref : "video/mp4";
381
+ const mimeType = (_ref = (_attr14 = attr(representation, "mimeType")) !== null && _attr14 !== void 0 ? _attr14 : asMime) !== null && _ref !== void 0 ? _ref : "video/mp4";
349
382
  trackMime = (_trackMime = trackMime) !== null && _trackMime !== void 0 ? _trackMime : mimeType;
350
383
  const segmentBase = children(representation, "SegmentBase")[0];
351
384
  if (segmentBase !== void 0) {
352
- var _numberAttr7, _parseFrameRate, _attr14;
385
+ var _numberAttr7, _parseFrameRate, _attr15;
353
386
  const indexRange = parseByteRange(attr(segmentBase, "indexRange"));
354
387
  if (indexRange === null) continue;
355
388
  const baseTimescale = (_numberAttr7 = numberAttr(segmentBase, "timescale")) !== null && _numberAttr7 !== void 0 ? _numberAttr7 : 1;
@@ -372,7 +405,7 @@ function parse(text, baseUrl) {
372
405
  renditions.push(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({
373
406
  id,
374
407
  bitrate: bandwidth,
375
- codecs: (_attr14 = attr(representation, "codecs")) !== null && _attr14 !== void 0 ? _attr14 : asCodecs,
408
+ codecs: (_attr15 = attr(representation, "codecs")) !== null && _attr15 !== void 0 ? _attr15 : asCodecs,
376
409
  mimeType,
377
410
  segments: sidxSegments
378
411
  }, sidxInit !== null ? { init: sidxInit } : {}), w !== null ? { width: w } : {}), h !== null ? { height: h } : {}), fr !== null ? { frameRate: fr } : {}));
@@ -385,11 +418,11 @@ function parse(text, baseUrl) {
385
418
  ]);
386
419
  if (template === null || template.media === null) {
387
420
  if (contentTypeOf(adaptationSet, mimeType) === "text" && periodDuration !== null) {
388
- var _attr15;
421
+ var _attr16;
389
422
  renditions.push({
390
423
  id,
391
424
  bitrate: bandwidth,
392
- codecs: (_attr15 = attr(representation, "codecs")) !== null && _attr15 !== void 0 ? _attr15 : asCodecs,
425
+ codecs: (_attr16 = attr(representation, "codecs")) !== null && _attr16 !== void 0 ? _attr16 : asCodecs,
393
426
  mimeType,
394
427
  segments: [{
395
428
  seq: 0,
@@ -432,7 +465,7 @@ function parse(text, baseUrl) {
432
465
  renditions.push(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({
433
466
  id,
434
467
  bitrate: bandwidth,
435
- codecs: (_attr16 = attr(representation, "codecs")) !== null && _attr16 !== void 0 ? _attr16 : asCodecs,
468
+ codecs: (_attr17 = attr(representation, "codecs")) !== null && _attr17 !== void 0 ? _attr17 : asCodecs,
436
469
  mimeType,
437
470
  segments
438
471
  }, init !== null ? { init } : {}), width !== null ? { width } : {}), height !== null ? { height } : {}), frameRate !== null ? { frameRate } : {}), tiles !== null ? { tiles } : {}), playoutRate !== null ? { maxPlayoutRate: playoutRate } : {}));
@@ -450,6 +483,21 @@ function parse(text, baseUrl) {
450
483
  renditions
451
484
  }, lang !== null ? { lang } : {}), role !== null ? { role } : {}), roles.length > 0 ? { roles } : {}), characteristics.length > 0 ? { characteristics } : {}), forced ? { forced: true } : {}));
452
485
  }
486
+ const hasVideo = tracks.some((t) => t.contentType === "video");
487
+ for (const adaptationSet of hasVideo ? adaptationSets : []) for (const [instreamId, lang] of captionChannels(adaptationSet)) {
488
+ const id = `cea608:${instreamId}`;
489
+ if (!/^CC[1-4]$/.test(instreamId) || tracks.some((t) => t.id === id)) continue;
490
+ tracks.push(_objectSpread2(_objectSpread2({
491
+ id,
492
+ contentType: "text",
493
+ mimeType: "application/cea-608",
494
+ protection: null
495
+ }, lang !== null ? { lang } : {}), {}, {
496
+ role: "caption",
497
+ instreamId,
498
+ renditions: []
499
+ }));
500
+ }
453
501
  if (tracks.length === 0) return {
454
502
  presentation: null,
455
503
  error: {
@@ -466,7 +514,7 @@ function parse(text, baseUrl) {
466
514
  isLive
467
515
  }, mpdDuration !== null ? { duration: mpdDuration } : {}), {}, {
468
516
  periods: [_objectSpread2(_objectSpread2({
469
- id: (_attr17 = attr(periodElement, "id")) !== null && _attr17 !== void 0 ? _attr17 : "p0",
517
+ id: (_attr18 = attr(periodElement, "id")) !== null && _attr18 !== void 0 ? _attr18 : "p0",
470
518
  start: periodStart
471
519
  }, periodDuration !== null ? { duration: periodDuration } : {}), {}, { tracks })],
472
520
  couplings: []
@@ -211,6 +211,32 @@ function mediaContentType(type) {
211
211
  if (type === "SUBTITLES") return "text";
212
212
  return null;
213
213
  }
214
+ /** The CHARACTERISTICS tags of a rendition, as written, in order. */
215
+ function characteristicsOf(entry) {
216
+ var _entry$attributes$CHA;
217
+ return ((_entry$attributes$CHA = entry.attributes.CHARACTERISTICS) !== null && _entry$attributes$CHA !== void 0 ? _entry$attributes$CHA : "").split(",").map((tag) => tag.trim()).filter((tag) => tag !== "");
218
+ }
219
+ /**
220
+ * RFC 8216bis §4.4.6.1: a CLOSED-CAPTIONS rendition names an in-band
221
+ * CEA-608 channel (INSTREAM-ID CC1 to CC4) inside the video. It becomes a
222
+ * text track with no segments; the caption stage reads the cues from the
223
+ * video. CEA-708 services (SERVICEn) are left out until a stage decodes them.
224
+ */
225
+ function captionTrack(entry) {
226
+ if (entry.type !== "CLOSED-CAPTIONS") return null;
227
+ const instreamId = entry.attributes["INSTREAM-ID"];
228
+ if (instreamId === void 0 || !/^CC[1-4]$/.test(instreamId)) return null;
229
+ const characteristics = characteristicsOf(entry);
230
+ return _objectSpread2(_objectSpread2(_objectSpread2({
231
+ id: `${entry.groupId}:${entry.name}`,
232
+ contentType: "text",
233
+ mimeType: "application/cea-608",
234
+ protection: null
235
+ }, entry.attributes.LANGUAGE !== void 0 ? { lang: entry.attributes.LANGUAGE } : {}), {}, { role: "caption" }, characteristics.length > 0 ? { characteristics } : {}), {}, {
236
+ instreamId,
237
+ renditions: []
238
+ });
239
+ }
214
240
  /**
215
241
  * The rendition fields a tag with a URI attribute declares: the Roku
216
242
  * EXT-X-IMAGE-STREAM-INF and the RFC 8216 §4.3.4.3 EXT-X-I-FRAME-STREAM-INF.
@@ -463,12 +489,17 @@ function parse(text, baseUrl) {
463
489
  });
464
490
  }
465
491
  for (const entry of mediaEntries) {
466
- var _variants$find, _entry$attributes$CHA;
492
+ var _variants$find;
493
+ const caption = captionTrack(entry);
494
+ if (caption !== null) {
495
+ tracks.push(caption);
496
+ continue;
497
+ }
467
498
  const contentType = mediaContentType(entry.type);
468
499
  if (contentType === null || entry.uri === null) continue;
469
500
  const { audio } = splitCodecs((_variants$find = variants.find((v) => v.attributes.AUDIO === entry.groupId)) === null || _variants$find === void 0 ? void 0 : _variants$find.attributes.CODECS);
470
501
  const mimeType = contentType === "audio" ? "audio/mp4" : "text/vtt";
471
- const characteristics = ((_entry$attributes$CHA = entry.attributes.CHARACTERISTICS) !== null && _entry$attributes$CHA !== void 0 ? _entry$attributes$CHA : "").split(",").map((tag) => tag.trim()).filter((tag) => tag !== "");
502
+ const characteristics = characteristicsOf(entry);
472
503
  tracks.push(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({
473
504
  id: `${entry.groupId}:${entry.name}`,
474
505
  contentType,
@@ -14,21 +14,28 @@ import { groupOf } from "../../kernel/rendition-select.js";
14
14
  * that group — preferring the current language so a group switch does not
15
15
  * silently change languages.
16
16
  *
17
- * A user language choice is remembered and re-applied on top of every
18
- * group switch, so `alt-audio` never fights `engine.tracks.select`.
17
+ * A user choice is remembered as its language and its characteristics, and
18
+ * re-applied on top of every group switch, so `alt-audio` never fights
19
+ * `engine.tracks.select`: an audio description track chosen in one group
20
+ * stays an audio description track in the next, not the regular track in
21
+ * the same language.
19
22
  */
20
- const INITIAL = { preferredLang: null };
23
+ const INITIAL = {
24
+ preferredLang: null,
25
+ preferredCharacteristics: []
26
+ };
21
27
  /** Audio tracks with their group parsed from the `group:name` id convention. */
22
28
  function audioTracks(kernel) {
23
29
  var _kernel$presentation$, _kernel$presentation;
24
30
  const out = [];
25
31
  for (const period of (_kernel$presentation$ = (_kernel$presentation = kernel.presentation) === null || _kernel$presentation === void 0 ? void 0 : _kernel$presentation.periods) !== null && _kernel$presentation$ !== void 0 ? _kernel$presentation$ : []) for (const track of period.tracks) {
26
- var _track$lang;
32
+ var _track$lang, _track$characteristic;
27
33
  if (track.contentType !== "audio") continue;
28
34
  out.push({
29
35
  id: track.id,
30
36
  group: groupOf(track.id),
31
37
  lang: (_track$lang = track.lang) !== null && _track$lang !== void 0 ? _track$lang : null,
38
+ characteristics: (_track$characteristic = track.characteristics) !== null && _track$characteristic !== void 0 ? _track$characteristic : [],
32
39
  isDefault: track.role === "main"
33
40
  });
34
41
  }
@@ -42,12 +49,21 @@ function requiredGroup(kernel) {
42
49
  const coupling = (_kernel$presentation2 = kernel.presentation) === null || _kernel$presentation2 === void 0 ? void 0 : _kernel$presentation2.couplings.find((c) => c.renditionId === activeVideo);
43
50
  return (_coupling$requires$au = coupling === null || coupling === void 0 ? void 0 : coupling.requires.audio) !== null && _coupling$requires$au !== void 0 ? _coupling$requires$au : null;
44
51
  }
45
- /** Picks the audio track in `group`, preferring a language, then default, then first. */
46
- function pickInGroup(tracks, group, preferredLang) {
47
- var _ref, _ref2;
52
+ function sameTags(a, b) {
53
+ return a.length === b.length && a.every((tag) => b.includes(tag));
54
+ }
55
+ /**
56
+ * Picks the audio track in `group`: the preferred language with the
57
+ * preferred characteristics, then the language alone, then default, then
58
+ * first.
59
+ */
60
+ function pickInGroup(tracks, group, preference) {
61
+ var _ref, _ref2, _sameLang$find;
48
62
  const inGroup = tracks.filter((t) => t.group === group);
49
63
  if (inGroup.length === 0) return null;
50
- return (_ref = (_ref2 = preferredLang !== null ? inGroup.find((t) => t.lang === preferredLang) : void 0) !== null && _ref2 !== void 0 ? _ref2 : inGroup.find((t) => t.isDefault)) !== null && _ref !== void 0 ? _ref : inGroup[0];
64
+ const { preferredLang, preferredCharacteristics } = preference;
65
+ const sameLang = preferredLang !== null ? inGroup.filter((t) => t.lang === preferredLang) : [];
66
+ return (_ref = (_ref2 = (_sameLang$find = sameLang.find((t) => sameTags(t.characteristics, preferredCharacteristics))) !== null && _sameLang$find !== void 0 ? _sameLang$find : sameLang[0]) !== null && _ref2 !== void 0 ? _ref2 : inGroup.find((t) => t.isDefault)) !== null && _ref !== void 0 ? _ref : inGroup[0];
51
67
  }
52
68
  /** Loops a command back into the bus through a zero-delay schedule effect. */
53
69
  function select(trackId) {
@@ -61,9 +77,13 @@ const reduceAltAudio = (slice, msg, kernel) => {
61
77
  const state = slice !== null && slice !== void 0 ? slice : INITIAL;
62
78
  if (msg.type === "LOAD" || msg.type === "UNLOAD" || msg.type === "DETACH") return [INITIAL, []];
63
79
  if (msg.type === "SELECT_TRACK") {
80
+ var _chosen$lang;
64
81
  const chosen = audioTracks(kernel).find((t) => t.id === msg.trackId);
65
- if ((chosen === null || chosen === void 0 ? void 0 : chosen.lang) != null) return [{ preferredLang: chosen.lang }, []];
66
- return [state, []];
82
+ if (chosen === void 0) return [state, []];
83
+ return [{
84
+ preferredLang: (_chosen$lang = chosen.lang) !== null && _chosen$lang !== void 0 ? _chosen$lang : state.preferredLang,
85
+ preferredCharacteristics: chosen.characteristics
86
+ }, []];
67
87
  }
68
88
  if (msg.type === "MANIFEST_LOADED" || msg.type === "PLAYLIST_REFRESHED" || msg.type === "SEGMENT_LOADED") {
69
89
  const group = requiredGroup(kernel);
@@ -72,7 +92,7 @@ const reduceAltAudio = (slice, msg, kernel) => {
72
92
  const tracks = audioTracks(kernel);
73
93
  const activeInfo = tracks.find((t) => t.id === active);
74
94
  if (activeInfo !== void 0 && activeInfo.group === group) return [state, []];
75
- const target = pickInGroup(tracks, group, state.preferredLang);
95
+ const target = pickInGroup(tracks, group, state);
76
96
  if (target === void 0 || target === null || target.id === active) return [state, []];
77
97
  return [state, [select(target.id)]];
78
98
  }
@@ -9,45 +9,114 @@ import { Cea608Decoder } from "./decode.js";
9
9
  * The stage imports neither source, only the shared registry, which is what
10
10
  * lets one decoder serve both routes (entanglement #1).
11
11
  *
12
+ * The captions are a text track like any subtitle: selectable through
13
+ * `engine.tracks`, and listed in a player's menu. The manifest declares the
14
+ * track (HLS CLOSED-CAPTIONS, DASH cea-608 Accessibility). A stream that
15
+ * declares none gets one added on its first cue (ADD_TRACK). The decoder
16
+ * reads CC1, so the stage plays the CC1 track.
17
+ *
12
18
  * Decoded captions become native VTTCues on a caption TextTrack, rendered by
13
- * the browser like any text track. The track is created on the first cue and
14
- * left off by default; the viewer or the app turns it on.
19
+ * the browser. The stage keeps that track and the engine's text selection
20
+ * in step, both ways, as text-webvtt does for its own tracks: showing while
21
+ * the caption track is selected, hidden otherwise, so cues keep arriving.
15
22
  */
23
+ const MIME = "application/cea-608";
24
+ /** The channel the decoder reads: field 1, channel 1. */
25
+ const CHANNEL = "CC1";
26
+ /** The track a stream gets when its manifest declares no captions. */
27
+ const ADDED = {
28
+ id: "cea608:CC1",
29
+ contentType: "text",
30
+ mimeType: MIME,
31
+ protection: null,
32
+ role: "caption",
33
+ instreamId: CHANNEL,
34
+ renditions: []
35
+ };
16
36
  function textCea608() {
17
37
  return {
18
38
  name: "text-cea608",
19
39
  provides: ["text-cea608", {
20
40
  contentType: "text",
21
- mimeType: "application/cea-608"
41
+ mimeType: MIME
22
42
  }],
23
43
  requires: [["nal-scan", "ts-transmux"]],
24
44
  install(ctx) {
25
45
  const decoder = new Cea608Decoder();
26
46
  const element = ctx.element;
27
- let track = null;
28
- /** Empties the track. `cues` reads null while disabled; hidden makes them removable. */
29
- function ensureTrack() {
30
- if (track === null) {
31
- track = adoptTextTrack(element, "captions", "CC1", "en");
32
- track.mode = "hidden";
47
+ let native = null;
48
+ let adding = false;
49
+ /** The CC1 caption track of the presentation, declared or added. */
50
+ function captionTrack() {
51
+ var _ctx$getState$present, _ctx$getState$present2;
52
+ for (const period of (_ctx$getState$present = (_ctx$getState$present2 = ctx.getState().presentation) === null || _ctx$getState$present2 === void 0 ? void 0 : _ctx$getState$present2.periods) !== null && _ctx$getState$present !== void 0 ? _ctx$getState$present : []) for (const track of period.tracks) if (track.mimeType === MIME && track.instreamId === CHANNEL) return track;
53
+ return null;
54
+ }
55
+ function selected(track) {
56
+ return track !== null && ctx.getState().tracks.active.get("text") === track.id;
57
+ }
58
+ /** The native track, created on first need. Hidden keeps cues arriving and removable. */
59
+ function ensureNative() {
60
+ if (native === null) {
61
+ var _captionTrack;
62
+ native = adoptTextTrack(element, "captions", CHANNEL, (_captionTrack = captionTrack()) === null || _captionTrack === void 0 ? void 0 : _captionTrack.lang);
63
+ native.mode = "hidden";
33
64
  }
34
- return track;
65
+ return native;
66
+ }
67
+ function mirror() {
68
+ const showing = selected(captionTrack());
69
+ if (native === null && !showing) return;
70
+ const target = ensureNative();
71
+ const mode = showing ? "showing" : "hidden";
72
+ if (target.mode !== mode) target.mode = mode;
73
+ }
74
+ function onNativeChange() {
75
+ const track = captionTrack();
76
+ if (native === null || track === null) return;
77
+ const on = native.mode === "showing";
78
+ if (on && !selected(track)) ctx.dispatch({
79
+ type: "SELECT_TRACK",
80
+ trackId: track.id
81
+ });
82
+ else if (!on && selected(track)) ctx.dispatch({
83
+ type: "DESELECT_TRACK",
84
+ contentType: "text"
85
+ });
35
86
  }
36
87
  const unregister = registerCaptionConsumer((packets) => {
37
88
  for (const packet of packets) for (const triple of packet.triples) if (triple.type === 0) decoder.push(triple.a, triple.b, packet.time);
38
89
  const cues = decoder.drain();
39
90
  if (cues.length === 0) return;
91
+ if (captionTrack() === null && !adding && ctx.getState().presentation !== null) {
92
+ adding = true;
93
+ ctx.dispatch({
94
+ type: "ADD_TRACK",
95
+ track: ADDED
96
+ });
97
+ }
40
98
  const VttCue = globalThis.VTTCue;
41
99
  if (VttCue === void 0) return;
42
- const target = ensureTrack();
100
+ const target = ensureNative();
43
101
  for (const cue of cues) target.addCue(new VttCue(cue.start, cue.end, cue.text));
44
102
  });
103
+ const offChanged = ctx.on("tracks:changed", () => {
104
+ if (captionTrack() === null) adding = false;
105
+ mirror();
106
+ });
107
+ const offSelected = ctx.on("tracks:selected", (payload) => {
108
+ if (payload.contentType === "text") mirror();
109
+ });
110
+ element.textTracks.addEventListener("change", onNativeChange);
45
111
  return () => {
46
112
  unregister();
47
- if (track !== null) {
48
- emptyTextTrack(track);
49
- track.mode = "disabled";
50
- track = null;
113
+ offChanged();
114
+ offSelected();
115
+ element.textTracks.removeEventListener("change", onNativeChange);
116
+ if (native !== null) {
117
+ emptyTextTrack(native);
118
+ native.mode = "disabled";
119
+ native = null;
51
120
  }
52
121
  };
53
122
  }
@@ -12,7 +12,11 @@ import { createTextTrackSink } from "../../kernel/sinks/text-track-sink.js";
12
12
  * manifest on, so the browser's caption menu lists all of them; the active
13
13
  * one is `showing`, the rest `disabled`. A pick in that menu selects in the
14
14
  * engine, and switching captions off there deselects.
15
+ *
16
+ * It mirrors only its own format. In-band captions are text tracks too, and
17
+ * text-cea608 mirrors those into the caption track it fills itself.
15
18
  */
19
+ const MIME = "text/vtt";
16
20
  function parseSegment(data, _meta) {
17
21
  return parseVtt(new TextDecoder().decode(data)).cues;
18
22
  }
@@ -21,7 +25,7 @@ function textWebvtt() {
21
25
  name: "text-webvtt",
22
26
  provides: ["text-webvtt", {
23
27
  contentType: "text",
24
- mimeType: "text/vtt"
28
+ mimeType: MIME
25
29
  }],
26
30
  requires: ["scheduler"],
27
31
  install(ctx) {
@@ -30,12 +34,12 @@ function textWebvtt() {
30
34
  element,
31
35
  parse: parseSegment
32
36
  });
33
- ctx.registerParser("text/vtt", parseSegment);
37
+ ctx.registerParser(MIME, parseSegment);
34
38
  ctx.registerSink("text", () => sink);
35
39
  function textTracks() {
36
40
  const presentation = ctx.getState().presentation;
37
41
  if (presentation === null) return [];
38
- return presentation.periods.flatMap((period) => period.tracks.filter((track) => track.contentType === "text"));
42
+ return presentation.periods.flatMap((period) => period.tracks.filter((track) => track.contentType === "text" && track.mimeType === MIME));
39
43
  }
40
44
  function activeId() {
41
45
  return ctx.getState().tracks.active.get("text");
@@ -61,7 +65,7 @@ function textWebvtt() {
61
65
  type: "SELECT_TRACK",
62
66
  trackId: showing.id
63
67
  });
64
- } else if (active !== void 0) ctx.dispatch({
68
+ } else if (textTracks().some((track) => track.id === active)) ctx.dispatch({
65
69
  type: "DESELECT_TRACK",
66
70
  contentType: "text"
67
71
  });
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAiBH,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAKvE,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,UAAU,EACV,KAAK,GACN,MAAM,6BAA6B,CAAC;AAGrC,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEjF,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAExD,mBAAmB,kBAAkB,CAAC;AACtC,mBAAmB,mBAAmB,CAAC;AACvC,mBAAmB,eAAe,CAAC;AACnC,mBAAmB,mBAAmB,CAAC;AACvC,mBAAmB,qBAAqB,CAAC;AACzC,mBAAmB,oBAAoB,CAAC;AACxC,mBAAmB,iBAAiB,CAAC;AACrC,mBAAmB,kBAAkB,CAAC;AAEtC;;;;;;GAMG;AAEH,MAAM,WAAW,kBAAkB;CAAG;AAEtC;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAIlE,qEAAqE;AACrE,wBAAgB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,QAAQ,CA0Y3D;yBA1Ye,QAAQ;mBAgZH,gBAAgB,KAAG,QAAQ,GAAG,IAAI"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAiBH,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAKvE,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,UAAU,EACV,KAAK,GACN,MAAM,6BAA6B,CAAC;AAGrC,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEjF,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAExD,mBAAmB,kBAAkB,CAAC;AACtC,mBAAmB,mBAAmB,CAAC;AACvC,mBAAmB,eAAe,CAAC;AACnC,mBAAmB,mBAAmB,CAAC;AACvC,mBAAmB,qBAAqB,CAAC;AACzC,mBAAmB,oBAAoB,CAAC;AACxC,mBAAmB,iBAAiB,CAAC;AACrC,mBAAmB,kBAAkB,CAAC;AAEtC;;;;;;GAMG;AAEH,MAAM,WAAW,kBAAkB;CAAG;AAEtC;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAIlE,qEAAqE;AACrE,wBAAgB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,QAAQ,CAgZ3D;yBAhZe,QAAQ;mBAsZH,gBAAgB,KAAG,QAAQ,GAAG,IAAI"}