@trismegisto/media 0.0.0-stage → 4.0.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 (83) hide show
  1. package/LICENSE +56 -0
  2. package/MIGRATION.md +831 -0
  3. package/NOTICE +14 -0
  4. package/README.md +87 -2
  5. package/dist/announce.d.ts +60 -0
  6. package/dist/announce.js +124 -0
  7. package/dist/announce.js.map +1 -0
  8. package/dist/archive.d.ts +121 -0
  9. package/dist/archive.js +413 -0
  10. package/dist/archive.js.map +1 -0
  11. package/dist/captions.d.ts +180 -0
  12. package/dist/captions.js +468 -0
  13. package/dist/captions.js.map +1 -0
  14. package/dist/controls.d.ts +79 -0
  15. package/dist/controls.js +153 -0
  16. package/dist/controls.js.map +1 -0
  17. package/dist/csv.d.ts +43 -0
  18. package/dist/csv.js +197 -0
  19. package/dist/csv.js.map +1 -0
  20. package/dist/detect.d.ts +86 -0
  21. package/dist/detect.js +597 -0
  22. package/dist/detect.js.map +1 -0
  23. package/dist/file-source.d.ts +72 -0
  24. package/dist/file-source.js +19 -0
  25. package/dist/file-source.js.map +1 -0
  26. package/dist/file-view.d.ts +77 -0
  27. package/dist/file-view.js +124 -0
  28. package/dist/file-view.js.map +1 -0
  29. package/dist/format.d.ts +29 -0
  30. package/dist/format.js +122 -0
  31. package/dist/format.js.map +1 -0
  32. package/dist/gallery.d.ts +40 -0
  33. package/dist/gallery.js +53 -0
  34. package/dist/gallery.js.map +1 -0
  35. package/dist/html-preview.d.ts +24 -0
  36. package/dist/html-preview.js +30 -0
  37. package/dist/html-preview.js.map +1 -0
  38. package/dist/image-view.d.ts +71 -0
  39. package/dist/image-view.js +158 -0
  40. package/dist/image-view.js.map +1 -0
  41. package/dist/image.d.ts +101 -0
  42. package/dist/image.js +146 -0
  43. package/dist/image.js.map +1 -0
  44. package/dist/index.d.ts +25 -0
  45. package/dist/index.js +28 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/keyboard.d.ts +101 -0
  48. package/dist/keyboard.js +144 -0
  49. package/dist/keyboard.js.map +1 -0
  50. package/dist/markdown-html.d.ts +12 -0
  51. package/dist/markdown-html.js +32 -0
  52. package/dist/markdown-html.js.map +1 -0
  53. package/dist/media-i18n.d.ts +17 -0
  54. package/dist/media-i18n.js +27 -0
  55. package/dist/media-i18n.js.map +1 -0
  56. package/dist/media-messages.d.ts +249 -0
  57. package/dist/media-messages.en.d.ts +2 -0
  58. package/dist/media-messages.en.js +218 -0
  59. package/dist/media-messages.en.js.map +1 -0
  60. package/dist/media-messages.es.d.ts +2 -0
  61. package/dist/media-messages.es.js +218 -0
  62. package/dist/media-messages.es.js.map +1 -0
  63. package/dist/media-messages.js +218 -0
  64. package/dist/media-messages.js.map +1 -0
  65. package/dist/player-view.d.ts +104 -0
  66. package/dist/player-view.js +171 -0
  67. package/dist/player-view.js.map +1 -0
  68. package/dist/player.d.ts +324 -0
  69. package/dist/player.js +1146 -0
  70. package/dist/player.js.map +1 -0
  71. package/dist/range.d.ts +75 -0
  72. package/dist/range.js +185 -0
  73. package/dist/range.js.map +1 -0
  74. package/dist/registry.d.ts +55 -0
  75. package/dist/registry.js +81 -0
  76. package/dist/registry.js.map +1 -0
  77. package/dist/text.d.ts +103 -0
  78. package/dist/text.js +192 -0
  79. package/dist/text.js.map +1 -0
  80. package/dist/thumbnail.d.ts +113 -0
  81. package/dist/thumbnail.js +332 -0
  82. package/dist/thumbnail.js.map +1 -0
  83. package/package.json +55 -6
