@banou/media-player 0.10.36 → 0.10.38

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/README.md CHANGED
@@ -234,8 +234,21 @@ reflect the real element froze the window: seeking while paused left the old sce
234
234
  transport state is carried by the Media Session instead, which is what the window reads for its
235
235
  play/pause button.
236
236
 
237
- If anything in that path is unavailable the player falls back to handing the browser the bare video,
238
- which plays without subtitles rather than not at all.
237
+ Frames are painted on the page's frame callbacks, which follow the browser window, not the picture
238
+ in picture one: they stop with the browser window minimized or off screen, while the window is still
239
+ on screen. A timer then paints at 60 a second instead. The page's own video is hidden while the
240
+ window is open, as Chrome's own picture in picture does, because a video shown in the page moves its
241
+ picture only on the page's rendering, so every paint would read the same frame for 250 ms. The
242
+ subtitles are rendered on the page's rendering too, so once they fall two seconds behind the video
243
+ they are left out of the window rather than shown wrong. `scripts/measure-picture-in-picture.mjs`
244
+ measures each state.
245
+
246
+ The window outlives the player. A player unmounted while its window is open leaves it open for a
247
+ second, and the next player mounted in the same document in that time plays in it, at the shape of
248
+ its own video. So an app that mounts a new player for the next episode keeps the window without a
249
+ click, which a new window would need. If no player takes the window in that second, it closes.
250
+
251
+ Where that path is unavailable the player offers no picture in picture control.
239
252
 
240
253
  ### Picture in picture for a media you do not own
241
254
 
@@ -1,2 +1,2 @@
1
- import { a as e, c as t, d as n, f as r, i, l as a, n as o, o as s, r as c, s as l, t as u, u as d } from "../engine-BZDbaSfM.js";
1
+ import { a as e, c as t, d as n, f as r, i, l as a, n as o, o as s, r as c, s as l, t as u, u as d } from "../engine-eF2uRLyY.js";
2
2
  export { i as DEFAULT_BUFFER_SIZE, e as MediaElementError, a as SUBTITLES_OFF, u as createPictureInPicture, d as createSubtitleRenderer, c as createThumbnailGenerator, n as getTimeRanges, s as isMediaElementError, o as pictureInPictureMode, l as startPlayback, t as terminateRemuxer, r as updateSourceBuffer };
