@banou/media-player 0.10.54 → 0.10.55

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 (81) hide show
  1. package/dist/{ar-CWVutin3.js → ar-CSjwFY8l.js} +2 -0
  2. package/dist/{cs-CmwRGxyE.js → cs-Dk6IDwX9.js} +2 -0
  3. package/dist/{de-DLdKEf3t.js → de-G319tpSe.js} +2 -0
  4. package/dist/{el-Ckj-z6DX.js → el-CtRdEeUl.js} +2 -0
  5. package/dist/engine/index.d.ts +2 -0
  6. package/dist/engine/index.js +2 -2
  7. package/dist/engine/playback.d.ts +2 -0
  8. package/dist/engine/subtitle-convert.d.ts +8 -0
  9. package/dist/engine/subtitles.d.ts +2 -0
  10. package/dist/{engine-DZ6BX5XH.js → engine-tBJeFD6J.js} +285 -147
  11. package/dist/{es-419-zORhhU8D.js → es-419-BzuTB161.js} +2 -0
  12. package/dist/{fr-BtPmNkri.js → fr-BC0Ncjsm.js} +2 -0
  13. package/dist/{he-Bu79qEth.js → he-UutSGaSy.js} +2 -0
  14. package/dist/{hi-BsH3tSHa.js → hi-kNW0VH4d.js} +2 -0
  15. package/dist/{hu-BkYBW-YP.js → hu-UJBXN0lB.js} +2 -0
  16. package/dist/{id-nUaBCV4o.js → id-DYADKCdp.js} +2 -0
  17. package/dist/index.d.ts +4 -3
  18. package/dist/index.js +1188 -953
  19. package/dist/{it-CqPSHyFA.js → it-GodcqBoI.js} +2 -0
  20. package/dist/{ja-DTjvriHw.js → ja-r3FM4zNQ.js} +2 -0
  21. package/dist/{ko-dV8T7XOJ.js → ko-kNn9SZJT.js} +2 -0
  22. package/dist/labels.d.ts +2 -0
  23. package/dist/{ms-VZQ7BI0z.js → ms-B_95sgk7.js} +2 -0
  24. package/dist/{nl-Q6iDxbDz.js → nl-DUua8lM5.js} +2 -0
  25. package/dist/{pl-BN7bK74l.js → pl-DYN3cCvL.js} +2 -0
  26. package/dist/{pt-BR-CPFILeFW.js → pt-BR-CRH5nyyj.js} +2 -0
  27. package/dist/react/components/chrome.d.ts +3 -2
  28. package/dist/react/components/control-bar.d.ts +3 -2
  29. package/dist/react/hooks/use-playback.d.ts +1 -5
  30. package/dist/react/video-player.d.ts +29 -1
  31. package/dist/remote/index.d.ts +25 -2
  32. package/dist/remote/index.js +134 -68
  33. package/dist/remote/protocol.d.ts +22 -6
  34. package/dist/{ro-Bwcm-i3k.js → ro-lXdsKpft.js} +2 -0
  35. package/dist/{ru-D1FMz751.js → ru-Du_uJXdo.js} +2 -0
  36. package/dist/{sv-ci9K0Lkk.js → sv-CpEL6oGd.js} +2 -0
  37. package/dist/{th-DR-UBONQ.js → th-CQac_Jcd.js} +2 -0
  38. package/dist/{tr-BqhdfT22.js → tr-DLRAnIOh.js} +2 -0
  39. package/dist/{uk-8pkZqdni.js → uk-Cra5hJzT.js} +2 -0
  40. package/dist/{vi-3mKZ9G_M.js → vi-L2-IGJYQ.js} +2 -0
  41. package/dist/{zh-Hans-CDgigWKY.js → zh-Hans-Dp0UkPYn.js} +2 -0
  42. package/dist/{zh-Hant-3WSNI0ne.js → zh-Hant-CS16XV8X.js} +2 -0
  43. package/package.json +1 -1
  44. package/src/lib/engine/index.ts +3 -0
  45. package/src/lib/engine/playback.ts +4 -0
  46. package/src/lib/engine/subtitle-convert.ts +186 -0
  47. package/src/lib/engine/subtitles.ts +46 -7
  48. package/src/lib/index.tsx +7 -0
  49. package/src/lib/labels.ts +2 -0
  50. package/src/lib/locales/ar.json +2 -0
  51. package/src/lib/locales/cs.json +2 -0
  52. package/src/lib/locales/de.json +2 -0
  53. package/src/lib/locales/el.json +2 -0
  54. package/src/lib/locales/es-419.json +2 -0
  55. package/src/lib/locales/fr.json +2 -0
  56. package/src/lib/locales/he.json +2 -0
  57. package/src/lib/locales/hi.json +2 -0
  58. package/src/lib/locales/hu.json +2 -0
  59. package/src/lib/locales/id.json +2 -0
  60. package/src/lib/locales/it.json +2 -0
  61. package/src/lib/locales/ja.json +2 -0
  62. package/src/lib/locales/ko.json +2 -0
  63. package/src/lib/locales/ms.json +2 -0
  64. package/src/lib/locales/nl.json +2 -0
  65. package/src/lib/locales/pl.json +2 -0
  66. package/src/lib/locales/pt-BR.json +2 -0
  67. package/src/lib/locales/ro.json +2 -0
  68. package/src/lib/locales/ru.json +2 -0
  69. package/src/lib/locales/sv.json +2 -0
  70. package/src/lib/locales/th.json +2 -0
  71. package/src/lib/locales/tr.json +2 -0
  72. package/src/lib/locales/uk.json +2 -0
  73. package/src/lib/locales/vi.json +2 -0
  74. package/src/lib/locales/zh-Hans.json +2 -0
  75. package/src/lib/locales/zh-Hant.json +2 -0
  76. package/src/lib/react/components/chrome.tsx +4 -3
  77. package/src/lib/react/components/control-bar.tsx +51 -6
  78. package/src/lib/react/hooks/use-playback.ts +207 -15
  79. package/src/lib/react/video-player.tsx +116 -3
  80. package/src/lib/remote/index.ts +149 -12
  81. package/src/lib/remote/protocol.ts +32 -7
