@zodal/media 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +73 -2
- package/dist/chunk-3JIQJ7J6.js +148 -0
- package/dist/chunk-3JIQJ7J6.js.map +1 -0
- package/dist/chunk-7I3V4HKP.js +132 -0
- package/dist/chunk-7I3V4HKP.js.map +1 -0
- package/dist/chunk-AMK7QKN7.js +50 -0
- package/dist/chunk-AMK7QKN7.js.map +1 -0
- package/dist/chunk-NBKMSPYQ.js +46 -0
- package/dist/chunk-NBKMSPYQ.js.map +1 -0
- package/dist/chunk-P3EWPYFQ.js +42 -0
- package/dist/chunk-P3EWPYFQ.js.map +1 -0
- package/dist/chunk-YBCEHG5I.js +68 -0
- package/dist/chunk-YBCEHG5I.js.map +1 -0
- package/dist/commands.cjs +198 -0
- package/dist/commands.cjs.map +1 -0
- package/dist/commands.d.cts +17 -0
- package/dist/commands.d.ts +17 -0
- package/dist/commands.js +171 -0
- package/dist/commands.js.map +1 -0
- package/dist/cues.cjs +78 -0
- package/dist/cues.cjs.map +1 -0
- package/dist/cues.d.cts +39 -0
- package/dist/cues.d.ts +39 -0
- package/dist/cues.js +15 -0
- package/dist/cues.js.map +1 -0
- package/dist/follow.cjs +162 -0
- package/dist/follow.cjs.map +1 -0
- package/dist/follow.d.cts +83 -0
- package/dist/follow.d.ts +83 -0
- package/dist/follow.js +19 -0
- package/dist/follow.js.map +1 -0
- package/dist/index.cjs +510 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +59 -0
- package/dist/index.js.map +1 -0
- package/dist/playback.cjs +72 -0
- package/dist/playback.cjs.map +1 -0
- package/dist/playback.d.cts +47 -0
- package/dist/playback.d.ts +47 -0
- package/dist/playback.js +11 -0
- package/dist/playback.js.map +1 -0
- package/dist/sleep.cjs +176 -0
- package/dist/sleep.cjs.map +1 -0
- package/dist/sleep.d.cts +99 -0
- package/dist/sleep.d.ts +99 -0
- package/dist/sleep.js +15 -0
- package/dist/sleep.js.map +1 -0
- package/dist/timed-text.cjs +155 -0
- package/dist/timed-text.cjs.map +1 -0
- package/dist/timed-text.d.cts +44 -0
- package/dist/timed-text.d.ts +44 -0
- package/dist/timed-text.js +9 -0
- package/dist/timed-text.js.map +1 -0
- package/dist/transport.cjs +167 -0
- package/dist/transport.cjs.map +1 -0
- package/dist/transport.d.cts +74 -0
- package/dist/transport.d.ts +74 -0
- package/dist/transport.js +110 -0
- package/dist/transport.js.map +1 -0
- package/dist/vtt.cjs +66 -0
- package/dist/vtt.cjs.map +1 -0
- package/dist/vtt.d.cts +22 -0
- package/dist/vtt.d.ts +22 -0
- package/dist/vtt.js +7 -0
- package/dist/vtt.js.map +1 -0
- package/package.json +155 -4
package/dist/sleep.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_SLEEP_FADE_MS,
|
|
3
|
+
DEFAULT_SLEEP_TICK_MS,
|
|
4
|
+
SLEEP_MINUTES,
|
|
5
|
+
createSleepTimer,
|
|
6
|
+
formatCountdown
|
|
7
|
+
} from "./chunk-3JIQJ7J6.js";
|
|
8
|
+
export {
|
|
9
|
+
DEFAULT_SLEEP_FADE_MS,
|
|
10
|
+
DEFAULT_SLEEP_TICK_MS,
|
|
11
|
+
SLEEP_MINUTES,
|
|
12
|
+
createSleepTimer,
|
|
13
|
+
formatCountdown
|
|
14
|
+
};
|
|
15
|
+
//# sourceMappingURL=sleep.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/timed-text.ts
|
|
21
|
+
var timed_text_exports = {};
|
|
22
|
+
__export(timed_text_exports, {
|
|
23
|
+
createTimedText: () => createTimedText
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(timed_text_exports);
|
|
26
|
+
|
|
27
|
+
// src/cues.ts
|
|
28
|
+
var CUE_EPSILON_S = 0.01;
|
|
29
|
+
function lastStarted(count, startOf, time) {
|
|
30
|
+
let lo = 0;
|
|
31
|
+
let hi = count - 1;
|
|
32
|
+
let at = -1;
|
|
33
|
+
while (lo <= hi) {
|
|
34
|
+
const mid = lo + hi >> 1;
|
|
35
|
+
if (startOf(mid) <= time) {
|
|
36
|
+
at = mid;
|
|
37
|
+
lo = mid + 1;
|
|
38
|
+
} else {
|
|
39
|
+
hi = mid - 1;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return at;
|
|
43
|
+
}
|
|
44
|
+
function cueAt(cues, time, options = {}) {
|
|
45
|
+
const { epsilonS = CUE_EPSILON_S, gaps = false } = options;
|
|
46
|
+
const at = lastStarted(cues.length, (i) => cues[i].start, time + epsilonS);
|
|
47
|
+
if (gaps && at >= 0 && time >= cues[at].end) return -1;
|
|
48
|
+
return at;
|
|
49
|
+
}
|
|
50
|
+
function wordAt(cue, time) {
|
|
51
|
+
const words = cue?.words;
|
|
52
|
+
if (!words?.length) return -1;
|
|
53
|
+
return Math.max(0, lastStarted(words.length, (i) => words[i][0], time));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/playback.ts
|
|
57
|
+
var SEEK_LAND_TIMEOUT_MS = 1500;
|
|
58
|
+
function abortError() {
|
|
59
|
+
const e = new Error("The play was cancelled while its seek was landing.");
|
|
60
|
+
e.name = "AbortError";
|
|
61
|
+
return e;
|
|
62
|
+
}
|
|
63
|
+
function seekLanded(port, { timeoutMs = SEEK_LAND_TIMEOUT_MS, signal } = {}) {
|
|
64
|
+
if (signal?.aborted) return Promise.reject(abortError());
|
|
65
|
+
if (!port.seeking || !port.addEventListener) return Promise.resolve();
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
let timer;
|
|
68
|
+
const settle = () => {
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
port.removeEventListener?.("seeked", landed);
|
|
71
|
+
signal?.removeEventListener("abort", aborted);
|
|
72
|
+
};
|
|
73
|
+
const landed = () => {
|
|
74
|
+
settle();
|
|
75
|
+
resolve();
|
|
76
|
+
};
|
|
77
|
+
const aborted = () => {
|
|
78
|
+
settle();
|
|
79
|
+
reject(abortError());
|
|
80
|
+
};
|
|
81
|
+
timer = setTimeout(() => {
|
|
82
|
+
if (!port.seeking) landed();
|
|
83
|
+
}, timeoutMs);
|
|
84
|
+
port.addEventListener("seeked", landed);
|
|
85
|
+
signal?.addEventListener("abort", aborted);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function seekThenPlay(port, time, options = {}) {
|
|
89
|
+
const play = options.play ?? (() => port.play());
|
|
90
|
+
const wasEnded = !!port.ended;
|
|
91
|
+
port.currentTime = time;
|
|
92
|
+
if (!wasEnded || !port.seeking) return Promise.resolve(play());
|
|
93
|
+
return seekLanded(port, options).then(() => play());
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// src/timed-text.ts
|
|
97
|
+
function createTimedText(cues, port, options = {}) {
|
|
98
|
+
const { playOnTap = true, play, follow, ...lookup } = options;
|
|
99
|
+
let state = { cue: -1, word: -1 };
|
|
100
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
101
|
+
let held = null;
|
|
102
|
+
const tick = () => {
|
|
103
|
+
const time = port.currentTime;
|
|
104
|
+
const cue = cueAt(cues, time, lookup);
|
|
105
|
+
const word = wordAt(cues[cue], time);
|
|
106
|
+
if (cue === state.cue && word === state.word) return;
|
|
107
|
+
const previous = state;
|
|
108
|
+
state = { cue, word };
|
|
109
|
+
listeners.forEach((l) => l(state, previous));
|
|
110
|
+
};
|
|
111
|
+
const cancelHeldPlay = () => {
|
|
112
|
+
if (!held) return false;
|
|
113
|
+
held.abort();
|
|
114
|
+
held = null;
|
|
115
|
+
return true;
|
|
116
|
+
};
|
|
117
|
+
return {
|
|
118
|
+
get: () => state,
|
|
119
|
+
subscribe(listener) {
|
|
120
|
+
listeners.add(listener);
|
|
121
|
+
return () => listeners.delete(listener);
|
|
122
|
+
},
|
|
123
|
+
tick,
|
|
124
|
+
tapCue(index) {
|
|
125
|
+
const cue = cues[index];
|
|
126
|
+
if (!cue) return;
|
|
127
|
+
follow?.resume();
|
|
128
|
+
cancelHeldPlay();
|
|
129
|
+
if (playOnTap && port.paused) {
|
|
130
|
+
const mine = new AbortController();
|
|
131
|
+
held = mine;
|
|
132
|
+
seekThenPlay(port, cue.start, { play, signal: mine.signal }).then(
|
|
133
|
+
() => {
|
|
134
|
+
if (held === mine) held = null;
|
|
135
|
+
},
|
|
136
|
+
() => void 0
|
|
137
|
+
// cancelled, or refused: the host's `play` reports a refusal
|
|
138
|
+
);
|
|
139
|
+
} else {
|
|
140
|
+
port.currentTime = cue.start;
|
|
141
|
+
}
|
|
142
|
+
tick();
|
|
143
|
+
},
|
|
144
|
+
cancelHeldPlay,
|
|
145
|
+
dispose() {
|
|
146
|
+
cancelHeldPlay();
|
|
147
|
+
listeners.clear();
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
152
|
+
0 && (module.exports = {
|
|
153
|
+
createTimedText
|
|
154
|
+
});
|
|
155
|
+
//# sourceMappingURL=timed-text.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/timed-text.ts","../src/cues.ts","../src/playback.ts"],"sourcesContent":["/**\n * A timed text over a media port: which cue and word are being heard, and what a tap on a line\n * does. Renderer-agnostic; a transcript, a lyrics panel and a subtitle line all draw from it.\n *\n * A tap plays from the line by default (a transcript); `playOnTap: false` only moves there (a\n * lyrics panel whose player is elsewhere). Playing from a line uses `seekThenPlay`, so it plays\n * from the line on Safari too after the media has ended.\n */\nimport { cueAt, wordAt, type CueAtOptions, type CueLike } from './cues.js';\nimport { seekThenPlay, type SeekablePort } from './playback.js';\nimport type { Follow } from './follow.js';\n\n/** The part of a media element a timed text uses. */\nexport interface TimedTextPort extends SeekablePort {\n readonly paused: boolean;\n}\n\nexport interface TimedTextState {\n cue: number;\n word: number;\n}\n\nexport interface TimedTextOptions extends CueAtOptions {\n /** A tap on a line plays from it (default) or only moves there. */\n playOnTap?: boolean;\n /** What starting playback means, to catch a refusal; defaults to `port.play()`. */\n play?: () => Promise<void> | void;\n /** A follow state to resume when a line is tapped. */\n follow?: Follow;\n}\n\nexport interface TimedText {\n get(): TimedTextState;\n subscribe(listener: (state: TimedTextState, previous: TimedTextState) => void): () => void;\n /** Read the port's position; call on a frame while playing and on `seeked`. */\n tick(): void;\n /** A person chose line `index`. */\n tapCue(index: number): void;\n /** Cancel a play waiting for its seek (a pause tapped meanwhile). True if there was one. */\n cancelHeldPlay(): boolean;\n /** The view went away: cancel a held play and forget the listeners. */\n dispose(): void;\n}\n\nexport function createTimedText(cues: readonly CueLike[], port: TimedTextPort, options: TimedTextOptions = {}): TimedText {\n const { playOnTap = true, play, follow, ...lookup } = options;\n let state: TimedTextState = { cue: -1, word: -1 };\n const listeners = new Set<(state: TimedTextState, previous: TimedTextState) => void>();\n let held: AbortController | null = null;\n\n const tick = () => {\n const time = port.currentTime;\n const cue = cueAt(cues, time, lookup);\n const word = wordAt(cues[cue], time);\n if (cue === state.cue && word === state.word) return;\n const previous = state;\n state = { cue, word };\n listeners.forEach((l) => l(state, previous));\n };\n const cancelHeldPlay = () => {\n if (!held) return false;\n held.abort();\n held = null;\n return true;\n };\n\n return {\n get: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n tick,\n tapCue(index) {\n const cue = cues[index];\n if (!cue) return;\n follow?.resume();\n cancelHeldPlay();\n if (playOnTap && port.paused) {\n const mine = new AbortController();\n held = mine;\n seekThenPlay(port, cue.start, { play, signal: mine.signal }).then(\n () => { if (held === mine) held = null; },\n () => undefined, // cancelled, or refused: the host's `play` reports a refusal\n );\n } else {\n port.currentTime = cue.start;\n }\n tick();\n },\n cancelHeldPlay,\n dispose() {\n cancelHeldPlay();\n listeners.clear();\n },\n };\n}\n","/**\n * Timed text, looked up by time: which cue and which word are being heard. Pure, no DOM.\n *\n * A cue is a span of text with a start and an end, in seconds, and optionally the times of its\n * words. A spoken overview's sentences (`@zodal/speech`), a song's lyric lines (arioso) and a\n * film's subtitles (srtplay) are all lists of cues. The shape is structural, so this module needs\n * no schema at runtime; the wire model is lacing's (`AlignedTrackV1`, media_hub ADR-0010).\n */\n\n/** The fields of a cue this module reads. `words` are `[start, end, text]`, in seconds. */\nexport interface CueLike {\n start: number;\n end: number;\n text?: string;\n words?: ReadonlyArray<readonly [number, number, string]>;\n}\n\n/**\n * Tolerance so a seek to a cue's own start lands in that cue and not the one before it, after\n * float rounding (`currentTime` is rarely exactly what was set).\n */\nexport const CUE_EPSILON_S = 0.01;\n\nconst SECONDS_PER_MINUTE = 60;\nconst MINUTES_PER_HOUR = 60;\n\n/** The last index `i` of a sorted list with `startOf(i) <= time`, or -1. */\nfunction lastStarted(count: number, startOf: (i: number) => number, time: number): number {\n let lo = 0;\n let hi = count - 1;\n let at = -1;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n if (startOf(mid) <= time) {\n at = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return at;\n}\n\nexport interface CueAtOptions {\n /** See `CUE_EPSILON_S`. */\n epsilonS?: number;\n /**\n * `false` (the default): the last cue that has started stays current through the gap after it,\n * as a transcript or lyrics view wants. `true`: -1 between cues, as subtitles want.\n */\n gaps?: boolean;\n}\n\n/** The index of the cue being heard at `time`: the last one that has started, or -1. */\nexport function cueAt(cues: readonly CueLike[], time: number, options: CueAtOptions = {}): number {\n const { epsilonS = CUE_EPSILON_S, gaps = false } = options;\n const at = lastStarted(cues.length, (i) => cues[i].start, time + epsilonS);\n if (gaps && at >= 0 && time >= cues[at].end) return -1;\n return at;\n}\n\n/** The index of the word being heard within `cue`, or -1 when it has no word times. */\nexport function wordAt(cue: CueLike | undefined, time: number): number {\n const words = cue?.words;\n if (!words?.length) return -1;\n return Math.max(0, lastStarted(words.length, (i) => words[i][0], time));\n}\n\n/** The cues' total length: the last cue's end, which stands in until the media reports its own. */\nexport function cuesDuration(cues: readonly CueLike[]): number {\n return cues.length ? cues[cues.length - 1].end : 0;\n}\n\n/** `m:ss`, or `h:mm:ss` past the hour. */\nexport function formatTime(seconds: number): string {\n const whole = Math.max(0, Math.floor(seconds || 0));\n const hours = Math.floor(whole / (SECONDS_PER_MINUTE * MINUTES_PER_HOUR));\n const minutes = Math.floor(whole / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR;\n const secs = whole % SECONDS_PER_MINUTE;\n const mm = hours && minutes < 10 ? `0${minutes}` : `${minutes}`;\n return `${hours ? `${hours}:` : ''}${mm}:${secs < 10 ? '0' : ''}${secs}`;\n}\n","/**\n * Playing from a chosen point, safely on every engine, with no DOM beyond the port itself.\n *\n * The trap: in WebKit (Safari, and every browser on an iPhone or iPad) `el.currentTime = t;\n * el.play()` on an element that has *ended* starts from the end, which ends again at once, or\n * from 0, because the seek has not landed when `play()` runs. Chromium and Firefox apply the\n * seek first. It shows as \"after the audio finished, tapping a transcript line plays from the\n * start\" (annals, 2026-11-13). Measured in Playwright WebKit: 12 of 12 taps restarted at 0;\n * calling `play()` first and seeking again still failed 10 of 12; waiting for `seeked` and then\n * playing was right 16 of 16.\n *\n * So `seekThenPlay` reads whether the element had ended *before* seeking (after the seek WebKit\n * already reports `ended === false`), and if it had and the seek is still landing, it plays on\n * `seeked`. The element has played before, so playing outside the tap is allowed.\n */\n\n/** The part of a media element `seekThenPlay` uses. The optional members are an HTMLMediaElement's. */\nexport interface SeekablePort {\n currentTime: number;\n play(): Promise<void> | void;\n /** True once playback reached the end. A port without it is never waited on. */\n readonly ended?: boolean;\n /** True while a seek is landing. */\n readonly seeking?: boolean;\n addEventListener?(type: 'seeked', listener: () => void): void;\n removeEventListener?(type: 'seeked', listener: () => void): void;\n}\n\n/** Play anyway after this long, if no seek is under way by then (a seek still landing is still awaited). */\nexport const SEEK_LAND_TIMEOUT_MS = 1500;\n\nexport interface SeekThenPlayOptions {\n /** What starting playback means; defaults to `port.play()`. A player passes its own, to catch a refusal. */\n play?: () => Promise<void> | void;\n timeoutMs?: number;\n /** Cancels a play held for its seek (a pause meanwhile): the promise rejects with an AbortError. */\n signal?: AbortSignal;\n}\n\nfunction abortError(): Error {\n const e = new Error('The play was cancelled while its seek was landing.');\n e.name = 'AbortError';\n return e;\n}\n\n/** Resolves once `port`'s seek has landed (`seeked`), or at once when no seek is landing. */\nexport function seekLanded(\n port: SeekablePort,\n { timeoutMs = SEEK_LAND_TIMEOUT_MS, signal }: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<void> {\n if (signal?.aborted) return Promise.reject(abortError());\n if (!port.seeking || !port.addEventListener) return Promise.resolve();\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const settle = () => {\n clearTimeout(timer);\n port.removeEventListener?.('seeked', landed);\n signal?.removeEventListener('abort', aborted);\n };\n const landed = () => { settle(); resolve(); };\n const aborted = () => { settle(); reject(abortError()); };\n // Playing while the seek is still under way is the bug itself, so the timer only ends a wait\n // whose seek is over without a `seeked` (a source that went away).\n timer = setTimeout(() => { if (!port.seeking) landed(); }, timeoutMs);\n port.addEventListener!('seeked', landed);\n signal?.addEventListener('abort', aborted);\n });\n}\n\n/**\n * Seeks `port` to `time` and plays from there, also when it has ended (see the module note).\n * Plays synchronously, inside the tap, whenever it can; returns what playing returned.\n */\nexport function seekThenPlay(port: SeekablePort, time: number, options: SeekThenPlayOptions = {}): Promise<void> {\n const play = options.play ?? (() => port.play());\n const wasEnded = !!port.ended;\n port.currentTime = time;\n if (!wasEnded || !port.seeking) return Promise.resolve(play());\n return seekLanded(port, options).then(() => play());\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBO,IAAM,gBAAgB;AAM7B,SAAS,YAAY,OAAe,SAAgC,MAAsB;AACxF,MAAI,KAAK;AACT,MAAI,KAAK,QAAQ;AACjB,MAAI,KAAK;AACT,SAAO,MAAM,IAAI;AACf,UAAM,MAAO,KAAK,MAAO;AACzB,QAAI,QAAQ,GAAG,KAAK,MAAM;AACxB,WAAK;AACL,WAAK,MAAM;AAAA,IACb,OAAO;AACL,WAAK,MAAM;AAAA,IACb;AAAA,EACF;AACA,SAAO;AACT;AAaO,SAAS,MAAM,MAA0B,MAAc,UAAwB,CAAC,GAAW;AAChG,QAAM,EAAE,WAAW,eAAe,OAAO,MAAM,IAAI;AACnD,QAAM,KAAK,YAAY,KAAK,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,OAAO,OAAO,QAAQ;AACzE,MAAI,QAAQ,MAAM,KAAK,QAAQ,KAAK,EAAE,EAAE,IAAK,QAAO;AACpD,SAAO;AACT;AAGO,SAAS,OAAO,KAA0B,MAAsB;AACrE,QAAM,QAAQ,KAAK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,IACA;AAAA,IACA,UAAU;AACR,qBAAe;AACf,gBAAU,MAAM;AAAA,IAClB;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { CueAtOptions, CueLike } from './cues.cjs';
|
|
2
|
+
import { SeekablePort } from './playback.cjs';
|
|
3
|
+
import { Follow } from './follow.cjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A timed text over a media port: which cue and word are being heard, and what a tap on a line
|
|
7
|
+
* does. Renderer-agnostic; a transcript, a lyrics panel and a subtitle line all draw from it.
|
|
8
|
+
*
|
|
9
|
+
* A tap plays from the line by default (a transcript); `playOnTap: false` only moves there (a
|
|
10
|
+
* lyrics panel whose player is elsewhere). Playing from a line uses `seekThenPlay`, so it plays
|
|
11
|
+
* from the line on Safari too after the media has ended.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** The part of a media element a timed text uses. */
|
|
15
|
+
interface TimedTextPort extends SeekablePort {
|
|
16
|
+
readonly paused: boolean;
|
|
17
|
+
}
|
|
18
|
+
interface TimedTextState {
|
|
19
|
+
cue: number;
|
|
20
|
+
word: number;
|
|
21
|
+
}
|
|
22
|
+
interface TimedTextOptions extends CueAtOptions {
|
|
23
|
+
/** A tap on a line plays from it (default) or only moves there. */
|
|
24
|
+
playOnTap?: boolean;
|
|
25
|
+
/** What starting playback means, to catch a refusal; defaults to `port.play()`. */
|
|
26
|
+
play?: () => Promise<void> | void;
|
|
27
|
+
/** A follow state to resume when a line is tapped. */
|
|
28
|
+
follow?: Follow;
|
|
29
|
+
}
|
|
30
|
+
interface TimedText {
|
|
31
|
+
get(): TimedTextState;
|
|
32
|
+
subscribe(listener: (state: TimedTextState, previous: TimedTextState) => void): () => void;
|
|
33
|
+
/** Read the port's position; call on a frame while playing and on `seeked`. */
|
|
34
|
+
tick(): void;
|
|
35
|
+
/** A person chose line `index`. */
|
|
36
|
+
tapCue(index: number): void;
|
|
37
|
+
/** Cancel a play waiting for its seek (a pause tapped meanwhile). True if there was one. */
|
|
38
|
+
cancelHeldPlay(): boolean;
|
|
39
|
+
/** The view went away: cancel a held play and forget the listeners. */
|
|
40
|
+
dispose(): void;
|
|
41
|
+
}
|
|
42
|
+
declare function createTimedText(cues: readonly CueLike[], port: TimedTextPort, options?: TimedTextOptions): TimedText;
|
|
43
|
+
|
|
44
|
+
export { type TimedText, type TimedTextOptions, type TimedTextPort, type TimedTextState, createTimedText };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { CueAtOptions, CueLike } from './cues.js';
|
|
2
|
+
import { SeekablePort } from './playback.js';
|
|
3
|
+
import { Follow } from './follow.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A timed text over a media port: which cue and word are being heard, and what a tap on a line
|
|
7
|
+
* does. Renderer-agnostic; a transcript, a lyrics panel and a subtitle line all draw from it.
|
|
8
|
+
*
|
|
9
|
+
* A tap plays from the line by default (a transcript); `playOnTap: false` only moves there (a
|
|
10
|
+
* lyrics panel whose player is elsewhere). Playing from a line uses `seekThenPlay`, so it plays
|
|
11
|
+
* from the line on Safari too after the media has ended.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** The part of a media element a timed text uses. */
|
|
15
|
+
interface TimedTextPort extends SeekablePort {
|
|
16
|
+
readonly paused: boolean;
|
|
17
|
+
}
|
|
18
|
+
interface TimedTextState {
|
|
19
|
+
cue: number;
|
|
20
|
+
word: number;
|
|
21
|
+
}
|
|
22
|
+
interface TimedTextOptions extends CueAtOptions {
|
|
23
|
+
/** A tap on a line plays from it (default) or only moves there. */
|
|
24
|
+
playOnTap?: boolean;
|
|
25
|
+
/** What starting playback means, to catch a refusal; defaults to `port.play()`. */
|
|
26
|
+
play?: () => Promise<void> | void;
|
|
27
|
+
/** A follow state to resume when a line is tapped. */
|
|
28
|
+
follow?: Follow;
|
|
29
|
+
}
|
|
30
|
+
interface TimedText {
|
|
31
|
+
get(): TimedTextState;
|
|
32
|
+
subscribe(listener: (state: TimedTextState, previous: TimedTextState) => void): () => void;
|
|
33
|
+
/** Read the port's position; call on a frame while playing and on `seeked`. */
|
|
34
|
+
tick(): void;
|
|
35
|
+
/** A person chose line `index`. */
|
|
36
|
+
tapCue(index: number): void;
|
|
37
|
+
/** Cancel a play waiting for its seek (a pause tapped meanwhile). True if there was one. */
|
|
38
|
+
cancelHeldPlay(): boolean;
|
|
39
|
+
/** The view went away: cancel a held play and forget the listeners. */
|
|
40
|
+
dispose(): void;
|
|
41
|
+
}
|
|
42
|
+
declare function createTimedText(cues: readonly CueLike[], port: TimedTextPort, options?: TimedTextOptions): TimedText;
|
|
43
|
+
|
|
44
|
+
export { type TimedText, type TimedTextOptions, type TimedTextPort, type TimedTextState, createTimedText };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/transport.ts
|
|
21
|
+
var transport_exports = {};
|
|
22
|
+
__export(transport_exports, {
|
|
23
|
+
createMediaPlayer: () => createMediaPlayer,
|
|
24
|
+
urlSource: () => urlSource
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(transport_exports);
|
|
27
|
+
var import_vanilla = require("zustand/vanilla");
|
|
28
|
+
|
|
29
|
+
// src/playback.ts
|
|
30
|
+
var SEEK_LAND_TIMEOUT_MS = 1500;
|
|
31
|
+
function abortError() {
|
|
32
|
+
const e = new Error("The play was cancelled while its seek was landing.");
|
|
33
|
+
e.name = "AbortError";
|
|
34
|
+
return e;
|
|
35
|
+
}
|
|
36
|
+
function seekLanded(port, { timeoutMs = SEEK_LAND_TIMEOUT_MS, signal } = {}) {
|
|
37
|
+
if (signal?.aborted) return Promise.reject(abortError());
|
|
38
|
+
if (!port.seeking || !port.addEventListener) return Promise.resolve();
|
|
39
|
+
return new Promise((resolve, reject) => {
|
|
40
|
+
let timer;
|
|
41
|
+
const settle = () => {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
port.removeEventListener?.("seeked", landed);
|
|
44
|
+
signal?.removeEventListener("abort", aborted);
|
|
45
|
+
};
|
|
46
|
+
const landed = () => {
|
|
47
|
+
settle();
|
|
48
|
+
resolve();
|
|
49
|
+
};
|
|
50
|
+
const aborted = () => {
|
|
51
|
+
settle();
|
|
52
|
+
reject(abortError());
|
|
53
|
+
};
|
|
54
|
+
timer = setTimeout(() => {
|
|
55
|
+
if (!port.seeking) landed();
|
|
56
|
+
}, timeoutMs);
|
|
57
|
+
port.addEventListener("seeked", landed);
|
|
58
|
+
signal?.addEventListener("abort", aborted);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/transport.ts
|
|
63
|
+
var urlSource = (ref) => ({
|
|
64
|
+
id: ref,
|
|
65
|
+
src: ref,
|
|
66
|
+
title: decodeURIComponent(ref.split("/").pop()?.split("?")[0] ?? ref)
|
|
67
|
+
});
|
|
68
|
+
var clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
|
|
69
|
+
var DEFAULT_SKIP_BACK_S = 15;
|
|
70
|
+
var DEFAULT_SKIP_AHEAD_S = 30;
|
|
71
|
+
function createMediaPlayer(port, options = {}) {
|
|
72
|
+
const { load, skipBackS = DEFAULT_SKIP_BACK_S, skipAheadS = DEFAULT_SKIP_AHEAD_S } = options;
|
|
73
|
+
const store = (0, import_vanilla.createStore)(() => ({
|
|
74
|
+
queue: [],
|
|
75
|
+
index: -1,
|
|
76
|
+
playing: false,
|
|
77
|
+
time: 0,
|
|
78
|
+
duration: 0,
|
|
79
|
+
rate: 1,
|
|
80
|
+
volume: 1
|
|
81
|
+
}));
|
|
82
|
+
const set = store.setState;
|
|
83
|
+
const get = store.getState;
|
|
84
|
+
const sync = () => set({ time: port.currentTime, duration: port.duration || 0, playing: !port.paused });
|
|
85
|
+
let soughtAfterEnd = false;
|
|
86
|
+
let held = null;
|
|
87
|
+
const select = (index) => {
|
|
88
|
+
const item = get().queue[index];
|
|
89
|
+
if (!item) return;
|
|
90
|
+
set({ index });
|
|
91
|
+
load?.(item, port);
|
|
92
|
+
if (item.resumeAt) port.currentTime = item.resumeAt;
|
|
93
|
+
sync();
|
|
94
|
+
};
|
|
95
|
+
const player = {
|
|
96
|
+
store,
|
|
97
|
+
port,
|
|
98
|
+
sync,
|
|
99
|
+
async play() {
|
|
100
|
+
if (get().index < 0 && get().queue.length) select(0);
|
|
101
|
+
if (soughtAfterEnd) {
|
|
102
|
+
held?.abort();
|
|
103
|
+
const mine = held = new AbortController();
|
|
104
|
+
try {
|
|
105
|
+
await seekLanded(port, { signal: mine.signal });
|
|
106
|
+
} catch {
|
|
107
|
+
return;
|
|
108
|
+
} finally {
|
|
109
|
+
if (held === mine) held = null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
soughtAfterEnd = false;
|
|
113
|
+
await port.play();
|
|
114
|
+
sync();
|
|
115
|
+
},
|
|
116
|
+
pause() {
|
|
117
|
+
held?.abort();
|
|
118
|
+
port.pause();
|
|
119
|
+
sync();
|
|
120
|
+
},
|
|
121
|
+
async toggle() {
|
|
122
|
+
if (held) player.pause();
|
|
123
|
+
else if (port.paused) await player.play();
|
|
124
|
+
else player.pause();
|
|
125
|
+
},
|
|
126
|
+
seekTo(seconds) {
|
|
127
|
+
const max = port.duration || Infinity;
|
|
128
|
+
soughtAfterEnd = soughtAfterEnd || !!port.ended;
|
|
129
|
+
port.currentTime = clamp(seconds, 0, max);
|
|
130
|
+
sync();
|
|
131
|
+
},
|
|
132
|
+
skipBy(delta) {
|
|
133
|
+
player.seekTo(port.currentTime + delta);
|
|
134
|
+
},
|
|
135
|
+
setRate(rate) {
|
|
136
|
+
port.playbackRate = clamp(rate, 0.25, 4);
|
|
137
|
+
set({ rate: port.playbackRate });
|
|
138
|
+
},
|
|
139
|
+
setVolume(volume) {
|
|
140
|
+
port.volume = clamp(volume, 0, 1);
|
|
141
|
+
set({ volume: port.volume });
|
|
142
|
+
},
|
|
143
|
+
enqueue(item, { next = false } = {}) {
|
|
144
|
+
const { queue, index } = get();
|
|
145
|
+
const at = next ? index + 1 : queue.length;
|
|
146
|
+
const q = [...queue.slice(0, at), item, ...queue.slice(at)];
|
|
147
|
+
set({ queue: q });
|
|
148
|
+
if (index < 0) select(0);
|
|
149
|
+
},
|
|
150
|
+
next() {
|
|
151
|
+
if (get().index + 1 < get().queue.length) select(get().index + 1);
|
|
152
|
+
},
|
|
153
|
+
previous() {
|
|
154
|
+
if (port.currentTime > skipBackS / 3 || get().index <= 0) player.seekTo(0);
|
|
155
|
+
else select(get().index - 1);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
void skipBackS;
|
|
159
|
+
void skipAheadS;
|
|
160
|
+
return player;
|
|
161
|
+
}
|
|
162
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
163
|
+
0 && (module.exports = {
|
|
164
|
+
createMediaPlayer,
|
|
165
|
+
urlSource
|
|
166
|
+
});
|
|
167
|
+
//# sourceMappingURL=transport.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/transport.ts","../src/playback.ts"],"sourcesContent":["/**\n * The transport: a headless media player with no DOM and no React, over any `MediaPort`.\n *\n * `MediaPort` is the part of an HTMLMediaElement the player uses (an element is one as it is; a\n * test fake, a wall clock or an embed adapter can be one too). `createMediaPlayer` is a zustand\n * store over a port, with a queue. Every action is also an acture command (`./commands`), so\n * keyboard, Media Session, a palette, MCP or gesture input are all just senders.\n *\n * Moved here from `@zodal/speech/media`, its seed (i2mint/zodal-speech#4).\n */\nimport { createStore, type StoreApi } from 'zustand/vanilla';\nimport { seekLanded, type SeekablePort } from './playback.js';\n\n/** The part of an HTMLMediaElement the player uses. */\nexport interface MediaPort extends SeekablePort {\n currentTime: number;\n readonly duration: number;\n readonly paused: boolean;\n playbackRate: number;\n volume: number;\n play(): Promise<void> | void;\n pause(): void;\n}\n\n/** A playable item. `src` is a URL the port can load (a presigned S3 URL, a stream route, a file URL). */\nexport interface MediaItem {\n id: string;\n src: string;\n title: string;\n kind?: 'audio' | 'video';\n /** Where to resume, in seconds. */\n resumeAt?: number;\n}\n\n/** Turns a source reference into an item. A source is any function with this shape. */\nexport type MediaSource = (ref: string) => MediaItem | Promise<MediaItem>;\n\n/** The simplest source: a URL (S3, a stream route or an HTML media element's file) becomes an item. */\nexport const urlSource: MediaSource = (ref) => ({\n id: ref,\n src: ref,\n title: decodeURIComponent(ref.split('/').pop()?.split('?')[0] ?? ref),\n});\n\nexport interface MediaState {\n queue: MediaItem[];\n index: number;\n playing: boolean;\n time: number;\n duration: number;\n rate: number;\n volume: number;\n}\n\nexport interface MediaPlayerOptions {\n /** Called when the current item changes, so the host can set the element's `src`. */\n load?: (item: MediaItem, port: MediaPort) => void;\n skipBackS?: number;\n skipAheadS?: number;\n}\n\nconst clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));\nconst DEFAULT_SKIP_BACK_S = 15;\nconst DEFAULT_SKIP_AHEAD_S = 30;\n\nexport interface MediaPlayer {\n store: StoreApi<MediaState>;\n port: MediaPort;\n play(): Promise<void>;\n pause(): void;\n toggle(): Promise<void>;\n seekTo(seconds: number): void;\n skipBy(deltaSeconds: number): void;\n setRate(rate: number): void;\n setVolume(volume: number): void;\n enqueue(item: MediaItem, opts?: { next?: boolean }): void;\n next(): void;\n previous(): void;\n /** Pull time and duration from the port into the store; call from `timeupdate` or a timer. */\n sync(): void;\n}\n\n/** Creates the headless player over any `MediaPort`. */\nexport function createMediaPlayer(port: MediaPort, options: MediaPlayerOptions = {}): MediaPlayer {\n const { load, skipBackS = DEFAULT_SKIP_BACK_S, skipAheadS = DEFAULT_SKIP_AHEAD_S } = options;\n const store = createStore<MediaState>(() => ({\n queue: [], index: -1, playing: false, time: 0, duration: 0, rate: 1, volume: 1,\n }));\n const set = store.setState;\n const get = store.getState;\n\n const sync = () => set({ time: port.currentTime, duration: port.duration || 0, playing: !port.paused });\n // A seek made after the end must land before play() on WebKit (see playback.ts).\n let soughtAfterEnd = false;\n let held: AbortController | null = null;\n const select = (index: number) => {\n const item = get().queue[index];\n if (!item) return;\n set({ index });\n load?.(item, port);\n if (item.resumeAt) port.currentTime = item.resumeAt;\n sync();\n };\n const player: MediaPlayer = {\n store, port, sync,\n async play() {\n if (get().index < 0 && get().queue.length) select(0);\n if (soughtAfterEnd) {\n held?.abort();\n const mine = (held = new AbortController());\n try {\n await seekLanded(port, { signal: mine.signal });\n } catch {\n return; // paused while the seek was landing\n } finally {\n if (held === mine) held = null;\n }\n }\n soughtAfterEnd = false;\n await port.play();\n sync();\n },\n pause() { held?.abort(); port.pause(); sync(); },\n async toggle() {\n if (held) player.pause(); // a play waiting for its seek: the tap means pause\n else if (port.paused) await player.play();\n else player.pause();\n },\n seekTo(seconds) {\n const max = port.duration || Infinity;\n soughtAfterEnd = soughtAfterEnd || !!port.ended;\n port.currentTime = clamp(seconds, 0, max);\n sync();\n },\n skipBy(delta) { player.seekTo(port.currentTime + delta); },\n setRate(rate) { port.playbackRate = clamp(rate, 0.25, 4); set({ rate: port.playbackRate }); },\n setVolume(volume) { port.volume = clamp(volume, 0, 1); set({ volume: port.volume }); },\n enqueue(item, { next = false } = {}) {\n const { queue, index } = get();\n const at = next ? index + 1 : queue.length;\n const q = [...queue.slice(0, at), item, ...queue.slice(at)];\n set({ queue: q });\n if (index < 0) select(0);\n },\n next() { if (get().index + 1 < get().queue.length) select(get().index + 1); },\n previous() {\n if (port.currentTime > skipBackS / 3 || get().index <= 0) player.seekTo(0);\n else select(get().index - 1);\n },\n };\n void skipBackS; void skipAheadS;\n return player;\n}\n","/**\n * Playing from a chosen point, safely on every engine, with no DOM beyond the port itself.\n *\n * The trap: in WebKit (Safari, and every browser on an iPhone or iPad) `el.currentTime = t;\n * el.play()` on an element that has *ended* starts from the end, which ends again at once, or\n * from 0, because the seek has not landed when `play()` runs. Chromium and Firefox apply the\n * seek first. It shows as \"after the audio finished, tapping a transcript line plays from the\n * start\" (annals, 2026-11-13). Measured in Playwright WebKit: 12 of 12 taps restarted at 0;\n * calling `play()` first and seeking again still failed 10 of 12; waiting for `seeked` and then\n * playing was right 16 of 16.\n *\n * So `seekThenPlay` reads whether the element had ended *before* seeking (after the seek WebKit\n * already reports `ended === false`), and if it had and the seek is still landing, it plays on\n * `seeked`. The element has played before, so playing outside the tap is allowed.\n */\n\n/** The part of a media element `seekThenPlay` uses. The optional members are an HTMLMediaElement's. */\nexport interface SeekablePort {\n currentTime: number;\n play(): Promise<void> | void;\n /** True once playback reached the end. A port without it is never waited on. */\n readonly ended?: boolean;\n /** True while a seek is landing. */\n readonly seeking?: boolean;\n addEventListener?(type: 'seeked', listener: () => void): void;\n removeEventListener?(type: 'seeked', listener: () => void): void;\n}\n\n/** Play anyway after this long, if no seek is under way by then (a seek still landing is still awaited). */\nexport const SEEK_LAND_TIMEOUT_MS = 1500;\n\nexport interface SeekThenPlayOptions {\n /** What starting playback means; defaults to `port.play()`. A player passes its own, to catch a refusal. */\n play?: () => Promise<void> | void;\n timeoutMs?: number;\n /** Cancels a play held for its seek (a pause meanwhile): the promise rejects with an AbortError. */\n signal?: AbortSignal;\n}\n\nfunction abortError(): Error {\n const e = new Error('The play was cancelled while its seek was landing.');\n e.name = 'AbortError';\n return e;\n}\n\n/** Resolves once `port`'s seek has landed (`seeked`), or at once when no seek is landing. */\nexport function seekLanded(\n port: SeekablePort,\n { timeoutMs = SEEK_LAND_TIMEOUT_MS, signal }: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<void> {\n if (signal?.aborted) return Promise.reject(abortError());\n if (!port.seeking || !port.addEventListener) return Promise.resolve();\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const settle = () => {\n clearTimeout(timer);\n port.removeEventListener?.('seeked', landed);\n signal?.removeEventListener('abort', aborted);\n };\n const landed = () => { settle(); resolve(); };\n const aborted = () => { settle(); reject(abortError()); };\n // Playing while the seek is still under way is the bug itself, so the timer only ends a wait\n // whose seek is over without a `seeked` (a source that went away).\n timer = setTimeout(() => { if (!port.seeking) landed(); }, timeoutMs);\n port.addEventListener!('seeked', landed);\n signal?.addEventListener('abort', aborted);\n });\n}\n\n/**\n * Seeks `port` to `time` and plays from there, also when it has ended (see the module note).\n * Plays synchronously, inside the tap, whenever it can; returns what playing returned.\n */\nexport function seekThenPlay(port: SeekablePort, time: number, options: SeekThenPlayOptions = {}): Promise<void> {\n const play = options.play ?? (() => port.play());\n const wasEnded = !!port.ended;\n port.currentTime = time;\n if (!wasEnded || !port.seeking) return Promise.resolve(play());\n return seekLanded(port, options).then(() => play());\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,qBAA2C;;;ACmBpC,IAAM,uBAAuB;AAUpC,SAAS,aAAoB;AAC3B,QAAM,IAAI,IAAI,MAAM,oDAAoD;AACxE,IAAE,OAAO;AACT,SAAO;AACT;AAGO,SAAS,WACd,MACA,E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AAS,GAAG,GAAG;AACxC,WAAK;AAAA,IACP;AAAA,IACA,OAAO,OAAO;AAAE,aAAO,OAAO,KAAK,cAAc,KAAK;AAAA,IAAG;AAAA,IACzD,QAAQ,MAAM;AAAE,WAAK,eAAe,MAAM,MAAM,MAAM,CAAC;AAAG,UAAI,EAAE,MAAM,KAAK,aAAa,CAAC;AAAA,IAAG;AAAA,IAC5F,UAAU,QAAQ;AAAE,WAAK,SAAS,MAAM,QAAQ,GAAG,CAAC;AAAG,UAAI,EAAE,QAAQ,KAAK,OAAO,CAAC;AAAA,IAAG;AAAA,IACrF,QAAQ,MAAM,EAAE,OAAO,MAAM,IAAI,CAAC,GAAG;AACnC,YAAM,EAAE,OAAO,MAAM,IAAI,IAAI;AAC7B,YAAM,KAAK,OAAO,QAAQ,IAAI,MAAM;AACpC,YAAM,IAAI,CAAC,GAAG,MAAM,MAAM,GAAG,EAAE,GAAG,MAAM,GAAG,MAAM,MAAM,EAAE,CAAC;AAC1D,UAAI,EAAE,OAAO,EAAE,CAAC;AAChB,UAAI,QAAQ,EAAG,QAAO,CAAC;AAAA,IACzB;AAAA,IACA,OAAO;AAAE,UAAI,IAAI,EAAE,QAAQ,IAAI,IAAI,EAAE,MAAM,OAAQ,QAAO,IAAI,EAAE,QAAQ,CAAC;AAAA,IAAG;AAAA,IAC5E,WAAW;AACT,UAAI,KAAK,cAAc,YAAY,KAAK,IAAI,EAAE,SAAS,EAAG,QAAO,OAAO,CAAC;AAAA,UACpE,QAAO,IAAI,EAAE,QAAQ,CAAC;AAAA,IAC7B;AAAA,EACF;AACA,OAAK;AAAW,OAAK;AACrB,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { StoreApi } from 'zustand/vanilla';
|
|
2
|
+
import { SeekablePort } from './playback.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The transport: a headless media player with no DOM and no React, over any `MediaPort`.
|
|
6
|
+
*
|
|
7
|
+
* `MediaPort` is the part of an HTMLMediaElement the player uses (an element is one as it is; a
|
|
8
|
+
* test fake, a wall clock or an embed adapter can be one too). `createMediaPlayer` is a zustand
|
|
9
|
+
* store over a port, with a queue. Every action is also an acture command (`./commands`), so
|
|
10
|
+
* keyboard, Media Session, a palette, MCP or gesture input are all just senders.
|
|
11
|
+
*
|
|
12
|
+
* Moved here from `@zodal/speech/media`, its seed (i2mint/zodal-speech#4).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** The part of an HTMLMediaElement the player uses. */
|
|
16
|
+
interface MediaPort extends SeekablePort {
|
|
17
|
+
currentTime: number;
|
|
18
|
+
readonly duration: number;
|
|
19
|
+
readonly paused: boolean;
|
|
20
|
+
playbackRate: number;
|
|
21
|
+
volume: number;
|
|
22
|
+
play(): Promise<void> | void;
|
|
23
|
+
pause(): void;
|
|
24
|
+
}
|
|
25
|
+
/** A playable item. `src` is a URL the port can load (a presigned S3 URL, a stream route, a file URL). */
|
|
26
|
+
interface MediaItem {
|
|
27
|
+
id: string;
|
|
28
|
+
src: string;
|
|
29
|
+
title: string;
|
|
30
|
+
kind?: 'audio' | 'video';
|
|
31
|
+
/** Where to resume, in seconds. */
|
|
32
|
+
resumeAt?: number;
|
|
33
|
+
}
|
|
34
|
+
/** Turns a source reference into an item. A source is any function with this shape. */
|
|
35
|
+
type MediaSource = (ref: string) => MediaItem | Promise<MediaItem>;
|
|
36
|
+
/** The simplest source: a URL (S3, a stream route or an HTML media element's file) becomes an item. */
|
|
37
|
+
declare const urlSource: MediaSource;
|
|
38
|
+
interface MediaState {
|
|
39
|
+
queue: MediaItem[];
|
|
40
|
+
index: number;
|
|
41
|
+
playing: boolean;
|
|
42
|
+
time: number;
|
|
43
|
+
duration: number;
|
|
44
|
+
rate: number;
|
|
45
|
+
volume: number;
|
|
46
|
+
}
|
|
47
|
+
interface MediaPlayerOptions {
|
|
48
|
+
/** Called when the current item changes, so the host can set the element's `src`. */
|
|
49
|
+
load?: (item: MediaItem, port: MediaPort) => void;
|
|
50
|
+
skipBackS?: number;
|
|
51
|
+
skipAheadS?: number;
|
|
52
|
+
}
|
|
53
|
+
interface MediaPlayer {
|
|
54
|
+
store: StoreApi<MediaState>;
|
|
55
|
+
port: MediaPort;
|
|
56
|
+
play(): Promise<void>;
|
|
57
|
+
pause(): void;
|
|
58
|
+
toggle(): Promise<void>;
|
|
59
|
+
seekTo(seconds: number): void;
|
|
60
|
+
skipBy(deltaSeconds: number): void;
|
|
61
|
+
setRate(rate: number): void;
|
|
62
|
+
setVolume(volume: number): void;
|
|
63
|
+
enqueue(item: MediaItem, opts?: {
|
|
64
|
+
next?: boolean;
|
|
65
|
+
}): void;
|
|
66
|
+
next(): void;
|
|
67
|
+
previous(): void;
|
|
68
|
+
/** Pull time and duration from the port into the store; call from `timeupdate` or a timer. */
|
|
69
|
+
sync(): void;
|
|
70
|
+
}
|
|
71
|
+
/** Creates the headless player over any `MediaPort`. */
|
|
72
|
+
declare function createMediaPlayer(port: MediaPort, options?: MediaPlayerOptions): MediaPlayer;
|
|
73
|
+
|
|
74
|
+
export { type MediaItem, type MediaPlayer, type MediaPlayerOptions, type MediaPort, type MediaSource, type MediaState, createMediaPlayer, urlSource };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { StoreApi } from 'zustand/vanilla';
|
|
2
|
+
import { SeekablePort } from './playback.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The transport: a headless media player with no DOM and no React, over any `MediaPort`.
|
|
6
|
+
*
|
|
7
|
+
* `MediaPort` is the part of an HTMLMediaElement the player uses (an element is one as it is; a
|
|
8
|
+
* test fake, a wall clock or an embed adapter can be one too). `createMediaPlayer` is a zustand
|
|
9
|
+
* store over a port, with a queue. Every action is also an acture command (`./commands`), so
|
|
10
|
+
* keyboard, Media Session, a palette, MCP or gesture input are all just senders.
|
|
11
|
+
*
|
|
12
|
+
* Moved here from `@zodal/speech/media`, its seed (i2mint/zodal-speech#4).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** The part of an HTMLMediaElement the player uses. */
|
|
16
|
+
interface MediaPort extends SeekablePort {
|
|
17
|
+
currentTime: number;
|
|
18
|
+
readonly duration: number;
|
|
19
|
+
readonly paused: boolean;
|
|
20
|
+
playbackRate: number;
|
|
21
|
+
volume: number;
|
|
22
|
+
play(): Promise<void> | void;
|
|
23
|
+
pause(): void;
|
|
24
|
+
}
|
|
25
|
+
/** A playable item. `src` is a URL the port can load (a presigned S3 URL, a stream route, a file URL). */
|
|
26
|
+
interface MediaItem {
|
|
27
|
+
id: string;
|
|
28
|
+
src: string;
|
|
29
|
+
title: string;
|
|
30
|
+
kind?: 'audio' | 'video';
|
|
31
|
+
/** Where to resume, in seconds. */
|
|
32
|
+
resumeAt?: number;
|
|
33
|
+
}
|
|
34
|
+
/** Turns a source reference into an item. A source is any function with this shape. */
|
|
35
|
+
type MediaSource = (ref: string) => MediaItem | Promise<MediaItem>;
|
|
36
|
+
/** The simplest source: a URL (S3, a stream route or an HTML media element's file) becomes an item. */
|
|
37
|
+
declare const urlSource: MediaSource;
|
|
38
|
+
interface MediaState {
|
|
39
|
+
queue: MediaItem[];
|
|
40
|
+
index: number;
|
|
41
|
+
playing: boolean;
|
|
42
|
+
time: number;
|
|
43
|
+
duration: number;
|
|
44
|
+
rate: number;
|
|
45
|
+
volume: number;
|
|
46
|
+
}
|
|
47
|
+
interface MediaPlayerOptions {
|
|
48
|
+
/** Called when the current item changes, so the host can set the element's `src`. */
|
|
49
|
+
load?: (item: MediaItem, port: MediaPort) => void;
|
|
50
|
+
skipBackS?: number;
|
|
51
|
+
skipAheadS?: number;
|
|
52
|
+
}
|
|
53
|
+
interface MediaPlayer {
|
|
54
|
+
store: StoreApi<MediaState>;
|
|
55
|
+
port: MediaPort;
|
|
56
|
+
play(): Promise<void>;
|
|
57
|
+
pause(): void;
|
|
58
|
+
toggle(): Promise<void>;
|
|
59
|
+
seekTo(seconds: number): void;
|
|
60
|
+
skipBy(deltaSeconds: number): void;
|
|
61
|
+
setRate(rate: number): void;
|
|
62
|
+
setVolume(volume: number): void;
|
|
63
|
+
enqueue(item: MediaItem, opts?: {
|
|
64
|
+
next?: boolean;
|
|
65
|
+
}): void;
|
|
66
|
+
next(): void;
|
|
67
|
+
previous(): void;
|
|
68
|
+
/** Pull time and duration from the port into the store; call from `timeupdate` or a timer. */
|
|
69
|
+
sync(): void;
|
|
70
|
+
}
|
|
71
|
+
/** Creates the headless player over any `MediaPort`. */
|
|
72
|
+
declare function createMediaPlayer(port: MediaPort, options?: MediaPlayerOptions): MediaPlayer;
|
|
73
|
+
|
|
74
|
+
export { type MediaItem, type MediaPlayer, type MediaPlayerOptions, type MediaPort, type MediaSource, type MediaState, createMediaPlayer, urlSource };
|