@@ -24,7 +24,10 @@ export type PictureInPictureOptions = {
24
24
  */
25
25
  subtitles: HTMLElement;
26
26
  maxWidth?: number;
27
- /** Where the mirror is mounted. It must be in the document. Defaults to the video's parent. */
27
+ /**
28
+ * Where the mirror is mounted. It must be in the document. Defaults to the video's parent in burn-in, where the
29
+ * mirror is the picture, and to the body in a window, so the window can outlive the player (see `destroy`).
30
+ */
28
31
  container?: HTMLElement;
29
32
  /** Overrides detection. Passing a mode the browser cannot honour is the caller's problem. */
30
33
  mode?: PictureInPictureMode;
@@ -33,9 +36,17 @@ export type PictureInPictureOptions = {
33
36
  };
34
37
  export type PictureInPictureController = {
35
38
  toggle: () => Promise<void>;
39
+ /**
40
+ * Burn-in, or a window that is not open, ends here. An open window stays open for a second, and the
41
+ * next controller created in the document in that time draws its own video into it, at that video's
42
+ * shape: an app that replaces the player for the next episode keeps the window with no click, which
43
+ * a new window would need. If no controller takes it in that second, it closes.
44
+ */
36
45
  destroy: () => void;
37
46
  mode: PictureInPictureMode;
38
47
  };
48
+ /** How long a destroyed controller's window waits for the next one; a remounted player asks within a few frames. */
49
+ export declare const HAND_OVER_MS = 1000;
39
50
  /**
40
51
  * null means offer no control at all. That covers Safari, whose picture in picture is
41
52
  * `webkitSetPresentationMode` and not the W3C API, so neither arm here can drive it. A dead button
@@ -226,13 +226,13 @@ var i = {
226
226
  constructor(e, t) {
227
227
  super(e, t), this.name = "MediaElementError";
228
228
  }
229
- }, x = (e) => !!e && typeof e == "object" && e.mediaElement === !0, S = -20, C = 60, w = 30, T = -5, E = 20, D = 5, O = 15e3, k = 1, A = 3, ee = 12, te = 200, ne = 250, j = 25e5, M = (e) => {
229
+ }, x = (e) => !!e && typeof e == "object" && e.mediaElement === !0, S = -20, C = 60, w = 30, T = -5, E = 20, D = 5, O = 15e3, k = 1, A = 3, ee = 12, j = 200, te = 250, M = 25e5, N = (e) => {
230
230
  let { worker: t } = e, n = setTimeout(() => t.terminate(), 2e3);
231
231
  e.destroy().catch(() => {}).finally(() => {
232
232
  clearTimeout(n), t.terminate();
233
233
  });
234
- }, re = async (t) => {
235
- let { videoElement: n, subtitleContainer: r, read: i, length: a, publicPath: c, libavWorkerUrl: u, jassubWorkerUrl: d, jassubWasmUrl: f, jassubLegacyWasmUrl: p, defaultFontUrl: m, cjkFontUrl: h, bufferSize: g = j, audioStreamIndex: _, chooseAudioStream: v, onReady: x, onError: re, onRecovered: ie, onSeek: ae, onSubtitleStreams: oe, onAudioStreams: se, onOutput: N } = t, ce = (t) => e({
234
+ }, ne = async (t) => {
235
+ let { videoElement: n, subtitleContainer: r, read: i, length: a, publicPath: c, libavWorkerUrl: u, jassubWorkerUrl: d, jassubWasmUrl: f, jassubLegacyWasmUrl: p, defaultFontUrl: m, cjkFontUrl: h, bufferSize: g = M, audioStreamIndex: _, chooseAudioStream: v, onReady: x, onError: ne, onRecovered: P, onSeek: F, onSubtitleStreams: re, onAudioStreams: ie, onOutput: I } = t, ae = (t) => e({
236
236
  publicPath: c,
237
237
  workerUrl: u,
238
238
  workerOptions: { type: "module" },
@@ -240,20 +240,20 @@ var i = {
240
240
  length: a,
241
241
  audioStreamIndex: t,
242
242
  read: i
243
- }), P = await ce(_), F = [], I = !1, le = () => {
244
- if (!I) {
245
- I = !0;
246
- for (let e of [...F].reverse()) try {
243
+ }), L = await ae(_), R = [], z = !1, oe = () => {
244
+ if (!z) {
245
+ z = !0;
246
+ for (let e of [...R].reverse()) try {
247
247
  e();
248
248
  } catch {}
249
249
  }
250
250
  };
251
- F.push(() => M(P));
251
+ R.push(() => N(L));
252
252
  try {
253
- let e = await P.init(), t = _ ?? v?.(e.audioStreams ?? []);
254
- _ === void 0 && t !== void 0 && t !== e.audioStreams?.[0]?.streamIndex && (M(P), P = await ce(t), e = await P.init());
253
+ let e = await L.init(), t = _ ?? v?.(e.audioStreams ?? []);
254
+ _ === void 0 && t !== void 0 && t !== e.audioStreams?.[0]?.streamIndex && (N(L), L = await ae(t), e = await L.init());
255
255
  let i = e.audioStreams ?? [], a = i.some((e) => e.streamIndex === t) ? t : i[0]?.streamIndex ?? -1;
256
- se?.(i, a);
256
+ ie?.(i, a);
257
257
  let c = y({
258
258
  video: n,
259
259
  container: r,
@@ -262,186 +262,186 @@ var i = {
262
262
  legacyWasmUrl: p,
263
263
  defaultFontUrl: m,
264
264
  cjkFontUrl: h,
265
- onStreams: oe
265
+ onStreams: re
266
266
  });
267
- if (F.push(() => c.destroy()), e.attachments?.length && c.pushAttachments(e.attachments), !e.info.output.videoMimeType) throw o("The video codec in this file could not be identified");
267
+ if (R.push(() => c.destroy()), e.attachments?.length && c.pushAttachments(e.attachments), !e.info.output.videoMimeType) throw o("The video codec in this file could not be identified");
268
268
  let u = [e.info.output.videoMimeType, e.info.output.audioMimeType].filter(Boolean).join(","), g = `video/mp4; codecs="${u}"`;
269
269
  if (!MediaSource.isTypeSupported(g)) throw o("This browser cannot play the codecs in this file: {codecs}", { codecs: u });
270
- let j = new MediaSource(), ue = URL.createObjectURL(j);
271
- F.push(() => URL.revokeObjectURL(ue)), n.src = ue, F.push(() => {
270
+ let M = new MediaSource(), se = URL.createObjectURL(M);
271
+ R.push(() => URL.revokeObjectURL(se)), n.src = se, R.push(() => {
272
272
  try {
273
273
  n.pause();
274
274
  } catch {}
275
275
  n.removeAttribute("src"), n.load();
276
276
  });
277
- let L = await new Promise((t, n) => {
277
+ let B = await new Promise((t, n) => {
278
278
  let r = setTimeout(() => {
279
279
  i(), n(o("The MediaSource never opened"));
280
280
  }, O), i = () => {
281
- clearTimeout(r), j.removeEventListener("sourceopen", a), j.removeEventListener("sourceclose", s), j.removeEventListener("error", s);
281
+ clearTimeout(r), M.removeEventListener("sourceopen", a), M.removeEventListener("sourceclose", s), M.removeEventListener("error", s);
282
282
  }, a = () => {
283
283
  try {
284
- let n = j.addSourceBuffer(g);
284
+ let n = M.addSourceBuffer(g);
285
285
  n.mode = "segments", n.timestampOffset = e.timestampOffset;
286
286
  let r = e.info.input.duration;
287
- Number.isFinite(r) && r > 0 && (j.duration = r), i(), t(n);
287
+ Number.isFinite(r) && r > 0 && (M.duration = r), i(), t(n);
288
288
  } catch (e) {
289
289
  i(), n(e);
290
290
  }
291
291
  }, s = () => {
292
292
  i(), n(o("The MediaSource closed before a SourceBuffer could be created"));
293
293
  };
294
- j.addEventListener("sourceopen", a, { once: !0 }), j.addEventListener("sourceclose", s, { once: !0 }), j.addEventListener("error", s, { once: !0 });
295
- }), { appendBuffer: R, unbufferRange: de, endOfStream: fe } = l(L, j);
296
- await R(e.data), N?.({
294
+ M.addEventListener("sourceopen", a, { once: !0 }), M.addEventListener("sourceclose", s, { once: !0 }), M.addEventListener("error", s, { once: !0 });
295
+ }), { appendBuffer: ce, unbufferRange: le, endOfStream: ue } = l(B, M);
296
+ await ce(e.data), I?.({
297
297
  type: "init",
298
298
  data: e.data,
299
299
  audioMimeType: e.info.output.audioMimeType,
300
300
  audioStreamIndex: a
301
- }), N?.({
301
+ }), I?.({
302
302
  type: "run",
303
303
  pts: e.timestampOffset,
304
304
  from: 0
305
305
  }), e.subtitles?.length && c.pushFragments(e.subtitles), x?.();
306
- let z = !1, B = !1, V = 0, H, pe = () => H ?? n.currentTime, U = !1, me = !1, he = 0, W = 0, G = null, K = 0, q = 0, J = !1, ge = 0, Y = !0, X = (e, t, n = !1) => {
306
+ let V = !1, H = !1, U = 0, W, de = () => W ?? n.currentTime, G = !1, fe = !1, K = 0, q = 0, J = null, Y = 0, X = 0, pe = !1, me = 0, he = !0, ge = (e, t, n = !1) => {
307
307
  let r = e?.message === "Cancelled";
308
- t && r || (console.error(e), (!J || n) && (J = !0, re?.(r ? o("Reading the video file failed", void 0, { cause: e }) : e)));
308
+ t && r || (console.error(e), (!pe || n) && (pe = !0, ne?.(r ? o("Reading the video file failed", void 0, { cause: e }) : e)));
309
309
  }, _e = async (e = !1) => {
310
- if (V > 0 && !e) return;
311
- let t = n.currentTime, r = e ? T : S, i = e ? E : C, a = s(L), o = (e, t) => (Y = !1, de(e, t));
310
+ if (U > 0 && !e) return;
311
+ let t = n.currentTime, r = e ? T : S, i = e ? E : C, a = s(B), o = (e, t) => (he = !1, le(e, t));
312
312
  a.length && a[0].start < t + r && await o(0, t + r);
313
313
  for (let { end: e } of a) e > t + i && await o(t + i, e);
314
314
  }, ve = () => {
315
- let e = s(L);
315
+ let e = s(B);
316
316
  if (!e.length) return !0;
317
- let t = pe(), n = e.find((e) => e.start <= t + k && t < e.end);
317
+ let t = de(), n = e.find((e) => e.start <= t + k && t < e.end);
318
318
  return Ce() && xe(t) && (!n || n.start <= t) || n && n.end >= t + C ? !1 : !n || n.end < t + w;
319
- }, ye = (e) => s(L).find((t) => t.start <= e + k && e < t.end), be = () => ye(n.currentTime), xe = (e = n.currentTime) => {
319
+ }, ye = (e) => s(B).find((t) => t.start <= e + k && e < t.end), be = () => ye(n.currentTime), xe = (e = n.currentTime) => {
320
320
  let t = ye(e);
321
- return e >= q - .1 || !!t && t.end >= q - .1;
321
+ return e >= X - .1 || !!t && t.end >= X - .1;
322
322
  }, Se = () => {
323
- let e = s(L).map((e) => e.end);
324
- e.length && (q = Math.max(q, ...e)), U && (me = !0);
325
- }, Ce = () => U || me && (s(L).at(-1)?.end ?? 0) >= q - .1, we = async (t) => {
326
- B = !0, G = null, K = 0, ge = t, Y = !0;
327
- let n = ++W;
323
+ let e = s(B).map((e) => e.end);
324
+ e.length && (X = Math.max(X, ...e)), G && (fe = !0);
325
+ }, Ce = () => G || fe && (s(B).at(-1)?.end ?? 0) >= X - .1, we = async (t) => {
326
+ H = !0, J = null, Y = 0, me = t, he = !0;
327
+ let n = ++q;
328
328
  try {
329
- let { data: r, pts: i, subtitles: a, finished: o } = await P.seek(t);
330
- if (I || n !== W) return;
331
- o && (U = !0), a?.length && c.pushFragments(a), N?.({
329
+ let { data: r, pts: i, subtitles: a, finished: o } = await L.seek(t);
330
+ if (z || n !== q) return;
331
+ o && (G = !0), a?.length && c.pushFragments(a), I?.({
332
332
  type: "run",
333
333
  pts: e.timestampOffset,
334
334
  from: i
335
- }), r.byteLength && N?.({
335
+ }), r.byteLength && I?.({
336
336
  type: "fragment",
337
337
  data: r
338
- }), o && N?.({ type: "end" }), r.byteLength && (await R(r), Se());
338
+ }), o && I?.({ type: "end" }), r.byteLength && (await ce(r), Se());
339
339
  } catch (e) {
340
- n === W && (Y = !1), X(e, I || n !== W);
340
+ n === q && (he = !1), ge(e, z || n !== q);
341
341
  } finally {
342
- n === W && (B = !1);
342
+ n === q && (H = !1);
343
343
  }
344
344
  }, Te = async () => {
345
- let e = G;
345
+ let e = J;
346
346
  if (e) try {
347
- await R(e), Se(), G === e && (G = null, K = 0);
347
+ await ce(e), Se(), J === e && (J = null, Y = 0);
348
348
  } catch (t) {
349
- if (G !== e) return;
349
+ if (J !== e) return;
350
350
  if (t?.name === "QuotaExceededError") {
351
351
  let t = await _e(!0).then(() => !0, () => !1);
352
- if (G !== e) return;
352
+ if (J !== e) return;
353
353
  if (t) {
354
- U = !1, await we(be()?.end ?? n.currentTime);
354
+ G = !1, await we(be()?.end ?? n.currentTime);
355
355
  return;
356
356
  }
357
357
  }
358
- if (K += 1, K < D) return;
359
- throw G = null, t;
358
+ if (Y += 1, Y < D) return;
359
+ throw J = null, t;
360
360
  }
361
361
  }, Ee = async () => {
362
- if (z || B || $ !== void 0 || I || !G && (U || !ve())) return;
363
- let e = ++he, t = W, n = () => I || e !== he || t !== W;
364
- z = !0;
362
+ if (V || H || $ !== void 0 || z || !J && (G || !ve())) return;
363
+ let e = ++K, t = q, n = () => z || e !== K || t !== q;
364
+ V = !0;
365
365
  try {
366
- if (!G) {
367
- let { data: e, subtitles: t, finished: r } = await P.read();
368
- if (n() || (r && (U = !0), t?.length && c.pushFragments(t), e.byteLength && N?.({
366
+ if (!J) {
367
+ let { data: e, subtitles: t, finished: r } = await L.read();
368
+ if (n() || (r && (G = !0), t?.length && c.pushFragments(t), e.byteLength && I?.({
369
369
  type: "fragment",
370
370
  data: e
371
- }), r && N?.({ type: "end" }), !e.byteLength)) return;
372
- G = e, K = 0;
371
+ }), r && I?.({ type: "end" }), !e.byteLength)) return;
372
+ J = e, Y = 0;
373
373
  }
374
- await Te(), !n() && J && (J = !1, ie?.());
374
+ await Te(), !n() && pe && (pe = !1, P?.());
375
375
  } catch (e) {
376
- X(e, n());
376
+ ge(e, n());
377
377
  } finally {
378
- e === he && (z = !1);
378
+ e === K && (V = !1);
379
379
  }
380
- }, De = (e) => s(L).some((t) => t.start <= e && e < t.end && t.end >= ge) && ke(e), Oe = (e) => s(L).some((t) => t.start <= e && e < t.end), Z = (e) => {
380
+ }, De = (e) => s(B).some((t) => t.start <= e && e < t.end && t.end >= me) && ke(e), Oe = (e) => s(B).some((t) => t.start <= e && e < t.end), Z = (e) => {
381
381
  let t = ye(e);
382
382
  return t ? t.end - e : 0;
383
383
  }, ke = (e) => Z(e) >= A || Ce() && xe(e), Ae = async (e) => {
384
- if (!I && !(Oe(e) && ke(e))) {
385
- $ && clearTimeout($), $ = void 0, U = !1, V++, H = e;
384
+ if (!z && !(Oe(e) && ke(e))) {
385
+ $ && clearTimeout($), $ = void 0, G = !1, U++, W = e;
386
386
  try {
387
387
  await we(e);
388
- let t = W;
389
- for (let n = 0; n < ee && !(I || t !== W || U || Z(e) >= A); n++) {
388
+ let t = q;
389
+ for (let n = 0; n < ee && !(z || t !== q || G || Z(e) >= A); n++) {
390
390
  let t = Z(e);
391
391
  if (await Ee(), Z(e) <= t) break;
392
392
  }
393
393
  } finally {
394
- V--, H === e && (H = void 0);
394
+ U--, W === e && (W = void 0);
395
395
  }
396
396
  }
397
397
  }, je = 0, Me = null, Q, Ne = (e) => {
398
398
  let t = performance.now(), n = t - je;
399
- if (n >= te) {
400
- je = t, Me = null, ae?.(e);
399
+ if (n >= j) {
400
+ je = t, Me = null, F?.(e);
401
401
  return;
402
402
  }
403
403
  Me = e, !Q && (Q = setTimeout(() => {
404
404
  Q = void 0;
405
405
  let e = Me;
406
- Me = null, !(e === null || I) && (je = performance.now(), ae?.(e));
407
- }, te - n));
406
+ Me = null, !(e === null || z) && (je = performance.now(), F?.(e));
407
+ }, j - n));
408
408
  };
409
- F.push(() => {
409
+ R.push(() => {
410
410
  Q && clearTimeout(Q);
411
411
  });
412
412
  let Pe = 0, $;
413
- F.push(() => {
413
+ R.push(() => {
414
414
  $ && clearTimeout($);
415
415
  });
416
416
  let Fe = () => {
417
417
  let t = n.currentTime, r = e.info.input.duration || n.duration;
418
418
  r > 0 && Ne(Math.min(Math.max(t / r, 0), 1));
419
- let i = performance.now(), a = i - Pe < ne;
420
- if (Pe = i, !De(t) && !(Y && (B || Z(t) > 0) && Math.abs(t - ge) < .001)) {
421
- if (U = !1, $ && clearTimeout($), !a) {
419
+ let i = performance.now(), a = i - Pe < te;
420
+ if (Pe = i, !De(t) && !(he && (H || Z(t) > 0) && Math.abs(t - me) < .001)) {
421
+ if (G = !1, $ && clearTimeout($), !a) {
422
422
  $ = void 0, we(t);
423
423
  return;
424
424
  }
425
425
  $ = setTimeout(() => {
426
- if ($ = void 0, I) return;
426
+ if ($ = void 0, z) return;
427
427
  let e = n.currentTime;
428
- De(e) || (U = !1, we(e));
429
- }, ne);
428
+ De(e) || (G = !1, we(e));
429
+ }, te);
430
430
  }
431
431
  };
432
- n.addEventListener("seeking", Fe), F.push(() => n.removeEventListener("seeking", Fe));
432
+ n.addEventListener("seeking", Fe), R.push(() => n.removeEventListener("seeking", Fe));
433
433
  let Ie = !1, Le = () => {
434
434
  if (Ie) return;
435
435
  Ie = !0;
436
436
  let e = n.error;
437
- X(new b(`the media element failed: ${e?.message ?? "unknown"}`, { cause: e }), !1, !0);
437
+ ge(new b(`the media element failed: ${e?.message ?? "unknown"}`, { cause: e }), !1, !0);
438
438
  };
439
- n.addEventListener("error", Le), F.push(() => n.removeEventListener("error", Le));
439
+ n.addEventListener("error", Le), R.push(() => n.removeEventListener("error", Le));
440
440
  let Re = setInterval(() => {
441
- Ie || n.error || (_e().catch(() => {}), Ee().catch((e) => X(e, !1)), Ce() && !G && xe() && j.readyState === "open" && fe(() => !B).catch(() => {}));
441
+ Ie || n.error || (_e().catch(() => {}), Ee().catch((e) => ge(e, !1)), Ce() && !J && xe() && M.readyState === "open" && ue(() => !H).catch(() => {}));
442
442
  }, 100);
443
- return F.push(() => clearInterval(Re)), {
444
- destroy: le,
443
+ return R.push(() => clearInterval(Re)), {
444
+ destroy: oe,
445
445
  prepareSeek: Ae,
446
446
  videoElement: n,
447
447
  selectSubtitleStream: (e) => c.selectStream(e),
@@ -452,10 +452,10 @@ var i = {
452
452
  audioMimeType: e.info.output.audioMimeType
453
453
  };
454
454
  } catch (e) {
455
- throw le(), e;
455
+ throw oe(), e;
456
456
  }
457
- }, ie = 5, ae = 500, oe = 320, se = 1e6, N = 3, ce = 1e4, P = 1.5, F = 4e6, I = 3e4, le = async (e) => {
458
- let { publicPath: n, workerUrl: r, length: i, read: a, onThumbnails: o, width: s = oe } = e, c = await t({
457
+ }, P = 5, F = 500, re = 320, ie = 1e6, I = 3, ae = 1e4, L = 1.5, R = 4e6, z = 3e4, oe = async (e) => {
458
+ let { publicPath: n, workerUrl: r, length: i, read: a, onThumbnails: o, width: s = re } = e, c = await t({
459
459
  publicPath: n,
460
460
  workerUrl: r,
461
461
  workerOptions: { type: "module" },
@@ -463,7 +463,7 @@ var i = {
463
463
  read: a
464
464
  });
465
465
  try {
466
- let t = await c.init(), n = t.duration, r = Math.max(e.interval ?? ie, n / ae), a = [], l = (e) => {
466
+ let t = await c.init(), n = t.duration, r = Math.max(e.interval ?? P, n / F), a = [], l = (e) => {
467
467
  let t = [];
468
468
  for (let [a, o] of e.entries()) {
469
469
  let s = t.at(-1);
@@ -471,7 +471,7 @@ var i = {
471
471
  timestamp: o.timestamp,
472
472
  endTime: n,
473
473
  startByte: o.pos,
474
- endByte: Math.min((e[a + 1]?.pos ?? i) + se, i),
474
+ endByte: Math.min((e[a + 1]?.pos ?? i) + ie, i),
475
475
  done: !1,
476
476
  attempts: 0
477
477
  });
@@ -510,7 +510,7 @@ var i = {
510
510
  }), o(e);
511
511
  }, x = async (e) => {
512
512
  if (d) return;
513
- let t = await Promise.race([c.readKeyframe(e.timestamp), new Promise((e, t) => setTimeout(() => t(/* @__PURE__ */ Error("timed out")), ce))]), n = await createImageBitmap(new Blob([t], { type: "image/png" })), r = new OffscreenCanvas(s, Math.max(1, Math.round(n.height * (s / n.width))));
513
+ let t = await Promise.race([c.readKeyframe(e.timestamp), new Promise((e, t) => setTimeout(() => t(/* @__PURE__ */ Error("timed out")), ae))]), n = await createImageBitmap(new Blob([t], { type: "image/png" })), r = new OffscreenCanvas(s, Math.max(1, Math.round(n.height * (s / n.width))));
514
514
  r.getContext("2d").drawImage(n, 0, 0, r.width, r.height), n.close();