@@ -1,5 +1,13 @@
1
- import type { MediaChapter } from '../engine';
1
+ import type { ExternalSubtitleFormat, MediaChapter } from '../engine';
2
2
  import type { PlayerMedia, TimeRangesLike } from '../react/media';
3
+ /** External subtitle track description passed from an embedder to a framed player. */
4
+ export type RemoteExternalSubtitleTrack = {
5
+ id: string;
6
+ language: string;
7
+ label: string;
8
+ format: ExternalSubtitleFormat;
9
+ content?: string;
10
+ };
3
11
  /**
4
12
  * Everything readable about a player, as one plain object.
5
13
  *
@@ -44,9 +52,10 @@ export type PlayerSnapshot = {
44
52
  export declare const PLAYER_EVENTS: readonly ['loadstart', 'loadedmetadata', 'loadeddata', 'durationchange', 'timeupdate', 'play', 'playing', 'pause', 'seeking', 'seeked', 'progress', 'ratechange', 'volumechange', 'ended', 'waiting', 'stalled', 'suspend', 'canplay', 'canplaythrough', 'emptied', 'resize', 'error'];
45
53
  /**
46
54
  * The events a `<MediaPlayer expose>` raises beside its media's: its chapters changed, its viewer pressed
47
- * fullscreen while a mirror made with `fullscreen: true` has it, and its autoplay switch changed.
55
+ * fullscreen while a mirror made with `fullscreen: true` has it, its autoplay switch changed, the viewer
56
+ * clicked previous or next episode, or the player needs external subtitle content for a track id.
48
57
  */
49
- export declare const SERVED_EVENTS: readonly ['chapterschange', 'fullscreenrequest', 'autoplaynextchange'];
58
+ export declare const SERVED_EVENTS: readonly ['chapterschange', 'fullscreenrequest', 'autoplaynextchange', 'previousrequest', 'nextrequest', 'subtitleloadrequest'];
50
59
  export type PlayerEvent = typeof PLAYER_EVENTS[number] | typeof SERVED_EVENTS[number];
51
60
  /** The properties an embedder may set. Everything else is read-only on a media, here as there. */
52
61
  export declare const WRITABLE: readonly ['currentTime', 'volume', 'muted', 'playbackRate'];
@@ -65,10 +74,13 @@ export declare const PLAYER_CHANNEL = "banou-media-player";
65
74
  * framed.
66
75
  */
67
76
  export declare const DEFAULT_PLAYER_ID = "default";
68
- /** What rides the event port: the event's name and the state right after it. */
77
+ /** What rides the event port: the event's name, the state right after it, and any event payload. */
69
78
  export type PlayerUpdate = {
70
79
  event: PlayerEvent;
71
80
  snapshot: PlayerSnapshot;
81
+ detail?: {
82
+ trackId: string;
83
+ };
72
84
  };
73
85
  /**
74
86
  * What the player's document serves, one document at a time, addressed by player id. Internal: an
@@ -91,10 +103,14 @@ export type PlayerService = {
91
103
  }) => void;
92
104
  /**
93
105
  * `fullscreen` is the state shown by a player whose fullscreen a mirror has taken over, and is ignored otherwise.
94
- * `autoplayNext` is kept for the id while a mirror listens to it, and told to each player served under it.
106
+ * `autoplayNext`, `previousEpisode` and `nextEpisode` are kept for the id while a mirror listens to it, and told to each player served under it.
95
107
  */
96
- set: (id: string, name: Writable | 'fullscreen' | 'endingOffered' | 'autoplayNext', value: number | boolean) => void;
108
+ set: (id: string, name: Writable | 'fullscreen' | 'endingOffered' | 'autoplayNext' | 'previousEpisode' | 'nextEpisode', value: number | boolean | string | null) => void;
97
109
  call: (id: string, name: Callable) => Promise<void>;
110
+ /** Sets the remote external subtitle tracks shown by the player served under `id`. */
111
+ setExternalSubtitles: (id: string, tracks: RemoteExternalSubtitleTrack[]) => void;
112
+ /** Delivers loaded subtitle content (or an error when `content` is null) for a pending `subtitleloadrequest`. */
113
+ provideExternalSubtitle: (id: string, trackId: string, content: string | null, error?: string) => void;
98
114
  };