package/dist/player.js ADDED
@@ -0,0 +1,1146 @@
1
+ /**
2
+ * Controlador de reprodução sem framework. Envolve um `<video>`/`<audio>` que a casca criou, traduz os eventos de mídia
3
+ * (HTML Living Standard, HTMLMediaElement) num estado único observável e expõe comandos. A casca só desenha a partir do
4
+ * estado e chama comandos: nenhuma lógica de reprodução fica nela.
5
+ *
6
+ * Comandos que dependem de gesto da pessoa (tela cheia, imagem sobre imagem, tocar com som) devolvem promessa que
7
+ * nunca rejeita: a falha vira estado (`notice`, `error`).
8
+ */
9
+ import { chaptersFromCues, initialCaptionTrack } from './captions';
10
+ import { expiresAtTime } from './file-source';
11
+ /** Atrasos e passos do reprodutor, com a justificativa de cada um. */
12
+ export const MEDIA_TIMING = {
13
+ /** Abaixo de ~300 ms a pausa não é percebida como espera; mostrar o indicador antes disso pisca. */
14
+ bufferingDelay: 300,
15
+ /** 4 atualizações de tempo por segundo deixam a barra fluida sem redesenhar a cada quadro. */
16
+ timeUpdateInterval: 250,
17
+ /** Sem metadados em 10 s: bem acima de um carregamento normal, abaixo do ponto em que a pessoa desiste. */
18
+ slowMetadata: 10_000,
19
+ /** Pedir link novo 5 min antes de vencer: mais que o buffer que o navegador mantém à frente. */
20
+ refreshAhead: 5 * 60_000,
21
+ /** Passo de quadro sem `requestVideoFrameCallback`: 1/30 s, a taxa mais comum em vídeo gravado. */
22
+ frameFallback: 1 / 30,
23
+ };
24
+ /** Estado antes de o elemento existir (primeira pintura das cascas e servidor). */
25
+ export const EMPTY_PLAYBACK_STATE = {
26
+ phase: 'empty',
27
+ currentTime: 0,
28
+ duration: null,
29
+ bufferedEnd: 0,
30
+ seeking: false,
31
+ volume: 1,
32
+ muted: false,
33
+ rate: 1,
34
+ loop: false,
35
+ captions: { tracks: [], activeId: null, cues: [] },
36
+ chapters: [],
37
+ presentation: 'inline',
38
+ can: { fullscreen: false, pictureInPicture: false, volume: true, rate: true, seek: false, mediaSession: false },
39
+ error: null,
40
+ notice: null,
41
+ naturalSize: null,
42
+ seekableStart: 0,
43
+ seekableEnd: null,
44
+ };
45
+ /** Velocidades oferecidas: 0,5–2× em passos de 0,25 (7 itens cabem num menu sem rolagem em 390 px). */
46
+ export const PLAYBACK_RATES = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
47
+ /** Volume ao ativar o som partindo do zero: o meio da escala, que não assusta com som alto. */
48
+ export const UNMUTE_VOLUME = 0.5;
49
+ /** Próxima velocidade da lista, um degrau acima (`+1`) ou abaixo (`-1`); fica nas pontas. */
50
+ export function stepPlaybackRate(rate, direction, rates = PLAYBACK_RATES) {
51
+ if (direction > 0)
52
+ return rates.find((r) => r > rate + 1e-6) ?? rates[rates.length - 1];
53
+ for (let i = rates.length - 1; i >= 0; i--)
54
+ if (rates[i] < rate - 1e-6)
55
+ return rates[i];
56
+ return rates[0];
57
+ }
58
+ const streamingAdapters = [];
59
+ /** Registra um adaptador de transmissão; devolve a função que o tira. A CSP do app precisa de `media-src blob:`. */
60
+ export function registerStreamingAdapter(adapter) {
61
+ streamingAdapters.push(adapter);
62
+ return () => {
63
+ const index = streamingAdapters.indexOf(adapter);
64
+ if (index >= 0)
65
+ streamingAdapters.splice(index, 1);
66
+ };
67
+ }
68
+ // ----------------------------------------------------------------------------------------------- fases
69
+ /** Constantes de `readyState` (HTMLMediaElement). */
70
+ const HAVE_METADATA = 1;
71
+ const HAVE_CURRENT_DATA = 2;
72
+ const HAVE_FUTURE_DATA = 3;
73
+ /**
74
+ * Fase pela regra do reprodutor: erro → `error`; sem fonte → `empty`; sem metadados → `loading`; fim sem `loop` →
75
+ * `ended`; tocando com espera confirmada → `buffering`; tocando → `playing`; pausado depois de tocar → `paused`;
76
+ * pausado sem nunca ter tocado → `ready`.
77
+ */
78
+ export function derivePhase(input) {
79
+ if (input.error)
80
+ return 'error';
81
+ if (!input.hasSource)
82
+ return 'empty';
83
+ if (input.readyState < HAVE_METADATA)
84
+ return 'loading';
85
+ if (input.ended && !input.loop)
86
+ return 'ended';
87
+ if (!input.paused)
88
+ return input.stalled ? 'buffering' : 'playing';
89
+ return input.hasPlayed ? 'paused' : 'ready';
90
+ }
91
+ /** `MediaError.code` → motivo (1 aborted, 2 network, 3 decode, 4 unsupported). */
92
+ export function mediaErrorReason(code) {
93
+ switch (code) {
94
+ case 1:
95
+ return 'aborted';
96
+ case 2:
97
+ return 'network';
98
+ case 3:
99
+ return 'decode';
100
+ default:
101
+ return 'unsupported';
102
+ }
103
+ }
104
+ // ----------------------------------------------------------------------------------------------- exclusividade e Media Session
105
+ const exclusiveGroup = new Set();
106
+ let sessionOwner = null;
107
+ /** O volume pode ser mudado por script neste navegador (em alguns celulares o valor não muda). */
108
+ export function detectVolumeControl(doc) {
109
+ try {
110
+ const probe = doc.createElement('audio');
111
+ probe.volume = 0.5;
112
+ return Math.abs(probe.volume - 0.5) < 0.01;
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ }
118
+ function isVideo(element) {
119
+ return element.tagName === 'VIDEO';
120
+ }
121
+ function finiteOrNull(value) {
122
+ return Number.isFinite(value) && value >= 0 ? value : null;
123
+ }
124
+ /** Faixas de texto que o seletor de legendas lista (capítulos e metadados ficam de fora). */
125
+ function captionTracks(element, failed) {
126
+ const list = element.textTracks;
127
+ const tracks = [];
128
+ if (!list)
129
+ return tracks;
130
+ for (let i = 0; i < list.length; i++) {
131
+ const track = list[i];
132
+ if (track.kind !== 'captions' && track.kind !== 'subtitles' && track.kind !== 'descriptions')
133
+ continue;
134
+ const id = track.id || `${track.language}-${i}`;
135
+ if (failed.has(id))
136
+ continue;
137
+ tracks.push({ id, label: track.label, language: track.language, kind: track.kind, default: trackElementDefault(element, id) });
138
+ }
139
+ return tracks;
140
+ }
141
+ function trackElementDefault(element, id) {
142
+ const children = element.getElementsByTagName?.('track');
143
+ if (!children)
144
+ return false;
145
+ for (let i = 0; i < children.length; i++)
146
+ if (children[i].id === id)
147
+ return children[i].default;
148
+ return false;
149
+ }
150
+ function isCaptionKind(kind) {
151
+ return kind === 'captions' || kind === 'subtitles' || kind === 'descriptions';
152
+ }
153
+ /** Falas de uma `TextTrackCueList` (lista viva da plataforma) no formato do núcleo. */
154
+ function cueList(list) {
155
+ const cues = [];
156
+ if (!list)
157
+ return cues;
158
+ for (let i = 0; i < list.length; i++) {
159
+ const cue = list[i];
160
+ cues.push({ id: cue.id ?? '', start: cue.startTime, end: cue.endTime, text: cue.text ?? '' });
161
+ }
162
+ return cues;
163
+ }
164
+ function trackById(element, id) {
165
+ const list = element.textTracks;
166
+ if (!list)
167
+ return null;
168
+ for (let i = 0; i < list.length; i++) {
169
+ const track = list[i];
170
+ if ((track.id || `${track.language}-${i}`) === id)
171
+ return track;
172
+ }
173
+ return null;
174
+ }
175
+ /** O controlador de um elemento de mídia. */
176
+ export class MediaController {
177
+ element;
178
+ doc;
179
+ now;
180
+ exclusive;
181
+ useMediaSession;
182
+ container;
183
+ listeners = new Set();
184
+ eventListeners = new Set();
185
+ snapshot;
186
+ lastEmit = 0;
187
+ pendingEmit = null;
188
+ destroyed = false;
189
+ source = null;
190
+ expiresAt = null;
191
+ refreshRequested = false;
192
+ hasPlayed = false;
193
+ /** A pessoa quer a mídia tocando (sobrevive a um erro de rede no meio, para a retomada). */
194
+ playIntent = false;
195
+ stalled = false;
196
+ stallTimer = null;
197
+ slowTimer = null;
198
+ error = null;
199
+ notice = null;
200
+ presentation = 'inline';
201
+ failedTracks = new Set();
202
+ lastCaptionId = null;
203
+ preferredLanguage = null;
204
+ /** Faixa ligada (desenhada pela casca): a escolha fica aqui, não no `mode` da plataforma. */
205
+ activeCaption = null;
206
+ /** Idioma escolhido pela pessoa: `undefined` = ainda não escolheu; `null` = desligou. */
207
+ chosenLanguage = undefined;
208
+ /** Idioma salvo nas preferências do app. */
209
+ captionLanguage;
210
+ /** A escolha inicial de faixa desta fonte já foi feita. */
211
+ captionsInitialized = false;
212
+ /** Tela cheia nativa do celular: as legendas passam a ser as do sistema (`showing`). */
213
+ nativeCaptions = false;
214
+ /** Faixas cujas falas alguém lê (transcrição): ficam carregadas (`hidden`) mesmo desligadas. */
215
+ cueReaders = new Set();
216
+ cueListeners = new WeakSet();
217
+ adapter = null;
218
+ resume = null;
219
+ frameDuration = null;
220
+ frameHandle = null;
221
+ lastFrameTime = null;
222
+ orientationLocked = false;
223
+ volumeControl;
224
+ cleanup = [];
225
+ constructor(element, options = {}) {
226
+ this.element = element;
227
+ this.doc = element.ownerDocument;
228
+ this.now = options.now ?? (() => Date.now());
229
+ this.exclusive = options.exclusive ?? true;
230
+ this.useMediaSession = options.mediaSession ?? true;
231
+ this.container = options.container ?? null;
232
+ this.captionLanguage = options.captionLanguage ?? null;
233
+ this.volumeControl = detectVolumeControl(this.doc);
234
+ element.removeAttribute('controls');
235
+ element.preload = 'metadata';
236
+ this.setPreservesPitch();
237
+ this.snapshot = this.compute();
238
+ this.bind();
239
+ if (this.exclusive)
240
+ exclusiveGroup.add(this);
241
+ }
242
+ /** Estado atual (o mesmo objeto enquanto nada muda). */
243
+ get state() {
244
+ return this.snapshot;
245
+ }
246
+ /** Assina mudanças de estado; devolve a função que cancela. Chama na hora com o estado atual. */
247
+ subscribe(listener) {
248
+ this.listeners.add(listener);
249
+ listener(this.snapshot);
250
+ return () => this.listeners.delete(listener);
251
+ }
252
+ /** Assina os eventos para a casca (pedido de link novo). */
253
+ onEvent(listener) {
254
+ this.eventListeners.add(listener);
255
+ return () => this.eventListeners.delete(listener);
256
+ }
257
+ /** Troca o contêiner que entra em tela cheia. */
258
+ setContainer(container) {
259
+ this.container = container;
260
+ this.update(true);
261
+ }
262
+ /** Idioma preferido para o "ligar legendas" sem histórico (o da interface). */
263
+ setPreferredLanguage(language) {
264
+ this.preferredLanguage = language;
265
+ }
266
+ /** Idioma de legenda salvo nas preferências do app (usado na escolha inicial de cada fonte). */
267
+ setCaptionLanguage(language) {
268
+ this.captionLanguage = language;
269
+ }
270
+ /**
271
+ * Falas de uma faixa (transcrição). A faixa fica carregada (`hidden`) enquanto alguém lê; `release` solta. Vazio até
272
+ * o navegador terminar de ler o arquivo (o estado muda quando chegar).
273
+ */
274
+ readCues(id) {
275
+ if (!this.cueReaders.has(id)) {
276
+ this.cueReaders.add(id);
277
+ this.applyTrackModes();
278
+ }
279
+ return cueList(trackById(this.element, id)?.cues);
280
+ }
281
+ releaseCues(id) {
282
+ if (this.cueReaders.delete(id))
283
+ this.applyTrackModes();
284
+ }
285
+ // --------------------------------------------------------------------------------------------- fonte
286
+ /**
287
+ * Carrega uma fonte. Pausa, zera o estado e mantém volume, mudo, velocidade e a legenda escolhida (preferências da
288
+ * pessoa, não do arquivo). Um MIME que o navegador diz não tocar (`canPlayType` vazio) vira `unsupported` sem
289
+ * nenhum pedido de rede.
290
+ */
291
+ setSource(input) {
292
+ this.detachAdapter();
293
+ this.clearTimers();
294
+ const el = this.element;
295
+ if (!el.paused)
296
+ el.pause();
297
+ this.source = input;
298
+ this.expiresAt = expiresAtTime(input?.expiresAt ?? null);
299
+ this.refreshRequested = false;
300
+ this.hasPlayed = false;
301
+ this.playIntent = false;
302
+ this.stalled = false;
303
+ this.error = null;
304
+ this.notice = null;
305
+ this.failedTracks.clear();
306
+ this.captionsInitialized = false;
307
+ this.activeCaption = null;
308
+ this.frameDuration = null;
309
+ this.lastFrameTime = null;
310
+ if (!input?.src) {
311
+ el.removeAttribute('src');
312
+ el.load();
313
+ this.update(true);
314
+ return;
315
+ }
316
+ const streaming = input.streaming ?? null;
317
+ if (streaming) {
318
+ const adapter = streamingAdapters.find((a) => a.kind === streaming && a.canHandle(el, input.src)) ?? null;
319
+ const native = !!input.mime && el.canPlayType(input.mime) !== '';
320
+ if (!native && adapter) {
321
+ this.adapter = adapter;
322
+ this.startSlowTimer();
323
+ void Promise.resolve(adapter.attach(el, input.src)).catch(() => this.fail({ reason: 'network' }));
324
+ this.update(true);
325
+ return;
326
+ }
327
+ if (!native) {
328
+ el.removeAttribute('src');
329
+ this.fail({ reason: 'unsupported', detail: 'streaming' });
330
+ return;
331
+ }
332
+ }
333
+ else if (input.mime && el.canPlayType(input.mime) === '') {
334
+ el.removeAttribute('src');
335
+ this.fail({ reason: 'unsupported', detail: input.mime });
336
+ return;
337
+ }
338
+ el.preload = 'metadata';
339
+ el.src = input.src;
340
+ this.startSlowTimer();
341
+ this.update(true);
342
+ }
343
+ /**
344
+ * Recarrega (link novo depois de vencer, ou "Tentar de novo"). Com `keepPosition`, guarda o ponto, a intenção de
345
+ * tocar, a velocidade e a legenda, carrega a fonte e volta ao ponto depois dos metadados.
346
+ */
347
+ reload(options = {}) {
348
+ const current = this.source;
349
+ if (!current && !options.src)
350
+ return;
351
+ const wasPlaying = this.wantsToPlay();
352
+ const resume = options.keepPosition
353
+ ? { time: this.element.currentTime || this.snapshot.currentTime, play: wasPlaying, rate: this.element.playbackRate, captionId: this.snapshot.captions.activeId }
354
+ : null;
355
+ this.setSource({ ...(current ?? { src: '' }), src: options.src ?? current?.src ?? '', ...(options.expiresAt !== undefined ? { expiresAt: options.expiresAt } : {}) });
356
+ this.resume = resume;
357
+ }
358
+ /** O app informou que o link venceu (`status: 'expired'`): erro `expired` e pedido de link novo. */
359
+ markExpired() {
360
+ this.fail({ reason: 'expired' });
361
+ this.emitEvent({ type: 'refresh-request', reason: 'expired' });
362
+ }
363
+ // --------------------------------------------------------------------------------------------- comandos
364
+ /** Toca (em `ended`, do início). Bloqueio da plataforma vira aviso `blocked`, pausado. */
365
+ async play() {
366
+ const el = this.element;
367
+ if (!this.source?.src || this.error)
368
+ return;
369
+ if (el.ended)
370
+ el.currentTime = 0;
371
+ try {
372
+ await el.play();
373
+ if (this.notice === 'blocked')
374
+ this.notice = null;
375
+ }
376
+ catch (error) {
377
+ if (error?.name === 'NotAllowedError') {
378
+ this.notice = 'blocked';
379
+ this.update(true);
380
+ }
381
+ }
382
+ }
383
+ pause() {
384
+ this.element.pause();
385
+ }
386
+ togglePlay() {
387
+ if (this.element.paused || this.element.ended)
388
+ return this.play();
389
+ this.pause();
390
+ return Promise.resolve();
391
+ }
392
+ /** Vai para um ponto (limitado ao trecho navegável). */
393
+ seekTo(seconds) {
394
+ const { seekableStart, seekableEnd, duration } = this.snapshot;
395
+ const end = duration ?? seekableEnd;
396
+ if (end === null && seekableEnd === null)
397
+ return;
398
+ const target = Math.min(Math.max(seconds, seekableStart), end ?? seconds);
399
+ if (!Number.isFinite(target))
400
+ return;
401
+ this.element.currentTime = target;
402
+ this.update(true);
403
+ }
404
+ seekBy(delta) {
405
+ this.seekTo((this.element.currentTime || 0) + delta);
406
+ }
407
+ seekToFraction(fraction) {
408
+ const { duration } = this.snapshot;
409
+ if (duration === null)
410
+ return;
411
+ this.seekTo(Math.min(Math.max(fraction, 0), 1) * duration);
412
+ }
413
+ /** Volume 0..1; subir o volume tira o mudo. */
414
+ setVolume(volume) {
415
+ const value = Math.min(Math.max(Number.isFinite(volume) ? volume : 0, 0), 1);
416
+ this.element.volume = value;
417
+ if (value > 0 && this.element.muted)
418
+ this.element.muted = false;
419
+ this.update(true);
420
+ }
421
+ /** Mudo; ativar o som com volume zero volta a 50% (volume zero e sem mudo é um estado sem saída pelo botão). */
422
+ setMuted(muted) {
423
+ if (!muted && this.element.volume === 0)
424
+ this.element.volume = UNMUTE_VOLUME;
425
+ this.element.muted = muted;
426
+ this.update(true);
427
+ }
428
+ toggleMuted() {
429
+ this.setMuted(!(this.element.muted || this.element.volume === 0));
430
+ }
431
+ setRate(rate) {
432
+ if (!Number.isFinite(rate) || rate <= 0)
433
+ return;
434
+ this.setPreservesPitch();
435
+ this.element.playbackRate = rate;
436
+ this.element.defaultPlaybackRate = rate;
437
+ this.update(true);
438
+ }
439
+ stepRate(direction) {
440
+ this.setRate(stepPlaybackRate(this.element.playbackRate || 1, direction));
441
+ }
442
+ setLoop(loop) {
443
+ this.element.loop = loop;
444
+ this.update(true);
445
+ }
446
+ /**
447
+ * Liga uma faixa (ou desliga todas com `null`). A faixa ligada fica em `hidden`: o navegador carrega e ativa as falas,
448
+ * e a casca desenha numa camada própria (aparência da pessoa, acima da barra, dentro da tela cheia do contêiner). Só na
449
+ * tela cheia nativa do celular a faixa vai para `showing` (o sistema desenha).
450
+ */
451
+ selectCaptions(id, options = {}) {
452
+ if (!this.element.textTracks)
453
+ return;
454
+ this.activeCaption = id;
455
+ this.captionsInitialized = true;
456
+ if (id)
457
+ this.lastCaptionId = id;
458
+ if (options.user !== false) {
459
+ const language = id ? (this.snapshot.captions.tracks.find((t) => t.id === id)?.language ?? trackById(this.element, id)?.language ?? null) : null;
460
+ this.chosenLanguage = language;
461
+ this.emitEvent({ type: 'captions-selected', language });
462
+ }
463
+ this.applyTrackModes();
464
+ this.update(true);
465
+ }
466
+ /** Liga/desliga: volta à última faixa usada; sem histórico, a do idioma preferido; senão, a primeira. */
467
+ toggleCaptions() {
468
+ const { tracks, activeId } = this.snapshot.captions;
469
+ if (activeId)
470
+ return this.selectCaptions(null);
471
+ if (!tracks.length)
472
+ return;
473
+ const last = tracks.find((t) => t.id === this.lastCaptionId);
474
+ const lang = this.preferredLanguage?.toLowerCase();
475
+ const byLanguage = lang
476
+ ? tracks.find((t) => t.language.toLowerCase() === lang) ?? tracks.find((t) => t.language.toLowerCase().split('-')[0] === lang.split('-')[0])
477
+ : undefined;
478
+ this.selectCaptions((last ?? byLanguage ?? tracks[0]).id);
479
+ }
480
+ /** Avança ou volta um quadro com o vídeo pausado. */
481
+ stepFrame(direction) {
482
+ if (!this.element.paused)
483
+ return;
484
+ const step = this.frameDuration ?? MEDIA_TIMING.frameFallback;
485
+ this.seekBy(step * direction);
486
+ }
487
+ async enterFullscreen() {
488
+ const el = this.element;
489
+ if (!isVideo(el))
490
+ return;
491
+ const target = this.container ?? el;
492
+ try {
493
+ if (this.presentation === 'picture-in-picture')
494
+ await this.exitPictureInPicture();
495
+ if (typeof target.requestFullscreen === 'function' && this.doc.fullscreenEnabled !== false) {
496
+ await target.requestFullscreen();
497
+ }
498
+ else {
499
+ el.webkitEnterFullscreen?.();
500
+ // Tela cheia nativa do celular: os controles e as legendas do sistema assumem.
501
+ this.showNativeCaptions(true);
502
+ }
503
+ await this.lockOrientation();
504
+ }
505
+ catch {
506
+ // Recusado pela plataforma (sem gesto, sem permissão no iframe): o estado segue o evento.
507
+ }
508
+ this.update(true);
509
+ }
510
+ async exitFullscreen() {
511
+ try {
512
+ if (this.doc.fullscreenElement)
513
+ await this.doc.exitFullscreen();
514
+ else
515
+ this.element.webkitExitFullscreen?.();
516
+ }
517
+ catch {
518
+ // Já saiu.
519
+ }
520
+ this.unlockOrientation();
521
+ this.update(true);
522
+ }
523
+ toggleFullscreen() {
524
+ return this.snapshot.presentation === 'fullscreen' ? this.exitFullscreen() : this.enterFullscreen();
525
+ }
526
+ async enterPictureInPicture() {
527
+ const el = this.element;
528
+ if (!this.snapshot.can.pictureInPicture || typeof el.requestPictureInPicture !== 'function')
529
+ return;
530
+ try {
531
+ if (this.doc.fullscreenElement)
532
+ await this.doc.exitFullscreen();
533
+ await el.requestPictureInPicture();
534
+ }
535
+ catch {
536
+ // Recusado: o estado segue o evento.
537
+ }
538
+ this.update(true);
539
+ }
540
+ async exitPictureInPicture() {
541
+ const doc = this.doc;
542
+ try {
543
+ if (doc.pictureInPictureElement === this.element)
544
+ await doc.exitPictureInPicture?.();
545
+ }
546
+ catch {
547
+ // Já fechada pelo sistema.
548
+ }
549
+ this.update(true);
550
+ }
551
+ togglePictureInPicture() {
552
+ return this.snapshot.presentation === 'picture-in-picture' ? this.exitPictureInPicture() : this.enterPictureInPicture();
553
+ }
554
+ /** Solta tudo: eventos, temporizadores, Media Session e o grupo exclusivo. O elemento fica sem fonte. */
555
+ destroy() {
556
+ if (this.destroyed)
557
+ return;
558
+ this.destroyed = true;
559
+ this.clearTimers();
560
+ this.detachAdapter();
561
+ this.stopFrameWatch();
562
+ for (const off of this.cleanup)
563
+ off();
564
+ this.cleanup.length = 0;
565
+ exclusiveGroup.delete(this);
566
+ if (sessionOwner === this)
567
+ this.clearMediaSession();
568
+ this.listeners.clear();
569
+ this.eventListeners.clear();
570
+ if (this.pendingEmit)
571
+ clearTimeout(this.pendingEmit);
572
+ this.element.pause();
573
+ }
574
+ // --------------------------------------------------------------------------------------------- interno
575
+ wantsToPlay() {
576
+ return this.playIntent || !this.element.paused;
577
+ }
578
+ setPreservesPitch() {
579
+ const el = this.element;
580
+ try {
581
+ el.preservesPitch = true;
582
+ }
583
+ catch {
584
+ // Sem a propriedade.
585
+ }
586
+ }
587
+ fail(error) {
588
+ this.clearTimers();
589
+ this.error = error;
590
+ this.update(true);
591
+ }
592
+ startSlowTimer() {
593
+ this.slowTimer = setTimeout(() => {
594
+ this.slowTimer = null;
595
+ if (this.element.readyState < HAVE_METADATA && !this.error) {
596
+ this.notice = 'slow-range';
597
+ this.update(true);
598
+ }
599
+ }, MEDIA_TIMING.slowMetadata);
600
+ }
601
+ clearTimers() {
602
+ if (this.stallTimer)
603
+ clearTimeout(this.stallTimer);
604
+ if (this.slowTimer)
605
+ clearTimeout(this.slowTimer);
606
+ this.stallTimer = null;
607
+ this.slowTimer = null;
608
+ }
609
+ detachAdapter() {
610
+ if (this.adapter) {
611
+ try {
612
+ this.adapter.detach(this.element);
613
+ }
614
+ catch {
615
+ // O adaptador do app falhou ao soltar; nada a fazer aqui.
616
+ }
617
+ this.adapter = null;
618
+ }
619
+ }
620
+ emitEvent(event) {
621
+ for (const listener of [...this.eventListeners])
622
+ listener(event);
623
+ }
624
+ /** Espera confirmada: dados insuficientes por mais de 300 ms com intenção de tocar. */
625
+ scheduleStallCheck() {
626
+ if (this.stallTimer)
627
+ return;
628
+ this.stallTimer = setTimeout(() => {
629
+ this.stallTimer = null;
630
+ if (!this.element.paused && this.element.readyState < HAVE_FUTURE_DATA) {
631
+ this.stalled = true;
632
+ this.update(true);
633
+ }
634
+ }, MEDIA_TIMING.bufferingDelay);
635
+ }
636
+ clearStall() {
637
+ if (this.stallTimer)
638
+ clearTimeout(this.stallTimer);
639
+ this.stallTimer = null;
640
+ this.stalled = false;
641
+ }
642
+ capabilities(duration, seekableEnd) {
643
+ const el = this.element;
644
+ const doc = this.doc;
645
+ const video = isVideo(el);
646
+ const target = this.container ?? el;
647
+ const fullscreen = video && ((doc.fullscreenEnabled === true && typeof target.requestFullscreen === 'function') || typeof el.webkitEnterFullscreen === 'function');
648
+ const pictureInPicture = video && doc.pictureInPictureEnabled === true && !el.disablePictureInPicture && typeof el.requestPictureInPicture === 'function';
649
+ const nav = this.doc.defaultView?.navigator;
650
+ return {
651
+ fullscreen,
652
+ pictureInPicture,
653
+ volume: this.volumeControl,
654
+ rate: 'playbackRate' in el,
655
+ seek: duration !== null || (seekableEnd !== null && seekableEnd > 0),
656
+ mediaSession: !!nav?.mediaSession,
657
+ };
658
+ }
659
+ compute() {
660
+ const el = this.element;
661
+ const duration = finiteOrNull(el.duration);
662
+ const currentTime = Number.isFinite(el.currentTime) ? el.currentTime : 0;
663
+ let bufferedEnd = 0;
664
+ const buffered = el.buffered;
665
+ if (buffered) {
666
+ for (let i = 0; i < buffered.length; i++) {
667
+ if (buffered.start(i) <= currentTime + 0.01 && buffered.end(i) >= currentTime)
668
+ bufferedEnd = buffered.end(i);
669
+ }
670
+ }
671
+ let seekableStart = 0;
672
+ let seekableEnd = null;
673
+ const seekable = el.seekable;
674
+ if (seekable && seekable.length) {
675
+ seekableStart = seekable.start(0);
676
+ seekableEnd = finiteOrNull(seekable.end(seekable.length - 1));
677
+ }
678
+ const tracks = captionTracks(el, this.failedTracks);
679
+ const active = tracks.find((t) => t.id === this.activeCaption);
680
+ const cues = [];
681
+ if (active) {
682
+ const list = trackById(el, active.id)?.activeCues;
683
+ if (list) {
684
+ for (let i = 0; i < list.length; i++) {
685
+ const cue = list[i];
686
+ if (cue.text)
687
+ cues.push({ id: cue.id || `${cue.startTime}-${i}`, text: cue.text });
688
+ }
689
+ }
690
+ }
691
+ let chapters = [];
692
+ const list = el.textTracks;
693
+ if (list) {
694
+ for (let i = 0; i < list.length; i++) {
695
+ if (list[i].kind === 'chapters' && list[i].cues?.length) {
696
+ chapters = chaptersFromCues(cueList(list[i].cues));
697
+ break;
698
+ }
699
+ }
700
+ }
701
+ const video = isVideo(el) ? el : null;
702
+ const naturalSize = video && video.videoWidth > 0 ? { width: video.videoWidth, height: video.videoHeight } : null;
703
+ const phase = derivePhase({
704
+ hasSource: !!this.source?.src,
705
+ error: !!this.error && this.error.reason !== 'aborted',
706
+ readyState: el.readyState,
707
+ paused: el.paused,
708
+ ended: el.ended,
709
+ loop: el.loop,
710
+ hasPlayed: this.hasPlayed,
711
+ stalled: this.stalled,
712
+ });
713
+ return {
714
+ phase,
715
+ currentTime,
716
+ duration,
717
+ bufferedEnd,
718
+ seeking: el.seeking,
719
+ volume: el.volume,
720
+ muted: el.muted,
721
+ rate: el.playbackRate || 1,
722
+ loop: el.loop,
723
+ captions: { tracks, activeId: active?.id ?? null, cues },
724
+ chapters,
725
+ presentation: this.presentation,
726
+ can: this.capabilities(duration, seekableEnd),
727
+ error: this.error && this.error.reason !== 'aborted' ? this.error : null,
728
+ notice: this.notice,
729
+ naturalSize,
730
+ seekableStart,
731
+ seekableEnd,
732
+ };
733
+ }
734
+ sameState(a, b) {
735
+ return (a.phase === b.phase &&
736
+ a.currentTime === b.currentTime &&
737
+ a.duration === b.duration &&
738
+ a.bufferedEnd === b.bufferedEnd &&
739
+ a.seeking === b.seeking &&
740
+ a.volume === b.volume &&
741
+ a.muted === b.muted &&
742
+ a.rate === b.rate &&
743
+ a.loop === b.loop &&
744
+ a.captions.activeId === b.captions.activeId &&
745
+ a.captions.tracks.length === b.captions.tracks.length &&
746
+ a.captions.tracks.every((t, i) => t.id === b.captions.tracks[i]?.id && t.label === b.captions.tracks[i]?.label) &&
747
+ a.captions.cues.length === b.captions.cues.length &&
748
+ a.captions.cues.every((c, i) => c.id === b.captions.cues[i]?.id && c.text === b.captions.cues[i]?.text) &&
749
+ a.chapters.length === b.chapters.length &&
750
+ a.chapters.every((c, i) => c.start === b.chapters[i]?.start && c.title === b.chapters[i]?.title) &&
751
+ a.presentation === b.presentation &&
752
+ a.error?.reason === b.error?.reason &&
753
+ a.error?.detail === b.error?.detail &&
754
+ a.notice === b.notice &&
755
+ a.naturalSize?.width === b.naturalSize?.width &&
756
+ a.naturalSize?.height === b.naturalSize?.height &&
757
+ a.seekableStart === b.seekableStart &&
758
+ a.seekableEnd === b.seekableEnd &&
759
+ a.can.fullscreen === b.can.fullscreen &&
760
+ a.can.pictureInPicture === b.can.pictureInPicture &&
761
+ a.can.volume === b.can.volume &&
762
+ a.can.seek === b.can.seek &&
763
+ a.can.rate === b.can.rate &&
764
+ a.can.mediaSession === b.can.mediaSession);
765
+ }
766
+ /**
767
+ * Recalcula e avisa. `immediate` publica na hora (pausa, salto, comando); só o tempo correndo (timeupdate) respeita o
768
+ * intervalo de 250 ms.
769
+ */
770
+ update(immediate) {
771
+ if (this.destroyed)
772
+ return;
773
+ if (!this.captionsInitialized && this.source?.src)
774
+ this.initCaptions();
775
+ const next = this.compute();
776
+ if (this.sameState(next, this.snapshot))
777
+ return;
778
+ const onlyTime = !immediate && next.phase === this.snapshot.phase && this.sameState({ ...next, currentTime: this.snapshot.currentTime, bufferedEnd: this.snapshot.bufferedEnd }, this.snapshot);
779
+ if (onlyTime) {
780
+ const wait = MEDIA_TIMING.timeUpdateInterval - (this.now() - this.lastEmit);
781
+ if (wait > 0) {
782
+ if (!this.pendingEmit) {
783
+ this.pendingEmit = setTimeout(() => {
784
+ this.pendingEmit = null;
785
+ this.update(true);
786
+ }, wait);
787
+ }
788
+ return;
789
+ }
790
+ }
791
+ if (this.pendingEmit) {
792
+ clearTimeout(this.pendingEmit);
793
+ this.pendingEmit = null;
794
+ }
795
+ this.snapshot = next;
796
+ this.lastEmit = this.now();
797
+ for (const listener of [...this.listeners])
798
+ listener(next);
799
+ }
800
+ checkExpiry() {
801
+ if (this.expiresAt === null || this.refreshRequested || this.element.paused)
802
+ return;
803
+ if (this.expiresAt - this.now() < MEDIA_TIMING.refreshAhead) {
804
+ this.refreshRequested = true;
805
+ this.emitEvent({ type: 'refresh-request', reason: 'expiring' });
806
+ }
807
+ }
808
+ applyResume() {
809
+ const resume = this.resume;
810
+ if (!resume)
811
+ return;
812
+ this.resume = null;
813
+ const el = this.element;
814
+ if (Number.isFinite(resume.time) && resume.time > 0)
815
+ el.currentTime = resume.time;
816
+ if (resume.rate && resume.rate !== 1) {
817
+ el.playbackRate = resume.rate;
818
+ el.defaultPlaybackRate = resume.rate;
819
+ }
820
+ if (resume.captionId)
821
+ this.selectCaptions(resume.captionId, { user: false });
822
+ if (resume.play)
823
+ void this.play();
824
+ }
825
+ showNativeCaptions(on) {
826
+ this.nativeCaptions = on;
827
+ this.applyTrackModes();
828
+ }
829
+ /**
830
+ * Modo de cada faixa pela escolha do controlador: a ligada em `hidden` (ou `showing` na tela cheia nativa), as lidas
831
+ * pela transcrição em `hidden`, capítulos em `hidden` (as marcas da barra precisam das falas), o resto `disabled`.
832
+ */
833
+ applyTrackModes() {
834
+ const list = this.element.textTracks;
835
+ if (!list)
836
+ return;
837
+ for (let i = 0; i < list.length; i++) {
838
+ const track = list[i];
839
+ const id = track.id || `${track.language}-${i}`;
840
+ let mode = 'disabled';
841
+ if (track.kind === 'chapters')
842
+ mode = 'hidden';
843
+ else if (isCaptionKind(track.kind)) {
844
+ if (id === this.activeCaption)
845
+ mode = this.nativeCaptions ? 'showing' : 'hidden';
846
+ else if (this.cueReaders.has(id))
847
+ mode = 'hidden';
848
+ }
849
+ else
850
+ continue;
851
+ if (track.mode !== mode)
852
+ track.mode = mode;
853
+ if (!this.cueListeners.has(track) && typeof track.addEventListener === 'function') {
854
+ this.cueListeners.add(track);
855
+ const onCue = () => this.update(true);
856
+ track.addEventListener('cuechange', onCue);
857
+ this.cleanup.push(() => track.removeEventListener('cuechange', onCue));
858
+ }
859
+ }
860
+ }
861
+ /**
862
+ * Escolha inicial das faixas de uma fonte, quando elas aparecem: a escolha da pessoa nesta sessão (idioma, ou
863
+ * desligado); senão o idioma das preferências do app; senão a `default`; senão nenhuma.
864
+ */
865
+ initCaptions() {
866
+ if (this.captionsInitialized)
867
+ return;
868
+ const tracks = captionTracks(this.element, this.failedTracks);
869
+ if (!tracks.length)
870
+ return;
871
+ this.captionsInitialized = true;
872
+ let chosen;
873
+ if (this.chosenLanguage === null)
874
+ chosen = null;
875
+ else if (this.chosenLanguage !== undefined)
876
+ chosen = initialCaptionTrack(tracks, this.chosenLanguage) ?? initialCaptionTrack(tracks, this.captionLanguage);
877
+ else
878
+ chosen = initialCaptionTrack(tracks, this.captionLanguage);
879
+ this.activeCaption = chosen?.id ?? null;
880
+ this.applyTrackModes();
881
+ }
882
+ async lockOrientation() {
883
+ const el = this.element;
884
+ if (!isVideo(el) || el.videoWidth <= el.videoHeight)
885
+ return;
886
+ const orientation = this.doc.defaultView?.screen?.orientation;
887
+ try {
888
+ await orientation?.lock?.('landscape');
889
+ this.orientationLocked = true;
890
+ }
891
+ catch {
892
+ // Sem suporte (ou fora da tela cheia): falha silenciosa.
893
+ }
894
+ }
895
+ unlockOrientation() {
896
+ if (!this.orientationLocked)
897
+ return;
898
+ this.orientationLocked = false;
899
+ try {
900
+ this.doc.defaultView?.screen?.orientation?.unlock?.();
901
+ }
902
+ catch {
903
+ // Sem suporte.
904
+ }
905
+ }
906
+ syncPresentation() {
907
+ const doc = this.doc;
908
+ const el = this.element;
909
+ const target = this.container ?? el;
910
+ const fullscreenElement = doc.fullscreenElement;
911
+ const before = this.presentation;
912
+ if (doc.pictureInPictureElement === el)
913
+ this.presentation = 'picture-in-picture';
914
+ else if ((fullscreenElement && (fullscreenElement === target || fullscreenElement === el)) || el.webkitDisplayingFullscreen)
915
+ this.presentation = 'fullscreen';
916
+ else
917
+ this.presentation = 'inline';
918
+ if (before === 'fullscreen' && this.presentation !== 'fullscreen')
919
+ this.unlockOrientation();
920
+ }
921
+ publishMediaSession() {
922
+ if (!this.useMediaSession)
923
+ return;
924
+ const nav = this.doc.defaultView?.navigator;
925
+ const session = nav?.mediaSession;
926
+ if (!session)
927
+ return;
928
+ sessionOwner = this;
929
+ const Metadata = this.doc.defaultView?.MediaMetadata;
930
+ try {
931
+ if (Metadata) {
932
+ const artwork = this.source?.artwork ? [{ src: this.source.artwork }] : [];
933
+ session.metadata = new Metadata({ title: this.source?.title ?? '', artist: '', artwork });
934
+ }
935
+ }
936
+ catch {
937
+ // Metadados recusados: os controles continuam.
938
+ }
939
+ const handlers = [
940
+ ['play', () => void this.play()],
941
+ ['pause', () => this.pause()],
942
+ ['seekbackward', (details) => this.seekBy(-(details.seekOffset ?? 10))],
943
+ ['seekforward', (details) => this.seekBy(details.seekOffset ?? 10)],
944
+ ['seekto', (details) => details.seekTime !== undefined && this.seekTo(details.seekTime)],
945
+ ];
946
+ for (const [action, handler] of handlers) {
947
+ try {
948
+ session.setActionHandler(action, handler);
949
+ }
950
+ catch {
951
+ // Ação sem suporte neste navegador.
952
+ }
953
+ }
954
+ }
955
+ clearMediaSession() {
956
+ const nav = this.doc.defaultView?.navigator;
957
+ const session = nav?.mediaSession;
958
+ if (sessionOwner === this)
959
+ sessionOwner = null;
960
+ if (!session)
961
+ return;
962
+ try {
963
+ session.metadata = null;
964
+ }
965
+ catch {
966
+ // Sem metadados.
967
+ }
968
+ for (const action of ['play', 'pause', 'seekbackward', 'seekforward', 'seekto']) {
969
+ try {
970
+ session.setActionHandler(action, null);
971
+ }
972
+ catch {
973
+ // Ação sem suporte.
974
+ }
975
+ }
976
+ }
977
+ startFrameWatch() {
978
+ const el = this.element;
979
+ if (!isVideo(el) || typeof el.requestVideoFrameCallback !== 'function' || this.frameHandle !== null)
980
+ return;
981
+ const watch = (_now, metadata) => {
982
+ if (this.lastFrameTime !== null) {
983
+ const delta = metadata.mediaTime - this.lastFrameTime;
984
+ // A menor diferença positiva entre quadros apresentados é a duração de um quadro.
985
+ if (delta > 0.001 && delta < 0.5)
986
+ this.frameDuration = this.frameDuration === null ? delta : Math.min(this.frameDuration, delta);
987
+ }
988
+ this.lastFrameTime = metadata.mediaTime;
989
+ this.frameHandle = this.element.paused ? null : (el.requestVideoFrameCallback?.(watch) ?? null);
990
+ };
991
+ this.frameHandle = el.requestVideoFrameCallback(watch);
992
+ }
993
+ stopFrameWatch() {
994
+ const el = this.element;
995
+ if (this.frameHandle !== null)
996
+ el.cancelVideoFrameCallback?.(this.frameHandle);
997
+ this.frameHandle = null;
998
+ }
999
+ bind() {
1000
+ const el = this.element;
1001
+ const on = (target, type, handler, capture = false) => {
1002
+ target.addEventListener(type, handler, capture);
1003
+ this.cleanup.push(() => target.removeEventListener(type, handler, capture));
1004
+ };
1005
+ on(el, 'loadstart', () => this.update(true));
1006
+ on(el, 'loadedmetadata', () => {
1007
+ if (this.slowTimer)
1008
+ clearTimeout(this.slowTimer);
1009
+ this.slowTimer = null;
1010
+ if (this.notice === 'slow-range')
1011
+ this.notice = null;
1012
+ this.applyResume();
1013
+ this.update(true);
1014
+ });
1015
+ on(el, 'loadeddata', () => {
1016
+ if (isVideo(el) && el.videoWidth === 0 && el.readyState >= HAVE_CURRENT_DATA)
1017
+ this.notice = 'audio-only';
1018
+ this.update(true);
1019
+ });
1020
+ on(el, 'durationchange', () => this.update(true));
1021
+ on(el, 'resize', () => this.update(true));
1022
+ on(el, 'canplay', () => {
1023
+ this.clearStall();
1024
+ this.update(true);
1025
+ });
1026
+ on(el, 'canplaythrough', () => this.update(true));
1027
+ on(el, 'play', () => {
1028
+ this.hasPlayed = true;
1029
+ this.playIntent = true;
1030
+ if (this.exclusive)
1031
+ for (const other of exclusiveGroup)
1032
+ if (other !== this && !other.element.paused)
1033
+ other.pause();
1034
+ if (el.readyState < HAVE_FUTURE_DATA)
1035
+ this.scheduleStallCheck();
1036
+ this.update(true);
1037
+ });
1038
+ on(el, 'playing', () => {
1039
+ this.hasPlayed = true;
1040
+ this.clearStall();
1041
+ if (this.notice === 'blocked')
1042
+ this.notice = null;
1043
+ this.publishMediaSession();
1044
+ this.startFrameWatch();
1045
+ this.update(true);
1046
+ });
1047
+ on(el, 'waiting', () => {
1048
+ this.scheduleStallCheck();
1049
+ this.update(true);
1050
+ });
1051
+ on(el, 'pause', () => {
1052
+ // Pausa causada por erro não muda a intenção: a retomada volta a tocar.
1053
+ if (!el.error && !this.error)
1054
+ this.playIntent = false;
1055
+ this.clearStall();
1056
+ this.update(true);
1057
+ });
1058
+ on(el, 'seeking', () => this.update(true));
1059
+ on(el, 'seeked', () => this.update(true));
1060
+ on(el, 'timeupdate', () => {
1061
+ this.checkExpiry();
1062
+ this.update(false);
1063
+ });
1064
+ on(el, 'progress', () => this.update(false));
1065
+ on(el, 'volumechange', () => this.update(true));
1066
+ on(el, 'ratechange', () => this.update(true));
1067
+ on(el, 'ended', () => {
1068
+ if (!el.loop)
1069
+ this.playIntent = false;
1070
+ this.clearStall();
1071
+ if (!el.loop && sessionOwner === this)
1072
+ this.clearMediaSession();
1073
+ this.update(true);
1074
+ });
1075
+ on(el, 'emptied', () => this.update(true));
1076
+ on(el, 'error', (event) => {
1077
+ const target = event.target;
1078
+ if (target && target !== el && target.tagName === 'TRACK') {
1079
+ // Faixa que não carregou: sai do menu (aviso de desenvolvimento); não é erro do reprodutor.
1080
+ const id = target.id || target.srclang;
1081
+ this.failedTracks.add(id);
1082
+ console.warn(`[hermes-media] a faixa de texto "${id}" não carregou (CORS ou endereço inválido)`);
1083
+ this.update(true);
1084
+ return;
1085
+ }
1086
+ if (target && target !== el)
1087
+ return;
1088
+ const code = el.error?.code ?? 0;
1089
+ if (!code)
1090
+ return;
1091
+ let reason = mediaErrorReason(code);
1092
+ // Erro de decodificação antes do primeiro quadro: o formato não é suportado, não o arquivo corrompido.
1093
+ if (reason === 'decode' && !this.hasPlayed && el.readyState < HAVE_CURRENT_DATA)
1094
+ reason = 'unsupported';
1095
+ if (reason === 'aborted')
1096
+ return;
1097
+ if (reason === 'network' && this.expiresAt !== null && this.now() >= this.expiresAt) {
1098
+ this.fail({ reason: 'expired' });
1099
+ this.emitEvent({ type: 'refresh-request', reason: 'expired' });
1100
+ return;
1101
+ }
1102
+ this.fail({ reason, ...(reason === 'unsupported' && this.source?.mime ? { detail: this.source.mime } : {}) });
1103
+ }, true);
1104
+ on(el, 'enterpictureinpicture', () => {
1105
+ this.syncPresentation();
1106
+ this.update(true);
1107
+ });
1108
+ on(el, 'leavepictureinpicture', () => {
1109
+ this.syncPresentation();
1110
+ this.update(true);
1111
+ });
1112
+ on(el, 'webkitbeginfullscreen', () => {
1113
+ this.syncPresentation();
1114
+ this.update(true);
1115
+ });
1116
+ on(el, 'webkitendfullscreen', () => {
1117
+ this.syncPresentation();
1118
+ this.showNativeCaptions(false);
1119
+ this.update(true);
1120
+ });
1121
+ // Arquivo de faixa carregado (o evento é do `<track>` e não sobe: escuta na captura): falas e capítulos chegaram.
1122
+ on(el, 'load', (event) => {
1123
+ if (event.target?.tagName === 'TRACK')
1124
+ this.update(true);
1125
+ }, true);
1126
+ on(this.doc, 'fullscreenchange', () => {
1127
+ this.syncPresentation();
1128
+ this.update(true);
1129
+ });
1130
+ const tracks = el.textTracks;
1131
+ if (tracks && typeof tracks.addEventListener === 'function') {
1132
+ on(tracks, 'addtrack', () => {
1133
+ this.applyTrackModes();
1134
+ this.update(true);
1135
+ });
1136
+ on(tracks, 'removetrack', () => this.update(true));
1137
+ on(tracks, 'change', () => {
1138
+ // O navegador (ou o atributo `default`) mexeu num modo: a escolha do controlador vale.
1139
+ if (!this.nativeCaptions)
1140
+ this.applyTrackModes();
1141
+ this.update(true);
1142
+ });
1143
+ }
1144
+ }
1145
+ }
1146
+ //# sourceMappingURL=player.js.map