515
515
  let i = await r.convertToBlob({
516
516
  type: "image/webp",
@@ -534,7 +534,7 @@ var i = {
534
534
  if (!f.length) return;
535
535
  let e = f.splice(y(), 1)[0];
536
536
  p = !0, x(e).catch(() => {
537
- e.attempts += 1, e.done = e.attempts >= N;
537
+ e.attempts += 1, e.done = e.attempts >= I;
538
538
  }).finally(() => {
539
539
  p = !1, S();
540
540
  });
@@ -543,7 +543,7 @@ var i = {
543
543
  }, w = async (e) => {
544
544
  _ = !0;
545
545
  try {
546
- let t = await Promise.race([c.init(), new Promise((e, t) => setTimeout(() => t(/* @__PURE__ */ Error("timed out")), I))]);
546
+ let t = await Promise.race([c.init(), new Promise((e, t) => setTimeout(() => t(/* @__PURE__ */ Error("timed out")), z))]);
547
547
  if (d) return;
548
548
  h = e;
549
549
  let n = l(t.indexes);
@@ -569,7 +569,7 @@ var i = {
569
569
  if (d) return;
570
570
  v = e;
571
571
  let t = T(e);
572
- h < 0 ? h = t : (t >= Math.max(h * P, h + F) || t >= i && h < i) && (g = !0), E(e), S();
572
+ h < 0 ? h = t : (t >= Math.max(h * L, h + R) || t >= i && h < i) && (g = !0), E(e), S();
573
573
  },
574
574
  prioritize: (e) => {
575
575
  d || (m = e);
@@ -577,127 +577,169 @@ var i = {
577
577
  destroy: () => {
578
578
  d = !0, f.length = 0;
579
579
  for (let e of u) URL.revokeObjectURL(e.url);
580
- u = [], M(c);
580
+ u = [], N(c);
581
581
  }
582
582
  };
583
583
  } catch (e) {
584
- throw M(c), e;
584
+ throw N(c), e;
585
585
  }
586
- }, ue = 1280, L = 1920, R = 250, de = 100, fe = () => typeof HTMLCanvasElement < "u" && "captureStream" in HTMLCanvasElement.prototype, z = () => typeof document < "u" && typeof HTMLVideoElement < "u" && typeof HTMLVideoElement.prototype.requestPictureInPicture == "function" && !!document.pictureInPictureEnabled, B = () => typeof HTMLVideoElement < "u" && "mozCaptureStream" in HTMLVideoElement.prototype, V = () => fe() ? z() ? "window" : B() ? "burn-in" : null : null, H = (e) => {
587
- let { video: t, subtitles: n } = e, r = e.mode ?? V() ?? "window", i = e.maxWidth ?? (r === "burn-in" ? L : ue), a, o, s, c = !1, l = !1, u = !1, d = !1, f, p = () => r === "burn-in" ? !!a : !!a && document.pictureInPictureElement === a.mirror, m = (e, r) => {
586
+ }, se = 1280, B = 1920, ce = 100, le = 1e3 / 60, ue = 250, V = 2, H = 100, U = 1e3, W, de = (e) => {
587
+ W?.close();
588
+ let t = () => {
589
+ clearTimeout(r), e.mirror.removeEventListener("leavepictureinpicture", n), W = void 0;
590
+ }, n = () => {
591
+ t(), document.pictureInPictureElement === e.mirror && document.exitPictureInPicture().catch(() => {});
592
+ for (let t of e.stream.getTracks()) t.stop();
593
+ e.mirror.remove();
594
+ }, r = setTimeout(n, U);
595
+ e.mirror.addEventListener("leavepictureinpicture", n), W = {
596
+ session: e,
597
+ close: n,
598
+ cancel: t
599
+ };
600
+ }, G = () => {
601
+ let e = W;
602
+ return e?.cancel(), e?.session;
603
+ }, fe = () => typeof HTMLCanvasElement < "u" && "captureStream" in HTMLCanvasElement.prototype, K = () => typeof document < "u" && typeof HTMLVideoElement < "u" && typeof HTMLVideoElement.prototype.requestPictureInPicture == "function" && !!document.pictureInPictureEnabled, q = () => typeof HTMLVideoElement < "u" && "mozCaptureStream" in HTMLVideoElement.prototype, J = () => fe() ? K() ? "window" : q() ? "burn-in" : null : null, Y = (e) => {
604
+ let { video: t, subtitles: n } = e, r = e.mode ?? J() ?? "window", i = e.maxWidth ?? (r === "burn-in" ? B : se), a, o, s, c = 0, l = 0, u = 0, d = !1, f = !1, p = !1, m = !1, h, g = () => r === "burn-in" ? !!a : !!a && document.pictureInPictureElement === a.mirror, _ = (e, r) => {
588
605
  r.drawImage(t, 0, 0, e.width, e.height);
589
606
  let i = n.querySelector("canvas");
590
- i && i.width > 0 && i.height > 0 && r.drawImage(i, 0, 0, e.width, e.height);
591
- }, h = () => {
592
- a && m(a.composite, a.context);
593
- }, g = "requestVideoFrameCallback" in t, _ = () => {
594
- h(), v();
607
+ i && i.width > 0 && i.height > 0 && Math.abs(t.currentTime - u) <= V && r.drawImage(i, 0, 0, e.width, e.height);
595
608
  }, v = () => {
596
- !d && a && (o = g ? t.requestVideoFrameCallback(_) : requestAnimationFrame(_));
609
+ let e = Math.min(t.videoWidth || i, i);
610
+ return {
611
+ width: e,
612
+ height: Math.round(e * ((t.videoHeight || 9) / (t.videoWidth || 16)))
613
+ };
597
614
  }, y = () => {
598
- o !== void 0 && (g ? t.cancelVideoFrameCallback(o) : cancelAnimationFrame(o)), s !== void 0 && clearInterval(s), o = void 0, s = void 0;
599
- }, b = () => {
600
- "mediaSession" in navigator && (navigator.mediaSession.playbackState = t.paused ? "paused" : "playing");
601
- }, x = () => {
602
- c || l || !t.paused || t.play().catch(() => {});
615
+ if (!a) return;
616
+ let { composite: e, context: n } = a, { width: r, height: i } = v();
617
+ t.videoWidth && (e.width !== r || e.height !== i) && Object.assign(e, {
618
+ width: r,
619
+ height: i
620
+ }), l = performance.now(), _(e, n);
621
+ }, b = "requestVideoFrameCallback" in t, x = () => {
622
+ c = performance.now(), u = t.currentTime, y(), S();
603
623
  }, S = () => {
604
- c || l || (t.paused || t.pause(), r !== "burn-in" && (c = !0, a?.mirror.play().catch(() => {}).finally(() => {
605
- c = !1;
606
- })));
624
+ !m && a && (o = b ? t.requestVideoFrameCallback(x) : requestAnimationFrame(x));
607
625
  }, C = () => {
608
- b(), a?.mirror.play().catch(() => {});
626
+ o !== void 0 && (b ? t.cancelVideoFrameCallback(o) : cancelAnimationFrame(o)), s !== void 0 && clearInterval(s), o = void 0, s = void 0;
609
627
  }, w = () => {
610
- b(), r === "burn-in" && a?.mirror.pause();
628
+ "mediaSession" in navigator && (navigator.mediaSession.playbackState = t.paused ? "paused" : "playing");
611
629
  }, T = () => {
612
- if (r !== "burn-in" || !a || !t.paused || l) return;
613
- l = !0;
630
+ d || f || !t.paused || t.play().catch(() => {});
631
+ }, E = () => {
632
+ d || f || (t.paused || t.pause(), r !== "burn-in" && (d = !0, a?.mirror.play().catch(() => {}).finally(() => {
633
+ d = !1;
634
+ })));
635
+ }, D = () => {
636
+ w(), a?.mirror.play().catch(() => {});
637
+ }, O = () => {
638
+ w(), r === "burn-in" && a?.mirror.pause();
639
+ }, k = () => {
640
+ if (r !== "burn-in" || !a || !t.paused || f) return;
641
+ f = !0;
614
642
  let { mirror: e } = a;
615
- h(), e.play().then(() => new Promise((e) => {
616
- setTimeout(e, de);
643
+ y(), e.play().then(() => new Promise((e) => {
644
+ setTimeout(e, H);
617
645
  })).catch(() => {}).finally(() => {
618
646
  e.pause(), setTimeout(() => {
619
- l = !1;
620
- }, de);
647
+ f = !1;
648
+ }, H);
621
649
  });
622
- }, E = [["play", () => {
650
+ }, A = [["play", () => {
623
651
  t.play().catch(() => {});
624
- }], ["pause", () => t.pause()]], D = (e) => {
625
- if ("mediaSession" in navigator) for (let [t, n] of E) try {
652
+ }], ["pause", () => t.pause()]], ee = (e) => {
653
+ if ("mediaSession" in navigator) for (let [t, n] of A) try {
626
654
  navigator.mediaSession.setActionHandler(t, e ? n : null);
627
655
  } catch {}
628
- }, O = () => {
629
- if (y(), D(!1), t.removeEventListener("play", C), t.removeEventListener("pause", w), t.removeEventListener("seeked", T), !a) {
630
- f?.();
631
- return;
656
+ }, j = () => {
657
+ u = t.currentTime, S(), s = setInterval(() => {
658
+ let e = performance.now();
659
+ e - c < ce || t.paused && e - l < ue || y();
660
+ }, le);
661
+ }, te = (e) => {
662
+ e.addEventListener("play", T), e.addEventListener("pause", E), e.addEventListener("leavepictureinpicture", ne), t.addEventListener("play", D), t.addEventListener("pause", O), t.addEventListener("seeked", k), ee(!0), w();
663
+ }, M = () => {
664
+ C(), ee(!1), t.removeEventListener("play", D), t.removeEventListener("pause", O), t.removeEventListener("seeked", k);
665
+ let e = a;
666
+ return a = void 0, e?.mirror.removeEventListener("play", T), e?.mirror.removeEventListener("pause", E), e?.mirror.removeEventListener("leavepictureinpicture", ne), e;
667
+ }, N = () => {
668
+ let e = M();
669
+ if (e) {
670
+ for (let t of e.stream.getTracks()) t.stop();
671
+ e.mirror.remove();
632
672
  }
633
- let { stream: e, mirror: n } = a;
634
- n.removeEventListener("play", x), n.removeEventListener("pause", S), n.removeEventListener("leavepictureinpicture", k);
635
- for (let t of e.getTracks()) t.stop();
636
- n.remove(), a = void 0, f?.();
637
- }, k = () => O(), A = (e) => {
673
+ h?.();
674
+ }, ne = () => N(), P = () => {
675
+ let e = t.style.visibility;
676
+ t.style.visibility = "hidden", h = () => {
677
+ h = void 0, t.style.visibility = e;
678
+ };
679
+ }, F = (e) => {
638
680
  let r = t.style.opacity, i = n.style.display;
639
- e.style.cssText = "position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#000;z-index:1", t.style.opacity = "0", n.style.display = "none", f = () => {
640
- f = void 0, t.style.opacity = r, n.style.display = i;
681
+ e.style.cssText = "position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#000;z-index:1", t.style.opacity = "0", n.style.display = "none", h = () => {
682
+ h = void 0, t.style.opacity = r, n.style.display = i;
641
683
  };
642
- }, ee = async () => {
643
- let n = Math.min(t.videoWidth || i, i), o = Math.round(n * ((t.videoHeight || 9) / (t.videoWidth || 16))), c = document.createElement("canvas");
644
- c.width = n, c.height = o;
645
- let l = c.getContext("2d");
646
- if (!l) throw Error("the picture in picture composite has no 2d context");
647
- let u = document.createElement("video");
648
- u.muted = !0, u.playsInline = !0, r === "burn-in" ? A(u) : u.style.cssText = "position:fixed;width:1px;height:1px;opacity:0;pointer-events:none;left:-1px;top:-1px", m(c, l);
649
- let f = {
650
- composite: c,
651
- context: l,
652
- stream: c.captureStream(),
653
- mirror: u
684
+ }, re = async () => {
685
+ let n = Object.assign(document.createElement("canvas"), v()), i = n.getContext("2d");
686
+ if (!i) throw Error("the picture in picture composite has no 2d context");
687
+ let o = document.createElement("video");
688
+ o.muted = !0, o.playsInline = !0, r === "burn-in" ? F(o) : o.style.cssText = "position:fixed;width:1px;height:1px;opacity:0;pointer-events:none;left:-1px;top:-1px", _(n, i);
689
+ let s = {
690
+ composite: n,
691
+ context: i,
692
+ stream: n.captureStream(),
693
+ mirror: o
654
694
  };
655
- if (a = f, u.srcObject = f.stream, (e.container ?? t.parentElement ?? document.body).appendChild(u), v(), s = setInterval(() => {
656
- t.paused && h();
657
- }, R), u.play().catch(() => {}), u.readyState === 0 && await new Promise((e) => {
695
+ if (a = s, o.srcObject = s.stream, (e.container ?? (r === "burn-in" ? t.parentElement : null) ?? document.body).appendChild(o), j(), o.play().catch(() => {}), o.readyState === 0 && await new Promise((e) => {
658
696
  let t = () => {
659
697
  clearTimeout(n), e();
660
698
  }, n = setTimeout(t, 1e3);
661
- u.addEventListener("loadedmetadata", t, { once: !0 });
662
- }), d || a !== f) {
663
- u.remove();
699
+ o.addEventListener("loadedmetadata", t, { once: !0 });
700
+ }), m || a !== s) {
701
+ o.remove();
664
702
  return;
665
703
  }
666
- if (u.addEventListener("play", x), u.addEventListener("pause", S), u.addEventListener("leavepictureinpicture", k), t.addEventListener("play", C), t.addEventListener("pause", w), t.addEventListener("seeked", T), D(!0), b(), r === "burn-in") {
667
- t.paused && u.pause(), e.onBurnedInChange?.(!0);
704
+ if (te(o), r === "burn-in") {
705
+ t.paused && o.pause(), e.onBurnedInChange?.(!0);
668
706
  return;
669
707
  }
670
- await u.requestPictureInPicture();
671
- };
672
- return {
673
- toggle: async () => {
674
- if (!(d || u)) {
675
- u = !0;
676
- try {
677
- if (p()) {
678
- if (r === "burn-in") {
679
- O(), e.onBurnedInChange?.(!1);
680
- return;
681
- }
682
- await document.exitPictureInPicture().catch(() => {});
708
+ await o.requestPictureInPicture(), a === s && P();
709
+ }, ie = async () => {
710
+ if (!(m || p)) {
711
+ p = !0;
712
+ try {
713
+ if (g()) {
714
+ if (r === "burn-in") {
715
+ N(), e.onBurnedInChange?.(!1);
683
716
  return;
684
717
  }
685
- r !== "burn-in" && document.pictureInPictureElement && await document.exitPictureInPicture().catch(() => {});
686
- try {
687
- await ee();
688
- } catch (t) {
689
- console.warn("subtitle compositing for picture in picture failed", t), O(), r === "burn-in" && e.onBurnedInChange?.(!1);
690
- }
691
- } finally {
692
- u = !1;
718
+ await document.exitPictureInPicture().catch(() => {});
719
+ return;
693
720
  }
721
+ r !== "burn-in" && document.pictureInPictureElement && await document.exitPictureInPicture().catch(() => {});
722
+ try {
723
+ await re();
724
+ } catch (t) {
725
+ console.warn("subtitle compositing for picture in picture failed", t), N(), r === "burn-in" && e.onBurnedInChange?.(!1);
726
+ }
727
+ } finally {
728
+ p = !1;
694
729
  }
695
- },
730
+ }
731
+ }, I = r === "window" ? G() : void 0;
732
+ return I && (a = I, I.context.fillRect(0, 0, I.composite.width, I.composite.height), j(), te(I.mirror), P()), {
733
+ toggle: ie,
696
734
  mode: r,
697
735
  destroy: () => {
698
- d = !0, r !== "burn-in" && p() && document.exitPictureInPicture().catch(() => {}), O(), r === "burn-in" && e.onBurnedInChange?.(!1);
736
+ if (m = !0, r === "window" && g()) {
737
+ let e = M();
738
+ return h?.(), de(e);
739
+ }
740
+ N(), r === "burn-in" && e.onBurnedInChange?.(!1);
699
741
  }
700
742
  };
701
743
  };
702
744
  //#endregion
703
- export { b as a, M as c, s as d, l as f, j as i, u as l, a as m, V as n, x as o, i as p, le as r, re as s, H as t, y as u };
745
+ export { b as a, N as c, s as d, l as f, M as i, u as l, a as m, J as n, x as o, i as p, oe as r, ne as s, Y as t, y as u };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { c as e, l as t, m as n, n as r, o as i, p as a, r as o, s, t as c, u as l } from "./engine-BZDbaSfM.js";
1
+ import { c as e, l as t, m as n, n as r, o as i, p as a, r as o, s, t as c, u as l } from "./engine-eF2uRLyY.js";
2
2
  import { languageOf as u, playsIn as d, startingTracks as f } from "./language/index.js";
3
3
  import { n as p, r as m, t as h } from "./chapters-EBYXcEml.js";
4
4
  import { Children as g, Fragment as _, createContext as v, isValidElement as y, useCallback as b, useContext as x, useEffect as S, useMemo as C, useRef as w, useState as T, useSyncExternalStore as E } from "react";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banou/media-player",
3
- "version": "0.10.36",
3
+ "version": "0.10.38",
4
4
  "description": "A video player for containers and codecs the browser cannot play natively, remuxed on the fly",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -13,8 +13,23 @@ const DEFAULT_MAX_WIDTH = 1280
13
13
  * thumbnail-sized window does. A 4K source is still halved; see the note on `compositeWidth`.
14
14
  */
15
15
  const BURN_IN_MAX_WIDTH = 1920
16
- /** The frame callback fires only for presented frames, so a paused video needs its own repaint. */
17
- const PAUSED_REPAINT_INTERVAL = 250
16
+ /**
17
+ * Frame callbacks follow the BROWSER window's rendering, not the picture in picture window's: none with that window
18
+ * minimized or off screen (one a second on niri), while the picture in picture window is still shown. A timer paints
19
+ * once they have been silent this long. A paused video presents no frames either, and is repainted only every
20
+ * `PAUSED_REPAINT_MS`, for a seek or a subtitle change. `scripts/measure-picture-in-picture.mjs`, 2026-11-09, Chrome 156
21
+ * on weston, a 24 fps video, minimized or off screen: 0 different frames a second in the window before, 24 with this
22
+ * and `hidePicture`.
23
+ */
24
+ const STALLED_MS = 100
25
+ const REPAINT_TICK_MS = 1000 / 60
26
+ const PAUSED_REPAINT_MS = 250
27
+ /**
28
+ * The subtitle surface is rendered on the same frame callbacks, from a worker whose frames reach the page only while
29
+ * the page renders, so with the browser window off screen it keeps its last line. Drawn only while it is at most this
30
+ * far behind the video's time, which a page rendering once a second still is.
31
+ */
32
+ const STALE_SUBTITLES_S = 2
18
33
  /** Long enough for a paused mirror to present one frame of a fresh seek before it stops again. */
19
34
  const FLUSH_FRAME_MS = 100
20
35
 
@@ -37,7 +52,10 @@ export type PictureInPictureOptions = {
37
52
  */
38
53
  subtitles: HTMLElement
39
54
  maxWidth?: number
40
- /** Where the mirror is mounted. It must be in the document. Defaults to the video's parent. */
55
+ /**
56
+ * Where the mirror is mounted. It must be in the document. Defaults to the video's parent in burn-in, where the
57
+ * mirror is the picture, and to the body in a window, so the window can outlive the player (see `destroy`).
58
+ */
41
59
  container?: HTMLElement
42
60
  /** Overrides detection. Passing a mode the browser cannot honour is the caller's problem. */
43
61
  mode?: PictureInPictureMode
@@ -47,6 +65,12 @@ export type PictureInPictureOptions = {
47
65
 
48
66
  export type PictureInPictureController = {
49
67
  toggle: () => Promise<void>
68
+ /**
69
+ * Burn-in, or a window that is not open, ends here. An open window stays open for a second, and the
70
+ * next controller created in the document in that time draws its own video into it, at that video's
71
+ * shape: an app that replaces the player for the next episode keeps the window with no click, which
72
+ * a new window would need. If no controller takes it in that second, it closes.
73
+ */
50
74
  destroy: () => void
51
75
  mode: PictureInPictureMode
52
76
  }
@@ -58,6 +82,36 @@ type Session = {
58
82
  mirror: HTMLVideoElement
59
83
  }
60
84
 
85
+ /** How long a destroyed controller's window waits for the next one; a remounted player asks within a few frames. */
86
+ export const HAND_OVER_MS = 1000
87
+
88
+ let handedOver: { session: Session, close: () => void, cancel: () => void } | undefined
89
+
90
+ const handOver = (session: Session) => {
91
+ handedOver?.close()
92
+ const cancel = () => {
93
+ clearTimeout(timer)
94
+ session.mirror.removeEventListener('leavepictureinpicture', close)
95
+ handedOver = undefined
96
+ }
97
+ const close = () => {
98
+ cancel()
99
+ if (document.pictureInPictureElement === session.mirror) void document.exitPictureInPicture().catch(() => {})
100
+ for (const track of session.stream.getTracks()) track.stop()
101
+ session.mirror.remove()
102
+ }
103
+ const timer = setTimeout(close, HAND_OVER_MS)
104
+ session.mirror.addEventListener('leavepictureinpicture', close)
105
+ handedOver = { session, close, cancel }
106
+ }
107
+
108
+ /** The window a destroyed controller left, until it closes. */
109
+ const takeOver = () => {
110
+ const held = handedOver
111
+ held?.cancel()
112
+ return held?.session
113
+ }
114
+
61
115
  const canComposite = () =>
62
116
  typeof HTMLCanvasElement !== 'undefined' && 'captureStream' in HTMLCanvasElement.prototype
63
117
 
@@ -100,7 +154,11 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
100
154
 
101
155
  let session: Session | undefined
102
156
  let handle: number | undefined
103
- let pausedRepaint: ReturnType<typeof setInterval> | undefined
157
+ let repaint: ReturnType<typeof setInterval> | undefined
158
+ let lastFrame = 0
159
+ let lastPaint = 0
160
+ /** The video's time at the last frame callback, which the subtitle surface was rendered for. */
161
+ let frameTime = 0
104
162
  let syncing = false
105
163
  /** Burn-in only: a deliberate play/pause pair to push one frame, which must not reach the video. */
106
164
  let flushing = false
@@ -123,18 +181,34 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
123
181
  // jassub has transferred reports the size of the last frame its worker committed, so the zero
124
182
  // check still keeps drawImage off a source with no dimensions to read.
125
183
  const surface = subtitles.querySelector('canvas')
126
- if (surface && surface.width > 0 && surface.height > 0) {
184
+ if (surface && surface.width > 0 && surface.height > 0 && Math.abs(video.currentTime - frameTime) <= STALE_SUBTITLES_S) {
127
185
  context.drawImage(surface, 0, 0, composite.width, composite.height)
128
186
  }
129
187
  }
130
188
 
189
+ // Sized off the intrinsic dimensions, never the layout, so only a video of another size resizes a
190
+ // canvas that a MediaStream is capturing. A window taken over starts at the size of the video before.
191
+ const compositeSize = () => {
192
+ const width = Math.min(video.videoWidth || maxWidth, maxWidth)
193
+ return { width, height: Math.round(width * ((video.videoHeight || 9) / (video.videoWidth || 16))) }
194
+ }
195
+
131
196
  const paint = () => {
132
- if (session) draw(session.composite, session.context)
197
+ if (!session) return
198
+ const { composite, context } = session
199
+ const { width, height } = compositeSize()
200
+ if (video.videoWidth && (composite.width !== width || composite.height !== height)) {
201
+ Object.assign(composite, { width, height })
202
+ }
203
+ lastPaint = performance.now()
204
+ draw(composite, context)
133
205
  }
134
206
 
135
207
  const useFrameCallback = 'requestVideoFrameCallback' in video
136
208
 
137
209
  const loop = () => {
210
+ lastFrame = performance.now()
211
+ frameTime = video.currentTime
138
212
  paint()
139
213
  schedule()
140
214
  }
@@ -149,9 +223,9 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
149
223
  if (useFrameCallback) video.cancelVideoFrameCallback(handle)
150
224
  else cancelAnimationFrame(handle)
151
225
  }
152
- if (pausedRepaint !== undefined) clearInterval(pausedRepaint)
226
+ if (repaint !== undefined) clearInterval(repaint)
153
227
  handle = undefined
154
- pausedRepaint = undefined
228
+ repaint = undefined
155
229
  }
156
230
 
157
231
  const publishState = () => {
@@ -233,31 +307,71 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
233
307
  }
234
308
  }
235
309
 
236
- const teardown = () => {
310
+ const start = () => {
311
+ frameTime = video.currentTime
312
+ schedule()
313
+ repaint = setInterval(() => {
314
+ const now = performance.now()
315
+ if (now - lastFrame < STALLED_MS || (video.paused && now - lastPaint < PAUSED_REPAINT_MS)) return
316
+ paint()
317
+ }, REPAINT_TICK_MS)
318
+ }
319
+
320
+ const listen = (mirror: HTMLVideoElement) => {
321
+ mirror.addEventListener('play', onMirrorPlay)
322
+ mirror.addEventListener('pause', onMirrorPause)
323
+ mirror.addEventListener('leavepictureinpicture', onLeave)
324
+ video.addEventListener('play', onVideoPlay)
325
+ video.addEventListener('pause', onVideoPause)
326
+ video.addEventListener('seeked', onVideoSeeked)
327
+ bindMediaSession(true)
328
+ publishState()
329
+ }
330
+
331
+ /** Lets go of the session, mirror and window left as they are. */
332
+ const detach = () => {
237
333
  stopLoop()
238
334
  bindMediaSession(false)
239
335
  video.removeEventListener('play', onVideoPlay)
240
336
  video.removeEventListener('pause', onVideoPause)
241
337
  video.removeEventListener('seeked', onVideoSeeked)
242
- if (!session) {
243
- // a burn-in that never built a session can still have swapped the picture
244
- restore?.()
245
- return
246
- }
247
- const { stream, mirror } = session
248
- mirror.removeEventListener('play', onMirrorPlay)
249
- mirror.removeEventListener('pause', onMirrorPause)
250
- mirror.removeEventListener('leavepictureinpicture', onLeave)
251
- for (const track of stream.getTracks()) track.stop()
252
- mirror.remove()
338
+ const held = session
253
339
  session = undefined
340
+ held?.mirror.removeEventListener('play', onMirrorPlay)
341
+ held?.mirror.removeEventListener('pause', onMirrorPause)
342
+ held?.mirror.removeEventListener('leavepictureinpicture', onLeave)
343
+ return held
344
+ }
345
+
346
+ const teardown = () => {
347
+ const held = detach()
348
+ if (held) {
349
+ for (const track of held.stream.getTracks()) track.stop()
350
+ held.mirror.remove()
351
+ }
254
352
  // AFTER the mirror is gone. Restoring first puts the real picture and the overlay back while the
255
353
  // composite is still mounted and painting, which is the doubled subtitles this mode exists to avoid.
354
+ // A burn-in that never built a session can still have swapped the picture.
256
355
  restore?.()
257
356
  }
258
357
 
259
358
  const onLeave = () => teardown()
260
359
 
360
+ /**
361
+ * Window only, while it is open. A video shown in the page moves its picture on the page's rendering only, so with the
362
+ * browser window minimized or off screen every read got the same frame for 250 ms: 4 different frames a second
363
+ * however fast the timer painted. A hidden one gives a fresh frame on each read. Chrome's own picture in picture
364
+ * leaves only a placeholder in the page too.
365
+ */
366
+ const hidePicture = () => {
367
+ const visibility = video.style.visibility
368
+ video.style.visibility = 'hidden'
369
+ restore = () => {
370
+ restore = undefined
371
+ video.style.visibility = visibility
372
+ }
373
+ }
374
+
261
375
  /**
262
376
  * Swap the composite in as the player's picture.
263
377
  *
@@ -285,14 +399,7 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
285
399
  }
286
400
 
287
401
  const enter = async () => {
288
- // Sized off the intrinsic dimensions, never the layout, so a resize cannot resize a canvas that a
289
- // MediaStream is already capturing.
290
- const width = Math.min(video.videoWidth || maxWidth, maxWidth)
291
- const height = Math.round(width * ((video.videoHeight || 9) / (video.videoWidth || 16)))
292
-
293
- const composite = document.createElement('canvas')
294
- composite.width = width
295
- composite.height = height
402
+ const composite = Object.assign(document.createElement('canvas'), compositeSize())
296
403
  // The alpha channel is unused but has to stay: with `{ alpha: false }` Chrome's captureStream
297
404
  // delivers the first frame and then nothing, with the track still "live" and no error anywhere.
298
405
  const context = composite.getContext('2d')
@@ -312,10 +419,9 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
312
419
  const mine: Session = { composite, context, stream: composite.captureStream(), mirror }
313
420
  session = mine
314
421
  mirror.srcObject = mine.stream
315
- ;(options.container ?? video.parentElement ?? document.body).appendChild(mirror)
422
+ ;(options.container ?? (mode === 'burn-in' ? video.parentElement : null) ?? document.body).appendChild(mirror)
316
423
 
317
- schedule()
318
- pausedRepaint = setInterval(() => { if (video.paused) paint() }, PAUSED_REPAINT_INTERVAL)
424
+ start()
319
425
  void mirror.play().catch(() => {})
320
426
 
321
427
  // requestPictureInPicture rejects while readyState is 0, and the wait is short enough that the
@@ -335,14 +441,7 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
335
441
  return
336
442
  }
337
443
 
338
- mirror.addEventListener('play', onMirrorPlay)
339
- mirror.addEventListener('pause', onMirrorPause)
340
- mirror.addEventListener('leavepictureinpicture', onLeave)
341
- video.addEventListener('play', onVideoPlay)
342
- video.addEventListener('pause', onVideoPause)
343
- video.addEventListener('seeked', onVideoSeeked)
344
- bindMediaSession(true)
345
- publishState()
444
+ listen(mirror)
346
445
 
347
446
  if (mode === 'burn-in') {
348
447
  // No window to open: the browser's own control does that, on the element now on screen.
@@ -352,6 +451,7 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
352
451
  }
353
452
 
354
453
  await mirror.requestPictureInPicture()
454
+ if (session === mine) hidePicture()
355
455
  }
356
456
 
357
457
  const toggle = async () => {
@@ -386,12 +486,26 @@ export const createPictureInPicture = (options: PictureInPictureOptions): Pictur
386
486
  }
387
487
  }
388
488
 
489
+ const taken = mode === 'window' ? takeOver() : undefined
490
+ if (taken) {
491
+ session = taken
492
+ // the last frame of the video before would otherwise stay up until this one has a frame
493
+ taken.context.fillRect(0, 0, taken.composite.width, taken.composite.height)
494
+ start()
495
+ listen(taken.mirror)
496
+ hidePicture()
497
+ }
498
+
389
499
  return {
390
500
  toggle,
391
501
  mode,
392
502
  destroy: () => {
393
503
  destroyed = true
394
- if (mode !== 'burn-in' && active()) void document.exitPictureInPicture().catch(() => {})
504
+ if (mode === 'window' && active()) {
505
+ const held = detach()!
506
+ restore?.()
507
+ return handOver(held)
508
+ }
395
509
  teardown()
396
510
  if (mode === 'burn-in') options.onBurnedInChange?.(false)
397
511
  },