99
115
  /**
100
116
  * The events that bring a store attached to the mirror up to date from a snapshot alone, in the
@@ -14,6 +14,7 @@ var e = "Audio", t = "S-a copiat", n = "Copiați", r = "Dezactivate", i = "Dezac
14
14
  "Full screen (f)": "Ecran complet (f)",
15
15
  Mute: i,
16
16
  "Mute (m)": "Dezactivați sunetul (m)",
17
+ "Next episode": "Episodul următor",
17
18
  "Normalize volume": "Uniformizați volumul",
18
19
  "Now click your browser's pop out button": "Acum faceți clic pe butonul imagine în imagine al browserului",
19
20
  Pause: a,
@@ -24,6 +25,7 @@ var e = "Audio", t = "S-a copiat", n = "Copiați", r = "Dezactivate", i = "Dezac
24
25
  "Playback errors ({count})": "Erori de redare ({count})",
25
26
  "Playback failed": "Redarea a eșuat",
26
27
  "Playback speed": "Viteza de redare",
28
+ "Previous episode": "Episodul anterior",
27
29
  "Put the subtitles in the picture": "Integrați subtitrările în imagine",
28
30
  "Put the subtitles in the video": "Integrați subtitrările în videoclip",
29
31
  Quality: s,
@@ -14,6 +14,7 @@ var e = "Аудио", t = "Скопировано", n = "Копировать",
14
14
  "Full screen (f)": "Во весь экран (f)",
15
15
  Mute: i,
16
16
  "Mute (m)": "Выключить звук (m)",
17
+ "Next episode": "Следующая серия",
17
18
  "Normalize volume": "Выравнивать громкость",
18
19
  "Now click your browser's pop out button": "Теперь нажмите кнопку «картинка в картинке» в браузере",
19
20
  Pause: a,
@@ -24,6 +25,7 @@ var e = "Аудио", t = "Скопировано", n = "Копировать",
24
25
  "Playback errors ({count})": "Ошибки воспроизведения ({count})",
25
26
  "Playback failed": "Не удалось воспроизвести",
26
27
  "Playback speed": "Скорость",
28
+ "Previous episode": "Предыдущая серия",
27
29
  "Put the subtitles in the picture": "Встроить субтитры в изображение",
28
30
  "Put the subtitles in the video": "Встроить субтитры в видео",
29
31
  Quality: s,
@@ -14,6 +14,7 @@ var e = "Ljud", t = "Kopierat", n = "Kopiera", r = "Av", i = "Stäng av ljudet",
14
14
  "Full screen (f)": "Helskärm (f)",
15
15
  Mute: i,
16
16
  "Mute (m)": "Stäng av ljudet (m)",
17
+ "Next episode": "Nästa avsnitt",
17
18
  "Normalize volume": "Jämna ut volymen",
18
19
  "Now click your browser's pop out button": "Klicka nu på webbläsarens bild-i-bild-knapp",
19
20
  Pause: a,
@@ -24,6 +25,7 @@ var e = "Ljud", t = "Kopierat", n = "Kopiera", r = "Av", i = "Stäng av ljudet",
24
25
  "Playback errors ({count})": "Uppspelningsfel ({count})",
25
26
  "Playback failed": "Uppspelningen misslyckades",
26
27
  "Playback speed": "Hastighet",
28
+ "Previous episode": "Föregående avsnitt",
27
29
  "Put the subtitles in the picture": "Bränn in undertexterna i bilden",
28
30
  "Put the subtitles in the video": "Bränn in undertexterna i videon",
29
31
  Quality: s,
@@ -14,6 +14,7 @@ var e = "เสียง", t = "คัดลอกแล้ว", n = "คัด
14
14
  "Full screen (f)": "เต็มหน้าจอ (f)",
15
15
  Mute: i,
16
16
  "Mute (m)": "ปิดเสียง (m)",
17
+ "Next episode": "ตอนถัดไป",
17
18
  "Normalize volume": "ปรับระดับเสียงให้เท่ากัน",
18
19
  "Now click your browser's pop out button": "ตอนนี้ให้คลิกปุ่มภาพซ้อนภาพของเบราว์เซอร์",
19
20
  Pause: a,
@@ -24,6 +25,7 @@ var e = "เสียง", t = "คัดลอกแล้ว", n = "คัด
24
25
  "Playback errors ({count})": "ข้อผิดพลาดในการเล่น ({count})",
25
26
  "Playback failed": "เล่นไม่สำเร็จ",
26
27
  "Playback speed": "ความเร็วในการเล่น",
28
+ "Previous episode": "ตอนก่อนหน้า",
27
29
  "Put the subtitles in the picture": "ฝังคำบรรยายลงในภาพ",
28
30
  "Put the subtitles in the video": "ฝังคำบรรยายลงในวิดีโอ",
29
31
  Quality: s,
@@ -14,6 +14,7 @@ var e = "Ses", t = "Kopyalandı", n = "Kopyala", r = "Kapalı", i = "Sesi kapat"
14
14
  "Full screen (f)": "Tam ekran (f)",
15
15
  Mute: i,
16
16
  "Mute (m)": "Sesi kapat (m)",
17
+ "Next episode": "Sonraki bölüm",
17
18
  "Normalize volume": "Sesi dengele",
18
19
  "Now click your browser's pop out button": "Şimdi tarayıcınızın pencere içinde pencere düğmesine tıklayın",
19
20
  Pause: a,
@@ -24,6 +25,7 @@ var e = "Ses", t = "Kopyalandı", n = "Kopyala", r = "Kapalı", i = "Sesi kapat"
24
25
  "Playback errors ({count})": "Oynatma hataları ({count})",
25
26
  "Playback failed": "Oynatılamadı",
26
27
  "Playback speed": "Oynatma hızı",
28
+ "Previous episode": "Önceki bölüm",
27
29
  "Put the subtitles in the picture": "Altyazıları görüntüye göm",
28
30
  "Put the subtitles in the video": "Altyazıları videoya göm",
29
31
  Quality: s,
@@ -14,6 +14,7 @@ var e = "Аудіо", t = "Скопійовано", n = "Копіювати", r
14
14
  "Full screen (f)": "На весь екран (f)",
15
15
  Mute: i,
16
16
  "Mute (m)": "Вимкнути звук (m)",
17
+ "Next episode": "Наступна серія",
17
18
  "Normalize volume": "Вирівнювати гучність",
18
19
  "Now click your browser's pop out button": "Тепер натисніть кнопку «картинка в картинці» у браузері",
19
20
  Pause: a,
@@ -24,6 +25,7 @@ var e = "Аудіо", t = "Скопійовано", n = "Копіювати", r
24
25
  "Playback errors ({count})": "Помилки відтворення ({count})",
25
26
  "Playback failed": "Не вдалося відтворити",
26
27
  "Playback speed": "Швидкість",
28
+ "Previous episode": "Попередня серія",
27
29
  "Put the subtitles in the picture": "Вбудувати субтитри в зображення",
28
30
  "Put the subtitles in the video": "Вбудувати субтитри у відео",
29
31
  Quality: s,
@@ -14,6 +14,7 @@ var e = "Âm thanh", t = "Đã sao chép", n = "Sao chép", r = "Tắt", i = "T
14
14
  "Full screen (f)": "Toàn màn hình (f)",
15
15
  Mute: i,
16
16
  "Mute (m)": "Tắt tiếng (m)",
17
+ "Next episode": "Tập tiếp theo",
17
18
  "Normalize volume": "Cân bằng âm lượng",
18
19
  "Now click your browser's pop out button": "Bây giờ hãy nhấp vào nút hình trong hình của trình duyệt",
19
20
  Pause: a,
@@ -24,6 +25,7 @@ var e = "Âm thanh", t = "Đã sao chép", n = "Sao chép", r = "Tắt", i = "T
24
25
  "Playback errors ({count})": "Lỗi phát ({count})",
25
26
  "Playback failed": "Không phát được",
26
27
  "Playback speed": "Tốc độ phát",
28
+ "Previous episode": "Tập trước",
27
29
  "Put the subtitles in the picture": "Gắn phụ đề vào hình",
28
30
  "Put the subtitles in the video": "Gắn phụ đề vào video",
29
31
  Quality: s,
@@ -14,6 +14,7 @@ var e = "音频", t = "已复制", n = "复制", r = "关闭", i = "静音", a =
14
14
  "Full screen (f)": "全屏 (f)",
15
15
  Mute: i,
16
16
  "Mute (m)": "静音 (m)",
17
+ "Next episode": "下一集",
17
18
  "Normalize volume": "音量均衡",
18
19
  "Now click your browser's pop out button": "现在点击浏览器的画中画按钮",
19
20
  Pause: a,
@@ -24,6 +25,7 @@ var e = "音频", t = "已复制", n = "复制", r = "关闭", i = "静音", a =
24
25
  "Playback errors ({count})": "播放错误 ({count})",
25
26
  "Playback failed": "播放失败",
26
27
  "Playback speed": "播放速度",
28
+ "Previous episode": "上一集",
27
29
  "Put the subtitles in the picture": "将字幕嵌入画面",
28
30
  "Put the subtitles in the video": "将字幕嵌入视频",
29
31
  Quality: s,
@@ -14,6 +14,7 @@ var e = "音訊", t = "已複製", n = "複製", r = "關閉", i = "靜音", a =
14
14
  "Full screen (f)": "全螢幕 (f)",
15
15
  Mute: i,
16
16
  "Mute (m)": "靜音 (m)",
17
+ "Next episode": "下一集",
17
18
  "Normalize volume": "音量平衡",
18
19
  "Now click your browser's pop out button": "現在請點選瀏覽器的子母畫面按鈕",
19
20
  Pause: a,
@@ -24,6 +25,7 @@ var e = "音訊", t = "已複製", n = "複製", r = "關閉", i = "靜音", a =
24
25
  "Playback errors ({count})": "播放錯誤 ({count})",
25
26
  "Playback failed": "播放失敗",
26
27
  "Playback speed": "播放速度",
28
+ "Previous episode": "上一集",
27
29
  "Put the subtitles in the picture": "將字幕嵌入畫面",
28
30
  "Put the subtitles in the video": "將字幕嵌入影片",
29
31
  Quality: s,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banou/media-player",
3
- "version": "0.10.54",
3
+ "version": "0.10.55",
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",
@@ -4,6 +4,9 @@ export type { PlaybackOptions, PlaybackController, PlaybackOutput, MediaIndex, M
4
4
  export { createSubtitleRenderer, SUBTITLES_OFF } from './subtitles'
5
5
  export type { SubtitleRenderer, SubtitleRendererOptions, SubtitleStream } from './subtitles'
6
6
 
7
+ export { toAssSubtitles } from './subtitle-convert'
8
+ export type { ExternalSubtitleFormat } from './subtitle-convert'
9
+
7
10
  export { createThumbnailGenerator } from './thumbnails'
8
11
  export type { ThumbnailGenerator, ThumbnailGeneratorOptions, ThumbnailImage } from './thumbnails'
9
12
 
@@ -89,6 +89,8 @@ export type PlaybackController = {
89
89
  /** The element this pipeline drives, so a caller can read what actually got buffered. */
90
90
  videoElement: HTMLVideoElement
91
91
  selectSubtitleStream: (streamIndex: number | undefined) => void
92
+ setExternalSubtitleTrack: (assContent: string) => void
93
+ clearExternalSubtitleTrack: () => void
92
94
  /** Keyframe index of the input, which is what maps a downloaded byte range onto the timeline. */
93
95
  indexes: MediaIndex[]
94
96
  /** Named spans the container declared, empty when it declared none. */
@@ -876,6 +878,8 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
876
878
  prepareSeek,
877
879
  videoElement,
878
880
  selectSubtitleStream: (streamIndex: number | undefined) => subtitles.selectStream(streamIndex),
881
+ setExternalSubtitleTrack: (assContent: string) => subtitles.setExternalTrack(assContent),
882
+ clearExternalSubtitleTrack: () => subtitles.clearExternalTrack(),
879
883
  indexes: metadata.indexes ?? [],
880
884
  chapters: metadata.chapters ?? [],
881
885
  duration: metadata.info.input.duration,
@@ -0,0 +1,186 @@
1
+ /** Format of an external subtitle track loaded outside the media container. */
2
+ export type ExternalSubtitleFormat = 'srt' | 'vtt' | 'ass'
3
+
4
+ const CSS_COLORS: Readonly<Record<string, string>> = {
5
+ white: 'ffffff',
6
+ black: '000000',
7
+ red: 'ff0000',
8
+ green: '008000',
9
+ lime: '00ff00',
10
+ blue: '0000ff',
11
+ yellow: 'ffff00',
12
+ cyan: '00ffff',
13
+ aqua: '00ffff',
14
+ magenta: 'ff00ff',
15
+ fuchsia: 'ff00ff',
16
+ orange: 'ffa500',
17
+ gray: '808080',
18
+ grey: '808080',
19
+ silver: 'c0c0c0',
20
+ maroon: '800000',
21
+ navy: '000080',
22
+ olive: '808000',
23
+ purple: '800080',
24
+ teal: '008080',
25
+ }
26
+
27
+ const assColor = (raw: string): string | undefined => {
28
+ const value = raw.trim().toLowerCase()
29
+ let hex: string | undefined
30
+ if (/^#[0-9a-f]{6}$/.test(value)) hex = value.slice(1)
31
+ else if (/^#[0-9a-f]{3}$/.test(value)) hex = value.slice(1).split('').map((c) => c + c).join('')
32
+ else hex = CSS_COLORS[value]
33
+ if (!hex) return undefined
34
+ const r = hex.slice(0, 2).toUpperCase()
35
+ const g = hex.slice(2, 4).toUpperCase()
36
+ const b = hex.slice(4, 6).toUpperCase()
37
+ return `&H${b}${g}${r}&`
38
+ }
39
+
40
+ const NAMED_ENTITIES: Readonly<Record<string, string>> = {
41
+ amp: '&',
42
+ lt: '<',
43
+ gt: '>',
44
+ quot: '"',
45
+ apos: "'",
46
+ nbsp: ' ',
47
+ }
48
+
49
+ const decodeEntities = (text: string) =>
50
+ text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (match, entity: string) => {
51
+ const lower = entity.toLowerCase()
52
+ if (lower in NAMED_ENTITIES) return NAMED_ENTITIES[lower]!
53
+ if (lower.startsWith('#x')) {
54
+ const code = Number.parseInt(lower.slice(2), 16)
55
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match
56
+ }
57
+ if (lower.startsWith('#')) {
58
+ const code = Number.parseInt(lower.slice(1), 10)
59
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match
60
+ }
61
+ return match
62
+ })
63
+
64
+ const parseTimestamp = (raw: string): number | null => {
65
+ const match = /^(?:(\d+):)?(\d{1,2}):(\d{2})(?:[.,](\d{1,3}))?$/.exec(raw.trim())
66
+ if (!match) return null
67
+ const hours = match[1] !== undefined ? Number(match[1]) : 0
68
+ const minutes = Number(match[2])
69
+ const seconds = Number(match[3])
70
+ const ms = Number((match[4] ?? '0').padEnd(3, '0'))
71
+ if (minutes > 59 || seconds > 59) return null
72
+ return ((hours * 60 + minutes) * 60 + seconds) * 1000 + ms
73
+ }
74
+
75
+ const formatAssTime = (ms: number) => {
76
+ const totalCs = Math.max(0, Math.round(ms / 10))
77
+ const cs = totalCs % 100
78
+ const totalSec = Math.floor(totalCs / 100)
79
+ const sec = totalSec % 60
80
+ const totalMin = Math.floor(totalSec / 60)
81
+ const min = totalMin % 60
82
+ const hours = Math.floor(totalMin / 60)
83
+ const pad = (value: number) => String(value).padStart(2, '0')
84
+ return `${hours}:${pad(min)}:${pad(sec)}.${pad(cs)}`
85
+ }
86
+
87
+ const parseTimingLine = (line: string): { start: number, end: number } | null => {
88
+ const match = /^(\S+)\s*-->\s*(\S+)/.exec(line.trim())
89
+ if (!match) return null
90
+ const start = parseTimestamp(match[1]!)
91
+ const end = parseTimestamp(match[2]!)
92
+ if (start === null || end === null || end <= start) return null
93
+ return { start, end }
94
+ }
95
+
96
+ const attrValue = (attrs: string, name: string): string | undefined => {
97
+ const pattern = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i')
98
+ const match = pattern.exec(attrs)
99
+ return match?.[1] ?? match?.[2] ?? match?.[3]
100
+ }
101
+
102
+ const convertCueText = (lines: string[]): string => {
103
+ const joined = lines.join('\n').replace(/<br\s*\/?>/gi, '\n')
104
+ const fontStack: { color: boolean, face: boolean }[] = []
105
+
106
+ // Convert formatting tags before stripping unknown tags and before entity decoding so escaped
107
+ // angle brackets like &lt;i&gt; stay literal text.
108
+ const tagged = joined.replace(/<\/?([a-zA-Z][a-zA-Z0-9.-]*)(?:\s([^>]*))?>|<\d{1,2}:\d{2}(?::\d{2})?[.,]\d{1,3}>/g, (raw, tagName?: string, attrs = '') => {
109
+ if (!tagName) return ''
110
+ const closing = raw.startsWith('</')
111
+ const name = tagName.split('.')[0]!.toLowerCase()
112
+ if (name === 'i') return closing ? '{\\i0}' : '{\\i1}'
113
+ if (name === 'b') return closing ? '{\\b0}' : '{\\b1}'
114
+ if (name === 'u') return closing ? '{\\u0}' : '{\\u1}'
115
+ if (name === 'font') {
116
+ if (closing) {
117
+ const entry = fontStack.pop()
118
+ if (!entry) return ''
119
+ const resets = `${entry.color ? '\\c' : ''}${entry.face ? '\\fn' : ''}`
120
+ return resets ? `{${resets}}` : ''
121
+ }
122
+ const rawColor = attrValue(attrs, 'color')
123
+ const color = rawColor ? assColor(rawColor) : undefined
124
+ const face = attrValue(attrs, 'face')?.replace(/[{}]/g, '').trim() || undefined
125
+ fontStack.push({ color: !!color, face: !!face })
126
+ const tags = `${color ? `\\c${color}` : ''}${face ? `\\fn${face}` : ''}`
127
+ return tags ? `{${tags}}` : ''
128
+ }
129
+ return ''
130
+ })
131
+
132
+ return decodeEntities(tagged).replace(/\n/g, '\\N').trim()
133
+ }
134
+
135
+ const assHeader = (title?: string) => {
136
+ const cleanTitle = (title ?? 'External').replace(/[\r\n]+/g, ' ').trim() || 'External'
137
+ return [
138
+ '[Script Info]',
139
+ `Title: ${cleanTitle}`,
140
+ 'ScriptType: v4.00+',
141
+ 'WrapStyle: 0',
142
+ 'ScaledBorderAndShadow: yes',
143
+ 'PlayResX: 1920',
144
+ 'PlayResY: 1080',
145
+ '',
146
+ '[V4+ Styles]',
147
+ 'Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding',
148
+ 'Style: Default,Liberation Sans,64,&H00FFFFFF,&H000000FF,&H00000000,&H80000000,0,0,0,0,100,100,0,0,1,3,1.5,2,60,60,48,1',
149
+ '',
150
+ '[Events]',
151
+ 'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
152
+ ].join('\n')
153
+ }
154
+
155
+ /**
156
+ * Converts SubRip (`.srt`) or WebVTT (`.vtt`) text into a libass ASS script targeting a 1920x1080
157
+ * play resolution with `Liberation Sans` so `defaultFontUrl` and `cjkFontUrl` draw Latin and CJK
158
+ * glyphs without system font discovery. `.ass` inputs pass through unchanged aside from BOM removal.
159
+ */
160
+ export const toAssSubtitles = (content: string, format: ExternalSubtitleFormat, title?: string): string => {
161
+ const clean = content.startsWith('\uFEFF') ? content.slice(1) : content
162
+ if (format === 'ass') return clean
163
+
164
+ const normalized = clean.replace(/\r\n?/g, '\n').trim()
165
+ const blocks = normalized ? normalized.split(/\n[ \t]*\n+/) : []
166
+ const dialogues: string[] = []
167
+
168
+ for (let index = 0; index < blocks.length; index++) {
169
+ const block = blocks[index]!.trim()
170
+ if (!block) continue
171
+ if (format === 'vtt') {
172
+ if (index === 0 && /^WEBVTT(?:[ \t\n]|$)/.test(block)) continue
173
+ if (/^(?:NOTE|STYLE|REGION)(?:[ \t\n]|$)/.test(block)) continue
174
+ }
175
+ const lines = block.split('\n')
176
+ const timingIndex = lines.findIndex((line) => line.includes('-->'))
177
+ if (timingIndex === -1) continue
178
+ const timing = parseTimingLine(lines[timingIndex]!)
179
+ if (!timing) continue
180
+ const text = convertCueText(lines.slice(timingIndex + 1))
181
+ if (!text) continue
182
+ dialogues.push(`Dialogue: 0,${formatAssTime(timing.start)},${formatAssTime(timing.end)},Default,,0,0,0,,${text}`)
183
+ }
184
+
185
+ return dialogues.length ? `${assHeader(title)}\n${dialogues.join('\n')}\n` : `${assHeader(title)}\n`
186
+ }
@@ -192,6 +192,7 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
192
192
  const streams: SubtitleStream[] = []
193
193
  const dialogues = new Map<number, Map<string, SubtitleDialoguePart>>()
194
194
  let selected: number | undefined
195
+ let externalAss: string | null = null
195
196
  let onStreams = options.onStreams
196
197
  /**
197
198
  * Terminal, unlike a null `jassub`.
@@ -299,14 +300,14 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
299
300
  const REPAINT_ON = ['loadedmetadata', 'seeked', 'pause'] as const
300
301
  const onRepaintEvent = () => repaint()
301
302
 
302
- const bootJassub = (header: SubtitleHeaderPart) => {
303
+ const bootJassub = (subContent: string) => {
303
304
  const canvas = document.createElement('canvas')
304
305
  canvas.dataset.pending = ''
305
306
  container.append(canvas)
306
307
  try {
307
308
  jassub = new JASSUB({
308
309
  canvas,
309
- subContent: header.content,
310
+ subContent,
310
311
  workerUrl,
311
312
  modernWasmUrl: wasmUrl,
312
313
  modernWasmWorkerUrl: wasmWorkerUrl,
@@ -357,8 +358,8 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
357
358
  repaint()
358
359
  }
359
360
 
360
- const loadCjkFontFor = (events: ASSEvent[]) => {
361
- if (!cjkFontUrl || cjkFontRequested || !events.some((event) => CJK_TEXT.test(event.Text))) return
361
+ const requestCjkFont = () => {
362
+ if (!cjkFontUrl || cjkFontRequested) return
362
363
  cjkFontRequested = true
363
364
  onRenderer(async (renderer) => {
364
365
  await defaultFontLoaded
@@ -367,6 +368,16 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
367
368
  })
368
369
  }
369
370
 
371
+ const loadCjkFontFor = (events: ASSEvent[]) => {
372
+ if (!cjkFontUrl || cjkFontRequested || !events.some((event) => CJK_TEXT.test(event.Text))) return
373
+ requestCjkFont()
374
+ }
375
+
376
+ const loadCjkFontForText = (text: string) => {
377
+ if (!cjkFontUrl || cjkFontRequested || !CJK_TEXT.test(text)) return
378
+ requestCjkFont()
379
+ }
380
+
370
381
  const pushAttachments = (incoming: Attachment[]) => {
371
382
  attachments = [...attachments, ...incoming.map((a) => [a.filename, new Uint8Array(a.data)] as [string, Uint8Array])]
372
383
  }
@@ -381,8 +392,8 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
381
392
  headers.set(fragment.streamIndex, header)
382
393
  streams.push({ streamIndex: fragment.streamIndex, title: fragment.title, language: fragment.language })
383
394
  onStreams?.([...streams])
384
- if (selected === undefined) selected = fragment.streamIndex
385
- if (!jassub && !destroyed) bootJassub(header)
395
+ if (selected === undefined && externalAss === null) selected = fragment.streamIndex
396
+ if (!jassub && !destroyed) bootJassub(header.content)
386
397
  } else {
387
398
  const header = headers.get(fragment.streamIndex)
388
399
  if (!header) continue
@@ -408,8 +419,11 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
408
419
 
409
420
  const selectStream = (streamIndex: number | undefined) => {
410
421
  const next = streamIndex ?? SUBTITLES_OFF
411
- if (next === selected || !jassub) return
422
+ const wasExternal = externalAss !== null
423
+ if (!wasExternal && next === selected) return
424
+ externalAss = null
412
425
  selected = next
426
+ if (!jassub) return
413
427
  const header = headers.get(next)
414
428
  const events = [...dialogues.get(next)?.values() ?? []].map((part) => part.assEvent)
415
429
  onRenderer((renderer) => {
@@ -423,10 +437,35 @@ export const createSubtitleRenderer = (options: SubtitleRendererOptions) => {
423
437
  repaint()
424
438
  }
425
439
 
440
+ const setExternalTrack = (assContent: string) => {
441
+ if (destroyed || externalAss === assContent) return
442
+ externalAss = assContent
443
+ selected = SUBTITLES_OFF
444
+ if (!jassub) {
445
+ bootJassub(assContent)
446
+ loadCjkFontForText(assContent)
447
+ return
448
+ }
449
+ onRenderer((renderer) => Promise.all([renderer.freeTrack(), renderer.setTrack(assContent)]))
450
+ loadCjkFontForText(assContent)
451
+ repaint()
452
+ }
453
+
454
+ const clearExternalTrack = () => {
455
+ if (externalAss === null) return
456
+ externalAss = null
457
+ selected = SUBTITLES_OFF
458
+ if (!jassub) return
459
+ onRenderer((renderer) => renderer.removeAllEvents())
460
+ repaint()
461
+ }
462
+
426
463
  return {
427
464
  pushAttachments,
428
465
  pushFragments,
429
466
  selectStream,
467
+ setExternalTrack,
468
+ clearExternalTrack,
430
469
  getStreams: () => [...streams],
431
470
  getSelectedStream: () => selected,
432
471
  setOnStreams: (cb: (streams: SubtitleStream[]) => void) => { onStreams = cb },
package/src/lib/index.tsx CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  export { MediaPlayer, default } from './react/video-player'
4
4
  export type {
5
+ EpisodeNavigation,
6
+ EpisodeStep,
7
+ ExternalSubtitleTrack,
5
8
  HostFullscreen,
6
9
  MediaPlayerOptions,
7
10
  MediaPlayerLocalOptions,
@@ -40,6 +43,7 @@ export type { RemuxerInput } from './utils/source'
40
43
  // The engine is also published on its own subpath for consumers that want the pipeline with no React.
41
44
  export type {
42
45
  AudioStream,
46
+ ExternalSubtitleFormat,
43
47
  MediaChapter,
44
48
  MediaIndex,
45
49
  PictureInPictureController,
@@ -55,4 +59,7 @@ export {
55
59
  createSubtitleRenderer,
56
60
  createPictureInPicture,
57
61
  SUBTITLES_OFF,
62
+ toAssSubtitles,
58
63
  } from './engine'
64
+
65
+ export type { RemoteExternalSubtitleTrack } from './remote'
package/src/lib/labels.ts CHANGED
@@ -34,6 +34,8 @@ export const LABELS = {
34
34
  speed: '{rate}x',
35
35
  normalizeVolume: 'Normalize volume',
36
36
  autoplayNext: 'Autoplay next episode',
37
+ previousEpisode: 'Previous episode',
38
+ nextEpisode: 'Next episode',
37
39
  unavailable: 'Unavailable',
38
40
  switchFailed: 'Could not switch. Try again.',
39
41
  track: 'Track {number}',
@@ -13,6 +13,7 @@
13
13
  "Full screen (f)": "ملء الشاشة (f)",
14
14
  "Mute": "كتم الصوت",
15
15
  "Mute (m)": "كتم الصوت (m)",
16
+ "Next episode": "الحلقة التالية",
16
17
  "Normalize volume": "موازنة مستوى الصوت",
17
18
  "Now click your browser's pop out button": "انقر الآن على زر النافذة المنبثقة في متصفحك",
18
19
  "Pause": "إيقاف مؤقت",
@@ -23,6 +24,7 @@
23
24
  "Playback errors ({count})": "أخطاء التشغيل ({count})",
24
25
  "Playback failed": "فشل التشغيل",
25
26
  "Playback speed": "سرعة التشغيل",
27
+ "Previous episode": "الحلقة السابقة",
26
28
  "Put the subtitles in the picture": "دمج الترجمة في الصورة",
27
29
  "Put the subtitles in the video": "دمج الترجمة في الفيديو",
28
30
  "Quality": "الجودة",
@@ -13,6 +13,7 @@
13
13
  "Full screen (f)": "Celá obrazovka (f)",
14
14
  "Mute": "Ztlumit",
15
15
  "Mute (m)": "Ztlumit (m)",
16
+ "Next episode": "Další epizoda",
16
17
  "Normalize volume": "Vyrovnávat hlasitost",
17
18
  "Now click your browser's pop out button": "Teď klikněte na tlačítko obrazu v obraze ve svém prohlížeči",
18
19
  "Pause": "Pozastavit",
@@ -23,6 +24,7 @@
23
24
  "Playback errors ({count})": "Chyby přehrávání ({count})",
24
25
  "Playback failed": "Přehrávání se nezdařilo",
25
26
  "Playback speed": "Rychlost přehrávání",
27
+ "Previous episode": "Předchozí epizoda",
26
28
  "Put the subtitles in the picture": "Vložit titulky do obrazu",
27
29
  "Put the subtitles in the video": "Vložit titulky do videa",
28
30
  "Quality": "Kvalita",
@@ -13,6 +13,7 @@
13
13
  "Full screen (f)": "Vollbild (f)",
14
14
  "Mute": "Stummschalten",
15
15
  "Mute (m)": "Stummschalten (m)",
16
+ "Next episode": "Nächste Folge",
16
17
  "Normalize volume": "Lautstärke angleichen",
17
18
  "Now click your browser's pop out button": "Klicke jetzt auf die Bild-im-Bild-Schaltfläche deines Browsers",
18
19
  "Pause": "Pause",
@@ -23,6 +24,7 @@
23
24
  "Playback errors ({count})": "Wiedergabefehler ({count})",
24
25
  "Playback failed": "Wiedergabe fehlgeschlagen",
25
26
  "Playback speed": "Geschwindigkeit",
27
+ "Previous episode": "Vorherige Folge",
26
28
  "Put the subtitles in the picture": "Untertitel ins Bild einbetten",
27
29
  "Put the subtitles in the video": "Untertitel ins Video einbetten",
28
30
  "Quality": "Qualität",
@@ -13,6 +13,7 @@
13
13
  "Full screen (f)": "Πλήρης οθόνη (f)",
14
14
  "Mute": "Σίγαση",
15
15
  "Mute (m)": "Σίγαση (m)",
16
+ "Next episode": "Επόμενο επεισόδιο",
16
17
  "Normalize volume": "Εξισορρόπηση έντασης",
17
18
  "Now click your browser's pop out button": "Τώρα πατήστε το κουμπί εικόνας σε εικόνα του προγράμματος περιήγησης",
18
19
  "Pause": "Παύση",
@@ -23,6 +24,7 @@
23
24
  "Playback errors ({count})": "Σφάλματα αναπαραγωγής ({count})",
24
25
  "Playback failed": "Η αναπαραγωγή απέτυχε",
25
26
  "Playback speed": "Ταχύτητα",
27
+ "Previous episode": "Προηγούμενο επεισόδιο",
26
28
  "Put the subtitles in the picture": "Ενσωμάτωση υποτίτλων στην εικόνα",
27
29
  "Put the subtitles in the video": "Ενσωμάτωση υποτίτλων στο βίντεο",
28
30
  "Quality": "Ποιότητα",