embedded.html 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998
  1. <!DOCTYPE html>
  2. <meta name="apple-mobile-web-app-capable" content="yes" />
  3. <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"/>
  4. <html>
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="theme-color" content="#000000">
  8. <script src="../script/jquery.min.js"></script>
  9. <script src="../script/ao_module.js"></script>
  10. <script src="backend/common.js"></script>
  11. <!-- ASS/SSA subtitle parser + renderer (see script/ass.js) -->
  12. <script src="script/ass.js"></script>
  13. <style>
  14. *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  15. :root {
  16. --accent: #0a84ff;
  17. --surface: #1c1c1e;
  18. --surface2: #2c2c2e;
  19. --text: #f5f5f7;
  20. --text-sub: #98989d;
  21. --transition: 0.2s ease;
  22. --radius: 0.4em;
  23. }
  24. html, body { width: 100%; height: 100%; background: #000; overflow: hidden; }
  25. #player-wrap {
  26. position: relative;
  27. width: 100%; height: 100%;
  28. display: flex; align-items: center; justify-content: center;
  29. background: #000;
  30. }
  31. #main-video {
  32. width: 100%; height: 100%;
  33. object-fit: contain; display: block; background: #000;
  34. }
  35. /* ── Controls overlay ──────────────────────────────────────────────── */
  36. #video-controls {
  37. position: absolute;
  38. bottom: 0; left: 0; right: 0;
  39. background: linear-gradient(transparent, rgba(0,0,0,0.85) 100%);
  40. padding: 40px 14px 12px;
  41. transition: opacity 0.3s;
  42. }
  43. #video-controls.hidden { opacity: 0; pointer-events: none; }
  44. #player-wrap:has(#video-controls.hidden) { cursor: none; }
  45. #progress-wrap {
  46. position: relative;
  47. height: 4px; background: rgba(255,255,255,0.25);
  48. border-radius: var(--radius); cursor: pointer; margin-bottom: 12px;
  49. }
  50. #progress-wrap:hover { height: 6px; }
  51. #progress-wrap::before {
  52. content: ''; position: absolute;
  53. top: -16px; left: 0; right: 0; height: 16px;
  54. }
  55. #progress-bar { height: 100%; border-radius: var(--radius); background: var(--accent); pointer-events: none; }
  56. #progress-thumb {
  57. position: absolute; top: 50%; transform: translateY(-50%);
  58. width: 14px; height: 14px;
  59. background: #fff; border-radius: 50%; pointer-events: none; display: none;
  60. }
  61. #progress-wrap:hover #progress-thumb { display: block; }
  62. #controls-row { display: flex; align-items: center; gap: 10px; }
  63. .ctrl-btn {
  64. background: none; border: none; cursor: pointer;
  65. color: #fff; padding: 4px; line-height: 1;
  66. transition: opacity var(--transition); outline: none;
  67. display: flex; align-items: center; justify-content: center;
  68. flex-shrink: 0;
  69. }
  70. .ctrl-btn:hover { opacity: 0.7; }
  71. .ctrl-btn img { width: 24px; height: 24px; display: block; }
  72. #volume-wrap { display: flex; align-items: center; gap: 8px; }
  73. #volume-slider {
  74. -webkit-appearance: none;
  75. width: 80px; height: 4px;
  76. background: rgba(255,255,255,0.3); border-radius: 4px; outline: none; cursor: pointer;
  77. }
  78. #volume-slider::-webkit-slider-thumb {
  79. -webkit-appearance: none;
  80. width: 12px; height: 12px; background: #fff; border-radius: 50%;
  81. }
  82. /* Portrait phones/tablets drive playback volume with the hardware keys,
  83. so the in-page slider only eats toolbar width. Users who want it back
  84. can force it on from the settings popup ("Volume bar → Always show"). */
  85. @media (max-width: 899px) and (orientation: portrait) {
  86. #volume-slider { display: none; }
  87. }
  88. body.always-show-volume #volume-slider { display: block; }
  89. #time-display {
  90. font-size: 13px; color: rgba(255,255,255,0.8);
  91. font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  92. margin-left: 4px; white-space: nowrap;
  93. }
  94. #spacer { flex: 1; }
  95. /* ─── ASS subtitle overlay ───────────────────────────────────────────────────── */
  96. /* Sized in JS to the video's displayed rect so script coordinates land correctly
  97. regardless of letterboxing. Children are absolutely positioned by the renderer. */
  98. #ass-overlay {
  99. display: none;
  100. position: absolute;
  101. left: 0; top: 0; width: 0; height: 0;
  102. pointer-events: none;
  103. overflow: hidden;
  104. /* No z-index on purpose: subtitles sit directly after <video> in the DOM,
  105. so they paint above the (unpositioned) video but below every later
  106. positioned sibling — scrub preview, controls, menus and modals all stay
  107. on top of the text instead of being covered by it. */
  108. /* libass spaces lines by the font's own ascent+descent with no extra
  109. leading; 1.2 would push stacked dual-language lines apart and break
  110. the MarginV offsets releases use to sit them one above the other. */
  111. line-height: 1.05;
  112. }
  113. #ass-overlay.active { display: block; }
  114. /* ── Scrub-bar hover preview ───────────────────────────────────────── */
  115. #scrub-preview {
  116. display: none;
  117. position: absolute;
  118. bottom: 100%;
  119. margin-bottom: 12px;
  120. transform: translateX(-50%);
  121. pointer-events: none;
  122. z-index: 8;
  123. flex-direction: column;
  124. align-items: center;
  125. gap: 6px;
  126. }
  127. #scrub-preview.active { display: flex; }
  128. #scrub-preview-thumb {
  129. display: none;
  130. border-radius: 8px;
  131. background-color: #000;
  132. background-repeat: no-repeat;
  133. box-shadow: 0 4px 18px rgba(0,0,0,0.8), 0 0 0 2px rgba(255,255,255,0.14);
  134. }
  135. #scrub-preview-thumb.ready { display: block; }
  136. #scrub-preview-time {
  137. background: rgba(0,0,0,0.82);
  138. border-radius: 6px;
  139. padding: 3px 9px;
  140. font-size: 12px; font-weight: 600;
  141. color: #fff; white-space: nowrap;
  142. font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  143. font-variant-numeric: tabular-nums;
  144. }
  145. /* ── Transcode-seek freeze frame ───────────────────────────────────── */
  146. /* Deliberately no z-index: both sit immediately after <video> in the DOM,
  147. so they paint above the (unpositioned) video but below every later
  148. positioned sibling — controls and menus stay on top and clickable. */
  149. #seek-freeze {
  150. display: none;
  151. position: absolute; inset: 0;
  152. width: 100%; height: 100%;
  153. object-fit: contain;
  154. background: #000;
  155. pointer-events: none;
  156. }
  157. #seek-spinner {
  158. display: none;
  159. position: absolute; inset: 0;
  160. align-items: center; justify-content: center;
  161. pointer-events: none;
  162. }
  163. #seek-spinner.active { display: flex; }
  164. .seek-spinner-box {
  165. display: flex; flex-direction: column;
  166. align-items: center; gap: 10px;
  167. background: rgba(0,0,0,0.55);
  168. backdrop-filter: blur(4px);
  169. -webkit-backdrop-filter: blur(4px);
  170. border-radius: 14px;
  171. padding: 18px 24px;
  172. font-size: 12px; color: var(--text);
  173. font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  174. }
  175. .seek-spinner-box .spinner {
  176. width: 38px; height: 38px;
  177. border: 3px solid rgba(255,255,255,0.18);
  178. border-top-color: var(--accent);
  179. border-radius: 50%;
  180. animation: seekSpin 0.8s linear infinite;
  181. }
  182. @keyframes seekSpin { to { transform: rotate(360deg); } }
  183. /* ── Subtitle display ──────────────────────────────────────────────── */
  184. #subtitle-display {
  185. display: none;
  186. position: absolute;
  187. bottom: 72px; left: 50%; transform: translateX(-50%);
  188. width: 90%; text-align: center;
  189. pointer-events: none; /* z-index deliberately unset, see #ass-overlay */
  190. color: #fff; font-size: 22px; font-weight: 500; line-height: 1.45;
  191. text-shadow:
  192. -1px -1px 0 #000, 1px -1px 0 #000,
  193. -1px 1px 0 #000, 1px 1px 0 #000,
  194. 0 2px 6px rgba(0,0,0,0.85);
  195. }
  196. /* ── Centre play/pause flash indicator ─────────────────────────────── */
  197. #play-flash {
  198. position: absolute;
  199. top: 50%; left: 50%;
  200. width: 88px; height: 88px;
  201. margin: -44px 0 0 -44px;
  202. border-radius: 50%;
  203. background: rgba(0,0,0,0.55);
  204. backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
  205. display: flex; align-items: center; justify-content: center;
  206. pointer-events: none;
  207. opacity: 0; z-index: 18;
  208. }
  209. #play-flash img { width: 40px; height: 40px; display: block; }
  210. #play-flash.flash { animation: playFlash 0.62s ease-out; }
  211. @keyframes playFlash {
  212. 0% { opacity: 0; transform: scale(0.68); }
  213. 18% { opacity: 0.95; transform: scale(0.92); }
  214. 100% { opacity: 0; transform: scale(1.32); }
  215. }
  216. /* ── Resume popup ──────────────────────────────────────────────────── */
  217. #resume-popup {
  218. display: none;
  219. position: absolute; bottom: 90px; right: 20px; z-index: 25;
  220. background: rgba(22,22,24,0.97); backdrop-filter: blur(16px);
  221. border-radius: var(--radius); padding: 16px 18px; min-width: 240px;
  222. box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.1);
  223. animation: slideUpPopup 0.2s ease;
  224. color: var(--text);
  225. font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  226. }
  227. #resume-popup.active { display: block; }
  228. @keyframes slideUpPopup {
  229. from { opacity: 0; transform: translateY(10px); }
  230. to { opacity: 1; transform: translateY(0); }
  231. }
  232. #resume-popup-title { font-size: 13px; font-weight: 600; margin-bottom: 4px; }
  233. #resume-popup-sub { font-size: 12px; color: var(--text-sub); margin-bottom: 12px; }
  234. #resume-popup-btns { display: flex; gap: 8px; }
  235. .resume-btn {
  236. flex: 1; padding: 8px; border: none; cursor: pointer;
  237. border-radius: calc(var(--radius) / 1.6); font-size: 12px; font-weight: 600;
  238. outline: none; transition: opacity var(--transition);
  239. }
  240. .resume-btn:hover { opacity: 0.8; }
  241. #resume-btn-continue { background: var(--accent); color: #fff; }
  242. #resume-btn-restart { background: var(--surface2); color: var(--text); }
  243. /* ── Context menu ──────────────────────────────────────────────────── */
  244. #player-ctx {
  245. display: none;
  246. position: absolute; z-index: 30;
  247. background: rgba(28,28,30,0.97);
  248. backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
  249. border-radius: var(--radius); padding: 4px 0; min-width: 192px;
  250. box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
  251. user-select: none;
  252. font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  253. }
  254. .ctx-item {
  255. padding: 9px 14px; font-size: 13px; cursor: pointer;
  256. display: flex; align-items: center; gap: 10px;
  257. color: var(--text); transition: background var(--transition);
  258. }
  259. .ctx-item:hover { background: rgba(255,255,255,0.08); }
  260. .ctx-item.ctx-active { color: var(--accent); }
  261. .ctx-item.ctx-disabled { opacity: 0.3; pointer-events: none; }
  262. .ctx-icon { width: 16px; text-align: center; flex-shrink: 0; font-style: normal; }
  263. img.ctx-icon { height: 16px; opacity: 0.85; display: block; }
  264. .ctx-divider { height: 1px; background: rgba(255,255,255,0.08); margin: 3px 0; }
  265. .ctx-has-sub { justify-content: space-between; position: relative; }
  266. .ctx-sub-arrow { font-style: normal; opacity: 0.55; font-size: 15px; }
  267. #ctx-subtitle-sub {
  268. display: none;
  269. position: absolute; top: 0; left: 100%;
  270. background: rgba(28,28,30,0.97);
  271. backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
  272. border-radius: calc(var(--radius) * 1.5); padding: 4px 0; min-width: 200px;
  273. box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
  274. z-index: 32;
  275. }
  276. /* ── Subtitle settings modal ───────────────────────────────────────── */
  277. #subtitle-settings-modal {
  278. display: none;
  279. position: absolute; top: 50%; left: 50%;
  280. transform: translate(-50%, -50%);
  281. z-index: 40;
  282. background: rgba(18,18,20,0.97);
  283. backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
  284. border-radius: calc(var(--radius) / 1.5); padding: 20px 22px 18px; width: 340px;
  285. box-shadow: 0 8px 40px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.1);
  286. color: var(--text);
  287. font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  288. }
  289. #subtitle-settings-modal h3 {
  290. font-size: 14px; font-weight: 600; margin-bottom: 14px;
  291. display: flex; align-items: center; justify-content: space-between;
  292. }
  293. #sset-close {
  294. background: none; border: none; cursor: pointer;
  295. color: var(--text-sub); font-size: 17px; line-height: 1; padding: 0; outline: none;
  296. }
  297. #sset-close img { width: 14px; height: 14px; display: block; opacity: 0.55; transition: opacity var(--transition); }
  298. #sset-close:hover img { opacity: 1; }
  299. .sset-row {
  300. display: flex; align-items: center; gap: 10px;
  301. padding: 8px 0; border-bottom: 1px solid rgba(255,255,255,0.05);
  302. font-size: 12px;
  303. }
  304. .sset-row:last-child { border-bottom: none; }
  305. .sset-label { color: var(--text-sub); flex-shrink: 0; width: 56px; }
  306. .sset-seg {
  307. display: flex; background: var(--surface2);
  308. border-radius: calc(var(--radius) / 1.6); padding: 2px; gap: 2px; flex: 1;
  309. }
  310. .sset-seg-btn {
  311. flex: 1; padding: 4px 0; font-size: 12px; font-family: inherit;
  312. border: none; border-radius: calc(var(--radius) / 1.4); cursor: pointer;
  313. background: transparent; color: var(--text-sub);
  314. transition: background 0.15s, color 0.15s;
  315. }
  316. .sset-seg-btn.active { background: var(--surface); color: var(--text); }
  317. #sset-size { flex: 1; accent-color: var(--accent); cursor: pointer; }
  318. #sset-size-val { color: var(--text-sub); font-size: 11px; min-width: 32px; text-align: right; }
  319. #sset-font {
  320. flex: 1; background: var(--surface2); color: var(--text);
  321. border: 1px solid rgba(255,255,255,0.08); border-radius: calc(var(--radius) / 1.6);
  322. padding: 5px 8px; font-size: 12px; cursor: pointer; outline: none; appearance: auto;
  323. width: 100%;
  324. }
  325. .sset-colors { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; flex: 1; }
  326. .sset-color {
  327. width: 22px; height: 22px; border-radius: 50%;
  328. border: 2px solid transparent; outline: 2px solid transparent;
  329. cursor: pointer; padding: 0; flex-shrink: 0;
  330. transition: outline-color 0.15s, transform 0.1s;
  331. }
  332. .sset-color:hover { transform: scale(1.12); }
  333. .sset-color.active { outline-color: var(--text); transform: scale(1.15); }
  334. #sset-color-custom {
  335. width: 22px; height: 22px; border-radius: 50%;
  336. border: 2px solid rgba(255,255,255,0.2); padding: 0;
  337. cursor: pointer; background: transparent; flex-shrink: 0;
  338. }
  339. #sset-color-custom.active { border-color: var(--text); transform: scale(1.15); }
  340. #sset-preview {
  341. margin-top: 14px; background: rgba(0,0,0,0.65);
  342. border-radius: calc(var(--radius) / 1.25); padding: 14px 12px; text-align: center; line-height: 1.4;
  343. }
  344. /* ── Video info modal ──────────────────────────────────────────────── */
  345. #video-info-modal {
  346. display: none;
  347. position: absolute; top: 50%; left: 50%;
  348. transform: translate(-50%, -50%);
  349. z-index: 40;
  350. background: rgba(18,18,20,0.97);
  351. backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
  352. border-radius: calc(var(--radius) / 1.5); padding: 20px 22px 16px; width: 340px;
  353. box-shadow: 0 8px 40px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.1);
  354. color: var(--text);
  355. font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  356. }
  357. #video-info-modal h3 {
  358. font-size: 14px; font-weight: 600; margin-bottom: 12px;
  359. display: flex; align-items: center; justify-content: space-between;
  360. }
  361. #video-info-close {
  362. background: none; border: none; cursor: pointer;
  363. color: var(--text-sub); font-size: 17px; line-height: 1; padding: 0; outline: none;
  364. }
  365. #video-info-close img { width: 14px; height: 14px; display: block; opacity: 0.55; transition: opacity var(--transition); }
  366. #video-info-close:hover img { opacity: 1; }
  367. #video-info-tabs {
  368. display: flex; gap: 3px;
  369. background: var(--surface2); border-radius: calc(var(--radius) / 1.25); padding: 3px; margin-bottom: 12px;
  370. }
  371. .info-tab {
  372. flex: 1; text-align: center; padding: 5px 0;
  373. font-size: 12px; font-weight: 500; border-radius: calc(var(--radius) / 1.6); cursor: pointer;
  374. color: var(--text-sub);
  375. transition: background var(--transition), color var(--transition);
  376. }
  377. .info-tab.active { background: var(--surface); color: var(--text); }
  378. .info-row {
  379. display: flex; gap: 8px;
  380. padding: 5px 0; border-bottom: 1px solid rgba(255,255,255,0.05);
  381. font-size: 12px; line-height: 1.4;
  382. }
  383. .info-row:last-child { border-bottom: none; }
  384. .info-label { color: var(--text-sub); flex-shrink: 0; width: 110px; }
  385. .info-value { color: var(--text); word-break: break-all; }
  386. /* ── Playback settings popup (gear button) ─────────────────────────── */
  387. #settings-popup {
  388. display: none;
  389. position: absolute;
  390. right: 14px; bottom: 62px;
  391. z-index: 35;
  392. background: rgba(28,28,30,0.97);
  393. backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
  394. border-radius: calc(var(--radius) * 1.5);
  395. padding: 6px 0; width: 236px;
  396. box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
  397. color: var(--text);
  398. font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  399. user-select: none;
  400. }
  401. #settings-popup.active { display: block; }
  402. .set-section { padding: 6px 14px 8px; }
  403. .set-section + .set-section { border-top: 1px solid rgba(255,255,255,0.08); }
  404. .set-head {
  405. display: flex; align-items: center; gap: 8px;
  406. font-size: 11px; font-weight: 600; letter-spacing: 0.3px;
  407. text-transform: uppercase; color: var(--text-sub);
  408. margin-bottom: 7px;
  409. }
  410. .set-head img { width: 14px; height: 14px; opacity: 0.7; display: block; }
  411. .set-seg {
  412. display: flex; background: var(--surface2);
  413. border-radius: calc(var(--radius) * 1.2); padding: 2px; gap: 2px;
  414. }
  415. .set-seg-btn {
  416. flex: 1; padding: 5px 0; font-size: 12px; font-family: inherit;
  417. border: none; border-radius: var(--radius); cursor: pointer;
  418. background: transparent; color: var(--text-sub);
  419. transition: background 0.15s, color 0.15s; outline: none;
  420. }
  421. .set-seg-btn:hover { color: var(--text); }
  422. .set-seg-btn.active { background: var(--surface); color: var(--text); }
  423. .speed-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; }
  424. .speed-btn {
  425. padding: 5px 0; font-size: 12px; font-family: inherit;
  426. border: none; border-radius: var(--radius); cursor: pointer;
  427. background: var(--surface2); color: var(--text-sub);
  428. transition: background 0.15s, color 0.15s; outline: none;
  429. }
  430. .speed-btn:hover { color: var(--text); }
  431. .speed-btn.active { background: var(--accent); color: #fff; font-weight: 600; }
  432. .set-link {
  433. display: flex; align-items: center; gap: 9px;
  434. padding: 8px 14px; font-size: 13px; cursor: pointer;
  435. color: var(--text); transition: background var(--transition);
  436. }
  437. .set-link:hover { background: rgba(255,255,255,0.08); }
  438. .set-link img { width: 15px; height: 15px; opacity: 0.8; display: block; }
  439. /* ── Toast ─────────────────────────────────────────────────────────── */
  440. #toast {
  441. position: fixed; bottom: 30px; left: 50%;
  442. transform: translateX(-50%) translateY(20px);
  443. background: rgba(30,30,30,0.95); backdrop-filter: blur(8px);
  444. color: var(--text); padding: 10px 20px; border-radius: 20px;
  445. font-size: 13px; font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  446. opacity: 0; transition: opacity 0.3s, transform 0.3s;
  447. pointer-events: none; z-index: 1000; white-space: nowrap;
  448. }
  449. #toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
  450. </style>
  451. </head>
  452. <body>
  453. <div id="player-wrap">
  454. <video id="main-video" preload="metadata"></video>
  455. <!-- Frozen last frame + spinner, shown while a transcode seek re-buffers.
  456. Must stay directly after <video> — stacking relies on DOM order. -->
  457. <canvas id="seek-freeze"></canvas>
  458. <div id="seek-spinner">
  459. <div class="seek-spinner-box">
  460. <div class="spinner"></div>
  461. <span>Buffering…</span>
  462. </div>
  463. </div>
  464. <!-- Styled ASS/SSA subtitles are drawn here, sized to the video's
  465. displayed rectangle. The plain #subtitle-display below is used
  466. for SubRip tracks. -->
  467. <div id="ass-overlay"></div>
  468. <!-- Subtitle overlay -->
  469. <div id="subtitle-display"></div>
  470. <!-- Centre play/pause flash indicator -->
  471. <div id="play-flash"><img id="play-flash-icon" src="img/icons/play_white.svg" alt=""></div>
  472. <!-- Resume popup -->
  473. <div id="resume-popup">
  474. <div id="resume-popup-title">Resume playback?</div>
  475. <div id="resume-popup-sub"></div>
  476. <div id="resume-popup-btns">
  477. <button class="resume-btn" id="resume-btn-continue">Resume</button>
  478. <button class="resume-btn" id="resume-btn-restart">Start over</button>
  479. </div>
  480. </div>
  481. <!-- Context menu -->
  482. <div id="player-ctx">
  483. <div class="ctx-item" id="ctx-play"><img class="ctx-icon" src="img/icons/play_white.svg" alt="">Play</div>
  484. <div class="ctx-item" id="ctx-pause"><img class="ctx-icon" src="img/icons/pause_white.svg" alt="">Pause</div>
  485. <div class="ctx-divider"></div>
  486. <div class="ctx-item" id="ctx-repeat"><img class="ctx-icon" src="img/icons/repeat_white.svg" alt="">Repeat: Off</div>
  487. <div class="ctx-divider"></div>
  488. <div class="ctx-item ctx-has-sub" id="ctx-subtitle-parent">
  489. <span>Subtitles</span>
  490. <i class="ctx-sub-arrow">›</i>
  491. <div id="ctx-subtitle-sub">
  492. <div class="ctx-item ctx-active" id="ctx-sub-disable"><i class="ctx-icon">✓</i>Disable</div>
  493. <div class="ctx-divider"></div>
  494. <div class="ctx-item" id="ctx-sub-load"><i class="ctx-icon">+</i>Load SRT file…</div>
  495. </div>
  496. </div>
  497. <div class="ctx-divider"></div>
  498. <div class="ctx-item" id="ctx-subtitle-settings"><img class="ctx-icon" src="img/icons/settings_white.svg" alt="">Subtitle Settings</div>
  499. <div class="ctx-item" id="ctx-props">Video Properties</div>
  500. </div>
  501. <!-- Subtitle settings modal -->
  502. <div id="subtitle-settings-modal">
  503. <h3>Subtitle Settings<button id="sset-close" title="Close"><img src="img/icons/close_white.svg" alt=""></button></h3>
  504. <div class="sset-row">
  505. <span class="sset-label">Position</span>
  506. <div class="sset-seg">
  507. <button class="sset-seg-btn active" data-val="bottom">Bottom</button>
  508. <button class="sset-seg-btn" data-val="top">Top</button>
  509. </div>
  510. </div>
  511. <div class="sset-row">
  512. <span class="sset-label">Size</span>
  513. <input type="range" id="sset-size" min="14" max="52" step="1" value="22">
  514. <span id="sset-size-val">22px</span>
  515. </div>
  516. <div class="sset-row">
  517. <span class="sset-label">Font</span>
  518. <select id="sset-font">
  519. <option value="system-ui, sans-serif">System Default</option>
  520. <option value="Arial, sans-serif">Arial</option>
  521. <option value="'Helvetica Neue', Helvetica, sans-serif">Helvetica</option>
  522. <option value="Georgia, serif">Georgia</option>
  523. <option value="'Times New Roman', Times, serif">Times New Roman</option>
  524. <option value="'Courier New', Courier, monospace">Courier New</option>
  525. <option value="Verdana, sans-serif">Verdana</option>
  526. <option value="'Trebuchet MS', sans-serif">Trebuchet MS</option>
  527. <option value="Impact, fantasy">Impact</option>
  528. </select>
  529. </div>
  530. <div class="sset-row">
  531. <span class="sset-label">Color</span>
  532. <div class="sset-colors">
  533. <button class="sset-color active" data-color="#ffffff" style="background:#ffffff" title="White"></button>
  534. <button class="sset-color" data-color="#ffff00" style="background:#ffff00" title="Yellow"></button>
  535. <button class="sset-color" data-color="#00ffff" style="background:#00ffff" title="Cyan"></button>
  536. <button class="sset-color" data-color="#00ff88" style="background:#00ff88" title="Green"></button>
  537. <button class="sset-color" data-color="#ff8800" style="background:#ff8800" title="Orange"></button>
  538. <input type="color" id="sset-color-custom" value="#ffffff" title="Custom color">
  539. </div>
  540. </div>
  541. <div id="sset-preview">Sample subtitle text</div>
  542. </div>
  543. <!-- Video info / stats modal -->
  544. <div id="video-info-modal">
  545. <h3><span id="video-info-title">Video Properties</span><button id="video-info-close" title="Close" onclick="closeVideoInfo()"><img src="img/icons/close_white.svg" alt=""></button></h3>
  546. <div id="video-info-tabs">
  547. <div class="info-tab active" onclick="showInfoTab('props')">Properties</div>
  548. <div class="info-tab" onclick="showInfoTab('stats')">Stats</div>
  549. </div>
  550. <div id="video-info-body"></div>
  551. </div>
  552. <!-- Playback settings popup -->
  553. <div id="settings-popup">
  554. <div class="set-section">
  555. <div class="set-head"><img src="img/icons/repeat_white.svg" alt="">Repeat</div>
  556. <div class="set-seg" id="set-repeat-seg">
  557. <button class="set-seg-btn active" data-repeat="off">Off</button>
  558. <button class="set-seg-btn" data-repeat="one">Repeat one</button>
  559. </div>
  560. </div>
  561. <div class="set-section">
  562. <div class="set-head"><img src="img/icons/play_white.svg" alt="">Playback speed</div>
  563. <div class="speed-grid" id="set-speed-grid">
  564. <button class="speed-btn" data-speed="0.25">0.25×</button>
  565. <button class="speed-btn" data-speed="0.5">0.5×</button>
  566. <button class="speed-btn" data-speed="0.75">0.75×</button>
  567. <button class="speed-btn active" data-speed="1">Normal</button>
  568. <button class="speed-btn" data-speed="1.25">1.25×</button>
  569. <button class="speed-btn" data-speed="1.5">1.5×</button>
  570. <button class="speed-btn" data-speed="1.75">1.75×</button>
  571. <button class="speed-btn" data-speed="2">2×</button>
  572. </div>
  573. </div>
  574. <div class="set-section">
  575. <div class="set-head"><img src="img/icons/volume_white.svg" alt="">Volume bar</div>
  576. <div class="set-seg" id="set-volbar-seg">
  577. <button class="set-seg-btn active" data-volbar="auto">Auto</button>
  578. <button class="set-seg-btn" data-volbar="always">Always show</button>
  579. </div>
  580. </div>
  581. <div class="set-section" style="padding-left:0;padding-right:0;padding-bottom:2px;">
  582. <div class="set-link" id="set-load-subtitle">
  583. <img src="img/icons/movie_white.svg" alt="">Load SRT subtitle…
  584. </div>
  585. <div class="set-link" id="set-subtitle-settings">
  586. <img src="img/icons/settings_white.svg" alt="">Subtitle settings
  587. </div>
  588. <div class="set-link" id="set-video-props">
  589. <img src="img/icons/menu_white.svg" alt="">Video properties
  590. </div>
  591. </div>
  592. </div>
  593. <!-- Player controls -->
  594. <div id="video-controls">
  595. <div id="progress-wrap">
  596. <div id="progress-bar" style="width:0%"></div>
  597. <div id="progress-thumb" style="left:0%"></div>
  598. <div id="scrub-preview">
  599. <div id="scrub-preview-thumb"></div>
  600. <div id="scrub-preview-time">0:00</div>
  601. </div>
  602. </div>
  603. <div id="controls-row">
  604. <button class="ctrl-btn" id="ctrl-play" title="Play / Pause (Space)">
  605. <img id="play-icon" src="img/icons/play_white.svg" alt="">
  606. </button>
  607. <div id="volume-wrap">
  608. <button class="ctrl-btn" id="ctrl-mute" title="Mute (M)">
  609. <img id="mute-icon" src="img/icons/volume_white.svg" alt="">
  610. </button>
  611. <input id="volume-slider" type="range" min="0" max="1" step="0.05" value="1">
  612. </div>
  613. <span id="time-display">0:00 / 0:00</span>
  614. <span id="spacer"></span>
  615. <button class="ctrl-btn" id="ctrl-settings" title="Playback settings">
  616. <img src="img/icons/settings_white.svg" alt="">
  617. </button>
  618. <button class="ctrl-btn" id="ctrl-fs" title="Fullscreen (F)">
  619. <img src="img/icons/fullscreen_white.svg" alt="">
  620. </button>
  621. </div>
  622. </div>
  623. </div><!-- #player-wrap -->
  624. <div id="toast"></div>
  625. <script>
  626. // ── State ─────────────────────────────────────────────────────────────────────
  627. var vid = document.getElementById('main-video');
  628. var currentFile = null; // {name, filepath, ext}
  629. var transcodeSeekOffset = 0; // seconds already streamed before current chunk
  630. var isTranscodedVideo = false;
  631. var transcodeDuration = 0; // total duration for transcoded video (from /media/duration/)
  632. var pendingResumePos = 0;
  633. var watchSaveInterval = null;
  634. var controlsTimer = null;
  635. var repeatSingle = (localStorage.getItem('movie_repeat_one') === '1');
  636. var playbackSpeed = parseFloat(localStorage.getItem('movie_playback_speed') || '1') || 1;
  637. var alwaysShowVolumeBar = (localStorage.getItem('movie_always_volume_bar') === '1');
  638. var infoRefreshTimer = null;
  639. var currentInfoTab = 'props';
  640. // Subtitle state
  641. var loadedSubtitleFiles = []; // [{path, name, cues:[{start,end,text}]}]
  642. var activeSubtitleIndex = -1; // -1 = disabled
  643. // Subtitle settings (shared with main Movie window via localStorage)
  644. var subtitleSettings = { position: 'bottom', size: 22, font: 'system-ui, sans-serif', color: '#ffffff' };
  645. // ── Utilities ─────────────────────────────────────────────────────────────────
  646. function isWebPlayable(ext) {
  647. return ['mp4', 'webm', 'ogg'].indexOf(ext) !== -1;
  648. }
  649. function formatTime(s) {
  650. if (isNaN(s) || s < 0) { return '0:00'; }
  651. var h = Math.floor(s / 3600);
  652. var m = Math.floor((s % 3600) / 60);
  653. var sec = Math.floor(s % 60);
  654. var parts = [];
  655. if (h > 0) { parts.push(h); }
  656. parts.push(m);
  657. parts.push(sec < 10 ? '0' + sec : '' + sec);
  658. return parts.join(':');
  659. }
  660. function escapeHtml(str) {
  661. if (!str) { return ''; }
  662. return String(str)
  663. .replace(/&/g, '&amp;').replace(/</g, '&lt;')
  664. .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  665. }
  666. // Flash a large play/pause glyph in the centre of the video so the user gets
  667. // immediate feedback that their click / key press registered.
  668. function flashPlayState(isPlaying) {
  669. var $f = $('#play-flash');
  670. $('#play-flash-icon').attr('src',
  671. isPlaying ? 'img/icons/play_white.svg' : 'img/icons/pause_white.svg');
  672. $f.removeClass('flash');
  673. void $f[0].offsetWidth; // force reflow so the animation restarts
  674. $f.addClass('flash');
  675. }
  676. var toastTimer;
  677. function showToast(msg) {
  678. clearTimeout(toastTimer);
  679. $('#toast').text(msg).addClass('show');
  680. toastTimer = setTimeout(function () { $('#toast').removeClass('show'); }, 2800);
  681. }
  682. // ── File loading ──────────────────────────────────────────────────────────────
  683. var files = ao_module_loadInputFiles();
  684. if (files && files.length > 0) {
  685. currentFile = {
  686. name: files[0].filename,
  687. filepath: files[0].filepath,
  688. ext: files[0].filename.split('.').pop().toLowerCase()
  689. };
  690. ao_module_setWindowTitle('Movie – ' + currentFile.name);
  691. isTranscodedVideo = !isWebPlayable(currentFile.ext);
  692. vid.src = isTranscodedVideo
  693. ? TRANSCODE_API + '?file=' + encodeURIComponent(currentFile.filepath)
  694. : MEDIA_API + '?file=' + encodeURIComponent(currentFile.filepath);
  695. vid.autoplay = true;
  696. vid.load();
  697. // Resume position check (only for videos longer than 1 hour)
  698. if (!isTranscodedVideo) {
  699. $(vid).one('loadedmetadata.resume', function () {
  700. if (vid.duration > 3600 && currentFile) {
  701. ao_module_agirun(SCRIPT_GET_WATCHTIME, { filepath: currentFile.filepath }, function (data) {
  702. if (data && !data.error && data.position > 30 && data.position < vid.duration * 0.95) {
  703. showResumePopup(data.position, vid.duration);
  704. }
  705. });
  706. }
  707. });
  708. } else {
  709. // Fetch total duration separately (transcode stream doesn't expose it)
  710. fetch(ao_root + 'media/duration/?file=' + encodeURIComponent(currentFile.filepath))
  711. .then(function (r) { return r.json(); })
  712. .then(function (data) {
  713. if (data.duration > 0) {
  714. transcodeDuration = data.duration;
  715. if (transcodeDuration > 3600 && currentFile) {
  716. ao_module_agirun(SCRIPT_GET_WATCHTIME, { filepath: currentFile.filepath }, function (wdata) {
  717. if (wdata && !wdata.error && wdata.position > 30 && wdata.position < transcodeDuration * 0.95) {
  718. showResumePopup(wdata.position, transcodeDuration);
  719. }
  720. });
  721. }
  722. }
  723. }).catch(function () {});
  724. }
  725. }
  726. // ── Scrub-bar hover preview (storyboard) ──────────────────────────────────────
  727. // The server renders one sprite sheet per file holding a downscaled frame every
  728. // few seconds; we fetch it once and keep it in memory, so hovering the timeline
  729. // costs nothing. Asking ffmpeg for a frame per hover would be hopeless on a
  730. // software-decoded H.265 source, which is exactly where previews matter most.
  731. var storyboard = null; // layout from the server + the loaded sheet URL
  732. var storyboardToken = 0; // invalidates in-flight loads when the file changes
  733. var storyboardTimer = null;
  734. function resetStoryboard() {
  735. storyboardToken++;
  736. storyboard = null;
  737. clearTimeout(storyboardTimer);
  738. storyboardTimer = null;
  739. $('#scrub-preview-thumb').removeClass('ready');
  740. hideScrubPreview();
  741. }
  742. // Building the sheet runs ffmpeg, so hold off briefly and let playback (and any
  743. // transcode) get established before adding more load.
  744. function scheduleStoryboardLoad(filepath) {
  745. resetStoryboard();
  746. if (!filepath) { return; }
  747. var token = storyboardToken;
  748. storyboardTimer = setTimeout(function () { loadStoryboard(filepath, token); }, 3000);
  749. }
  750. function loadStoryboard(filepath, token) {
  751. var base = STORYBOARD_API + '?file=' + encodeURIComponent(filepath);
  752. fetch(base)
  753. .then(function (r) { return r.json(); })
  754. .then(function (meta) {
  755. if (token !== storyboardToken) { return; } // switched file while loading
  756. if (!meta || meta.error || !meta.interval || !meta.tileWidth) { return; }
  757. var img = new Image();
  758. img.onload = function () {
  759. if (token !== storyboardToken) { return; }
  760. meta.url = img.src;
  761. storyboard = meta;
  762. };
  763. img.src = base + '&image=1';
  764. })
  765. .catch(function () {}); // previews are optional — stay silent on failure
  766. }
  767. // Whole-file duration, whichever playback mode is active
  768. function scrubTotalDuration() {
  769. if (isTranscodedVideo) { return transcodeDuration; }
  770. return vid.duration || 0;
  771. }
  772. function initScrubPreview() {
  773. var $wrap = $('#progress-wrap');
  774. $wrap.on('mousemove', function (e) {
  775. var total = scrubTotalDuration();
  776. var rect = this.getBoundingClientRect();
  777. if (!total || !isFinite(total) || rect.width <= 0) { hideScrubPreview(); return; }
  778. var ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
  779. showScrubPreview(ratio * total, ratio, rect.width);
  780. });
  781. $wrap.on('mouseleave', hideScrubPreview);
  782. }
  783. function showScrubPreview(time, ratio, barWidth) {
  784. $('#scrub-preview-time').text(formatTime(time));
  785. var $thumb = $('#scrub-preview-thumb');
  786. var halfWidth;
  787. if (storyboard && storyboard.url) {
  788. var idx = Math.max(0, Math.min(storyboard.count - 1,
  789. Math.floor(time / storyboard.interval)));
  790. var col = idx % storyboard.cols;
  791. var row = Math.floor(idx / storyboard.cols);
  792. $thumb.addClass('ready').css({
  793. 'width': storyboard.tileWidth + 'px',
  794. 'height': storyboard.tileHeight + 'px',
  795. 'background-image': 'url("' + storyboard.url + '")',
  796. 'background-position': (-col * storyboard.tileWidth) + 'px '
  797. + (-row * storyboard.tileHeight) + 'px'
  798. });
  799. halfWidth = storyboard.tileWidth / 2;
  800. } else {
  801. // Sheet not ready (or unavailable) — the timestamp alone is still useful
  802. $thumb.removeClass('ready');
  803. halfWidth = 28;
  804. }
  805. // Keep the popup within the bar rather than letting it hang off an edge
  806. var x = Math.max(halfWidth, Math.min(barWidth - halfWidth, ratio * barWidth));
  807. $('#scrub-preview').css('left', x + 'px').addClass('active');
  808. }
  809. function hideScrubPreview() { $('#scrub-preview').removeClass('active'); }
  810. // ── Transcode seek (seek-by-reload) ───────────────────────────────────────────
  811. // Formats the browser can't decode are streamed through ffmpeg, so "seeking"
  812. // means restarting the transcode at a new offset. Replacing .src blanks the
  813. // <video> to black until the first frame of the new segment arrives, which can
  814. // take seconds. Freeze the last painted frame under a spinner instead, and only
  815. // reveal the live element once it is genuinely playing again.
  816. var seekFreezeTimer = null;
  817. function showSeekFreeze() {
  818. var canvas = document.getElementById('seek-freeze');
  819. if (canvas && vid.videoWidth > 0 && vid.videoHeight > 0) {
  820. canvas.width = vid.videoWidth;
  821. canvas.height = vid.videoHeight;
  822. try {
  823. canvas.getContext('2d').drawImage(vid, 0, 0, canvas.width, canvas.height);
  824. $(canvas).show();
  825. } catch (e) {
  826. // No decodable frame right now (e.g. seeking again mid-buffer) —
  827. // leave whatever is already frozen on screen rather than flashing black.
  828. }
  829. }
  830. $('#seek-spinner').addClass('active');
  831. clearTimeout(seekFreezeTimer);
  832. // Safety net: a stalled transcode must never leave the overlay stuck on
  833. seekFreezeTimer = setTimeout(hideSeekFreeze, 30000);
  834. }
  835. function hideSeekFreeze() {
  836. clearTimeout(seekFreezeTimer);
  837. seekFreezeTimer = null;
  838. $('#seek-freeze').hide();
  839. $('#seek-spinner').removeClass('active');
  840. }
  841. // Restart the transcode stream at `seconds`, holding the last frame until the
  842. // new segment plays. Clamped to the known duration.
  843. function transcodeSeekTo(seconds) {
  844. if (!currentFile) { return; }
  845. var pos = Math.max(0, seconds);
  846. if (transcodeDuration > 0) { pos = Math.min(transcodeDuration, pos); }
  847. showSeekFreeze();
  848. setSubtitleSeekFloor(pos);
  849. transcodeSeekOffset = pos;
  850. vid.src = TRANSCODE_API + '?file=' + encodeURIComponent(currentFile.filepath)
  851. + '&start=' + pos.toFixed(3);
  852. vid.load();
  853. vid.play();
  854. }
  855. // Current playback position in whole-file terms (transcode streams restart at 0)
  856. function effectivePlaybackTime() {
  857. return isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
  858. }
  859. // ── Video controls ────────────────────────────────────────────────────────────
  860. function initVideoControls() {
  861. var $prog = $('#progress-bar');
  862. var $thumb = $('#progress-thumb');
  863. var $time = $('#time-display');
  864. // Restore saved volume
  865. var savedVol = parseFloat(localStorage.getItem('movie_volume'));
  866. if (!isNaN(savedVol) && savedVol >= 0 && savedVol <= 1) {
  867. vid.volume = savedVol;
  868. $('#volume-slider').val(savedVol);
  869. }
  870. if (localStorage.getItem('movie_muted') === '1') { vid.muted = true; }
  871. $('#ctrl-play').on('click', togglePlay);
  872. $(vid).on('click', togglePlay);
  873. $('#ctrl-mute').on('click', function () { vid.muted = !vid.muted; updateMuteIcon(); });
  874. $('#volume-slider').on('input', function () {
  875. vid.volume = parseFloat($(this).val());
  876. updateMuteIcon();
  877. });
  878. $('#ctrl-fs').on('click', toggleFullscreen);
  879. // Progress bar — seek-by-reload for transcoded streams
  880. $('#progress-wrap').on('click', function (e) {
  881. if (isTranscodedVideo && transcodeDuration > 0 && currentFile) {
  882. transcodeSeekTo((e.offsetX / $(this).width()) * transcodeDuration);
  883. return;
  884. }
  885. if (vid.duration) {
  886. vid.currentTime = (e.offsetX / $(this).width()) * vid.duration;
  887. }
  888. });
  889. // Progress + subtitle update on timeupdate
  890. $(vid).on('timeupdate', function () {
  891. updateSubtitleDisplay();
  892. if (isTranscodedVideo) {
  893. var displayTime = vid.currentTime + transcodeSeekOffset;
  894. if (transcodeDuration > 0) {
  895. var pct = (displayTime / transcodeDuration) * 100;
  896. $prog.css('width', pct + '%');
  897. $thumb.css('left', 'calc(' + pct + '% - 7px)');
  898. $time.text(formatTime(displayTime) + ' / ' + formatTime(transcodeDuration));
  899. } else {
  900. $time.text(formatTime(displayTime) + ' / --:--');
  901. }
  902. return;
  903. }
  904. if (!vid.duration) { return; }
  905. var pct = (vid.currentTime / vid.duration) * 100;
  906. $prog.css('width', pct + '%');
  907. $thumb.css('left', 'calc(' + pct + '% - 7px)');
  908. $time.text(formatTime(vid.currentTime) + ' / ' + formatTime(vid.duration));
  909. });
  910. $(vid).on('play', function () {
  911. $('#play-icon').attr('src', 'img/icons/pause_white.svg');
  912. if (watchSaveInterval) { clearInterval(watchSaveInterval); }
  913. watchSaveInterval = setInterval(function () {
  914. var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
  915. if (!vid.paused && effectiveDuration > 3600) { saveWatchPosition(); }
  916. }, 30000);
  917. });
  918. $(vid).on('pause', function () {
  919. $('#play-icon').attr('src', 'img/icons/play_white.svg');
  920. if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
  921. var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
  922. var effectiveTime = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
  923. if (effectiveDuration > 3600 && effectiveTime > 30) { saveWatchPosition(); }
  924. showControls();
  925. });
  926. $(vid).on('ended', function () {
  927. clearWatchPosition();
  928. if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
  929. if (!repeatSingle) { return; }
  930. if (isTranscodedVideo && transcodeSeekOffset > 0 && currentFile) {
  931. // The stream started part-way in — restart it from the beginning
  932. transcodeSeekTo(0);
  933. } else {
  934. vid.currentTime = 0;
  935. vid.play();
  936. }
  937. });
  938. $(vid).on('volumechange', function () {
  939. updateMuteIcon();
  940. localStorage.setItem('movie_volume', vid.volume);
  941. localStorage.setItem('movie_muted', vid.muted ? '1' : '0');
  942. });
  943. // Drop the transcode-seek freeze frame the moment the new segment is live.
  944. // 'playing' is the accurate signal; 'loadeddata' covers a seek made while
  945. // paused (where 'playing' never fires), and 'error' avoids a stuck overlay.
  946. // Any seek — native or transcode reload — re-bases the subtitle floor
  947. $(vid).on('seeking', function () { setSubtitleSeekFloor(effectivePlaybackTime()); });
  948. $(vid).on('playing', hideSeekFreeze);
  949. $(vid).on('loadeddata', function () { if (vid.paused) { hideSeekFreeze(); } });
  950. $(vid).on('error', hideSeekFreeze);
  951. // Auto-hide controls on mouse movement
  952. $('#player-wrap').on('mousemove touchstart', showControls);
  953. document.addEventListener('fullscreenchange', function () {
  954. if (!document.fullscreenElement) { showControls(); }
  955. });
  956. }
  957. function updateMuteIcon() {
  958. var isMuted = vid.muted || vid.volume === 0;
  959. $('#mute-icon').attr('src', isMuted ? 'img/icons/mute_white.svg' : 'img/icons/volume_white.svg');
  960. $('#volume-slider').val(vid.muted ? 0 : vid.volume);
  961. }
  962. function togglePlay() {
  963. $('#resume-popup').removeClass('active');
  964. var willPlay = vid.paused;
  965. if (willPlay) { vid.play(); } else { vid.pause(); }
  966. flashPlayState(willPlay);
  967. }
  968. function showControls() {
  969. $('#video-controls').removeClass('hidden');
  970. clearTimeout(controlsTimer);
  971. controlsTimer = setTimeout(function () {
  972. // Keep the bar up while the settings popup is open — it is anchored to it
  973. if (!vid.paused && !$('#settings-popup').hasClass('active')) {
  974. $('#video-controls').addClass('hidden');
  975. }
  976. }, 3000);
  977. }
  978. function toggleFullscreen() {
  979. var el = document.getElementById('player-wrap');
  980. if (!document.fullscreenElement) {
  981. (el.requestFullscreen || el.webkitRequestFullscreen || el.mozRequestFullScreen).call(el);
  982. } else {
  983. (document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen).call(document);
  984. }
  985. }
  986. // ── Watch position (resume) ───────────────────────────────────────────────────
  987. function saveWatchPosition() {
  988. if (!currentFile) { return; }
  989. var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
  990. var effectiveTime = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
  991. if (!effectiveDuration || effectiveDuration < 3600 || effectiveTime < 10) { return; }
  992. ao_module_agirun(SCRIPT_SET_WATCHTIME, {
  993. filepath: currentFile.filepath,
  994. position: Math.floor(effectiveTime),
  995. duration: Math.floor(effectiveDuration)
  996. }, function () {}, function () {});
  997. }
  998. function clearWatchPosition() {
  999. if (!currentFile) { return; }
  1000. ao_module_agirun(SCRIPT_SET_WATCHTIME,
  1001. { filepath: currentFile.filepath, position: 0, duration: 0 },
  1002. function () {}, function () {});
  1003. }
  1004. function showResumePopup(savedPos, duration) {
  1005. vid.pause();
  1006. pendingResumePos = savedPos;
  1007. $('#resume-popup-sub').text(
  1008. 'Last position: ' + formatTime(savedPos) + ' of ' + formatTime(duration)
  1009. );
  1010. $('#resume-popup').addClass('active');
  1011. showControls();
  1012. $('#resume-btn-continue').off('click').on('click', function () {
  1013. if (isTranscodedVideo && currentFile) {
  1014. transcodeSeekTo(pendingResumePos);
  1015. } else {
  1016. vid.currentTime = pendingResumePos;
  1017. vid.play();
  1018. }
  1019. $('#resume-popup').removeClass('active');
  1020. });
  1021. $('#resume-btn-restart').off('click').on('click', function () {
  1022. vid.play();
  1023. $('#resume-popup').removeClass('active');
  1024. });
  1025. }
  1026. // ── Context menu ──────────────────────────────────────────────────────────────
  1027. function initContextMenu() {
  1028. var $ctx = $('#player-ctx');
  1029. $('#player-wrap').on('contextmenu', function (e) {
  1030. e.preventDefault();
  1031. if (!currentFile) { return; }
  1032. $('#ctx-play').toggleClass('ctx-disabled', !vid.paused);
  1033. $('#ctx-pause').toggleClass('ctx-disabled', vid.paused);
  1034. $('#ctx-repeat')
  1035. .toggleClass('ctx-active', repeatSingle)
  1036. .html('<img class="ctx-icon" src="img/icons/'
  1037. + (repeatSingle ? 'repeat_one_white.svg' : 'repeat_white.svg')
  1038. + '" alt="">Repeat: ' + (repeatSingle ? 'On' : 'Off'));
  1039. $('#ctx-subtitle-sub').hide();
  1040. closeSettingsPopup();
  1041. var rect = this.getBoundingClientRect();
  1042. var x = e.clientX - rect.left;
  1043. var y = e.clientY - rect.top;
  1044. $ctx.css({ left: x, top: y, display: 'block' });
  1045. var mw = $ctx.outerWidth(), mh = $ctx.outerHeight();
  1046. if (x + mw > rect.width) { $ctx.css('left', Math.max(0, x - mw)); }
  1047. if (y + mh > rect.height) { $ctx.css('top', Math.max(0, y - mh)); }
  1048. showControls();
  1049. });
  1050. $(document).on('mousedown.ctx', function (e) {
  1051. if (!$(e.target).closest('#player-ctx').length) { $ctx.hide(); }
  1052. });
  1053. $('#ctx-play').on('click', function () { vid.play(); flashPlayState(true); $ctx.hide(); });
  1054. $('#ctx-pause').on('click', function () { vid.pause(); flashPlayState(false); $ctx.hide(); });
  1055. $('#ctx-repeat').on('click', function () { setRepeatSingle(!repeatSingle); $ctx.hide(); });
  1056. $('#ctx-subtitle-settings').on('click', function () { $ctx.hide(); openSubtitleSettings(); });
  1057. $('#ctx-props').on('click', function () { $ctx.hide(); openVideoInfo('props'); });
  1058. }
  1059. // ── Playback settings popup (gear button) ─────────────────────────────────────
  1060. function setAlwaysShowVolumeBar(on) {
  1061. alwaysShowVolumeBar = !!on;
  1062. localStorage.setItem('movie_always_volume_bar', alwaysShowVolumeBar ? '1' : '0');
  1063. $('body').toggleClass('always-show-volume', alwaysShowVolumeBar);
  1064. $('#set-volbar-seg .set-seg-btn').removeClass('active')
  1065. .filter('[data-volbar="' + (alwaysShowVolumeBar ? 'always' : 'auto') + '"]').addClass('active');
  1066. }
  1067. function setRepeatSingle(on) {
  1068. repeatSingle = !!on;
  1069. vid.loop = false; // handled manually in the 'ended' handler
  1070. localStorage.setItem('movie_repeat_one', repeatSingle ? '1' : '0');
  1071. $('#set-repeat-seg .set-seg-btn').removeClass('active')
  1072. .filter('[data-repeat="' + (repeatSingle ? 'one' : 'off') + '"]').addClass('active');
  1073. }
  1074. function setPlaybackSpeed(rate) {
  1075. playbackSpeed = parseFloat(rate) || 1;
  1076. vid.playbackRate = playbackSpeed;
  1077. localStorage.setItem('movie_playback_speed', String(playbackSpeed));
  1078. $('#set-speed-grid .speed-btn').removeClass('active')
  1079. .filter('[data-speed="' + playbackSpeed + '"]').addClass('active');
  1080. }
  1081. function openSettingsPopup() {
  1082. setRepeatSingle(repeatSingle);
  1083. setPlaybackSpeed(playbackSpeed);
  1084. setAlwaysShowVolumeBar(alwaysShowVolumeBar);
  1085. $('#player-ctx').hide();
  1086. $('#settings-popup').addClass('active');
  1087. showControls();
  1088. }
  1089. function closeSettingsPopup() { $('#settings-popup').removeClass('active'); }
  1090. function toggleSettingsPopup() {
  1091. if ($('#settings-popup').hasClass('active')) { closeSettingsPopup(); }
  1092. else { openSettingsPopup(); }
  1093. }
  1094. function initSettingsPopup() {
  1095. $('#ctrl-settings').on('click', function (e) {
  1096. e.stopPropagation();
  1097. toggleSettingsPopup();
  1098. });
  1099. // Dismiss when clicking anywhere outside the popup or its button
  1100. $(document).on('mousedown.setpop', function (e) {
  1101. if (!$(e.target).closest('#settings-popup, #ctrl-settings').length) {
  1102. closeSettingsPopup();
  1103. }
  1104. });
  1105. $('#set-repeat-seg').on('click', '.set-seg-btn', function () {
  1106. setRepeatSingle($(this).data('repeat') === 'one');
  1107. });
  1108. $('#set-speed-grid').on('click', '.speed-btn', function () {
  1109. setPlaybackSpeed($(this).data('speed'));
  1110. });
  1111. $('#set-volbar-seg').on('click', '.set-seg-btn', function () {
  1112. setAlwaysShowVolumeBar($(this).data('volbar') === 'always');
  1113. });
  1114. $('#set-load-subtitle').on('click', function () { closeSettingsPopup(); pickSubtitleFile(); });
  1115. $('#set-subtitle-settings').on('click', function () { closeSettingsPopup(); openSubtitleSettings(); });
  1116. $('#set-video-props').on('click', function () { closeSettingsPopup(); openVideoInfo('props'); });
  1117. // Apply persisted values to the video element
  1118. setRepeatSingle(repeatSingle);
  1119. setPlaybackSpeed(playbackSpeed);
  1120. setAlwaysShowVolumeBar(alwaysShowVolumeBar);
  1121. // A transcode seek replaces the media source, which resets playbackRate —
  1122. // reapply the chosen speed every time new media is loaded.
  1123. $(vid).on('loadedmetadata', function () { vid.playbackRate = playbackSpeed; });
  1124. }
  1125. // ── Video info / stats modal ──────────────────────────────────────────────────
  1126. function openVideoInfo(tab) {
  1127. currentInfoTab = tab || 'props';
  1128. $('#video-info-modal').show();
  1129. $('.info-tab').removeClass('active').eq(currentInfoTab === 'props' ? 0 : 1).addClass('active');
  1130. $('#video-info-title').text(currentInfoTab === 'props' ? 'Video Properties' : 'Streaming Stats');
  1131. renderInfoContent();
  1132. if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
  1133. if (currentInfoTab === 'stats') {
  1134. infoRefreshTimer = setInterval(renderInfoContent, 1000);
  1135. }
  1136. }
  1137. function closeVideoInfo() {
  1138. $('#video-info-modal').hide();
  1139. if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
  1140. }
  1141. function showInfoTab(tab) {
  1142. currentInfoTab = tab;
  1143. $('.info-tab').removeClass('active').eq(tab === 'props' ? 0 : 1).addClass('active');
  1144. $('#video-info-title').text(tab === 'props' ? 'Video Properties' : 'Streaming Stats');
  1145. if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
  1146. if (tab === 'stats') { infoRefreshTimer = setInterval(renderInfoContent, 1000); }
  1147. renderInfoContent();
  1148. }
  1149. function infoRow(label, value) {
  1150. return '<div class="info-row"><span class="info-label">' + escapeHtml(String(label)) + '</span>'
  1151. + '<span class="info-value">' + escapeHtml(String(value)) + '</span></div>';
  1152. }
  1153. function renderInfoContent() {
  1154. var html = '';
  1155. if (currentInfoTab === 'props') {
  1156. html += infoRow('Title', currentFile ? currentFile.name : '–');
  1157. html += infoRow('Resolution', (vid.videoWidth && vid.videoHeight)
  1158. ? vid.videoWidth + ' × ' + vid.videoHeight : '–');
  1159. var infoDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
  1160. var infoPosition = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
  1161. html += infoRow('Duration', infoDuration ? formatTime(infoDuration) : '–');
  1162. html += infoRow('Position', infoPosition ? formatTime(infoPosition) : '–');
  1163. html += infoRow('Playback speed', vid.playbackRate + '×');
  1164. html += infoRow('Volume', vid.muted ? 'Muted' : Math.round(vid.volume * 100) + '%');
  1165. if (currentFile) { html += infoRow('File path', currentFile.filepath || '–'); }
  1166. } else {
  1167. var rsLabels = ['No info', 'Metadata only', 'Have current data', 'Have future data', 'Enough data'];
  1168. var nsLabels = ['Empty', 'Idle', 'Loading', 'No source'];
  1169. html += infoRow('Ready state', rsLabels[vid.readyState] || vid.readyState);
  1170. html += infoRow('Network state', nsLabels[vid.networkState] || vid.networkState);
  1171. var bufEnd = 0;
  1172. if (vid.buffered && vid.buffered.length > 0) {
  1173. for (var i = 0; i < vid.buffered.length; i++) {
  1174. if (vid.buffered.start(i) <= vid.currentTime + 0.1) {
  1175. bufEnd = Math.max(bufEnd, vid.buffered.end(i));
  1176. }
  1177. }
  1178. }
  1179. html += infoRow('Buffer ahead', Math.max(0, bufEnd - vid.currentTime).toFixed(1) + 's');
  1180. html += infoRow('Total buffered', vid.buffered.length > 0
  1181. ? formatTime(vid.buffered.end(vid.buffered.length - 1)) : '–');
  1182. if (vid.getVideoPlaybackQuality) {
  1183. var q = vid.getVideoPlaybackQuality();
  1184. html += infoRow('Frames decoded', q.totalVideoFrames || 0);
  1185. html += infoRow('Frames dropped', q.droppedVideoFrames || 0);
  1186. }
  1187. html += infoRow('Stalled / ended', vid.ended ? 'Ended' : (vid.readyState < 3 ? 'Yes' : 'No'));
  1188. }
  1189. $('#video-info-body').html(html);
  1190. }
  1191. // ── Subtitle settings ─────────────────────────────────────────────────────────
  1192. function loadSubtitleSettings() {
  1193. try {
  1194. var s = JSON.parse(localStorage.getItem('movie_subtitle_settings') || 'null');
  1195. if (s) { Object.assign(subtitleSettings, s); }
  1196. } catch (e) {}
  1197. }
  1198. function saveSubtitleSettings() {
  1199. localStorage.setItem('movie_subtitle_settings', JSON.stringify(subtitleSettings));
  1200. }
  1201. function applySubtitleSettings() {
  1202. var s = subtitleSettings;
  1203. $('#subtitle-display').css({
  1204. 'font-size': s.size + 'px',
  1205. 'font-family': s.font,
  1206. 'color': s.color,
  1207. 'bottom': s.position === 'bottom' ? '72px' : 'auto',
  1208. 'top': s.position === 'top' ? '72px' : 'auto',
  1209. 'transform': 'translateX(-50%)'
  1210. });
  1211. }
  1212. function syncSettingsPreview() {
  1213. var s = subtitleSettings;
  1214. $('#sset-preview').css({
  1215. 'font-size': s.size + 'px',
  1216. 'font-family': s.font,
  1217. 'color': s.color,
  1218. 'text-shadow': '-1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000, 0 2px 6px rgba(0,0,0,0.85)'
  1219. });
  1220. }
  1221. function openSubtitleSettings() {
  1222. var s = subtitleSettings;
  1223. $('.sset-seg-btn').removeClass('active').filter('[data-val="' + s.position + '"]').addClass('active');
  1224. $('#sset-size').val(s.size);
  1225. $('#sset-size-val').text(s.size + 'px');
  1226. $('#sset-font').val(s.font);
  1227. var swatchMatch = $('.sset-color[data-color="' + s.color.toLowerCase() + '"]');
  1228. $('.sset-color, #sset-color-custom').removeClass('active');
  1229. if (swatchMatch.length) { swatchMatch.addClass('active'); }
  1230. else { $('#sset-color-custom').addClass('active'); }
  1231. $('#sset-color-custom').val(s.color);
  1232. syncSettingsPreview();
  1233. $('#subtitle-settings-modal').show();
  1234. }
  1235. function closeSubtitleSettings() { $('#subtitle-settings-modal').hide(); }
  1236. function initSubtitleSettings() {
  1237. loadSubtitleSettings();
  1238. applySubtitleSettings();
  1239. $('#sset-close').on('click', closeSubtitleSettings);
  1240. $(document).on('click', '.sset-seg-btn', function () {
  1241. subtitleSettings.position = $(this).data('val');
  1242. $('.sset-seg-btn').removeClass('active');
  1243. $(this).addClass('active');
  1244. applySubtitleSettings();
  1245. saveSubtitleSettings();
  1246. });
  1247. $('#sset-size').on('input', function () {
  1248. subtitleSettings.size = parseInt($(this).val(), 10);
  1249. $('#sset-size-val').text(subtitleSettings.size + 'px');
  1250. applySubtitleSettings();
  1251. syncSettingsPreview();
  1252. saveSubtitleSettings();
  1253. });
  1254. $('#sset-font').on('change', function () {
  1255. subtitleSettings.font = $(this).val();
  1256. ensureEmbeddedFontLoaded(subtitleSettings.font); // no-op for built-in fonts
  1257. applySubtitleSettings();
  1258. syncSettingsPreview();
  1259. saveSubtitleSettings();
  1260. });
  1261. $(document).on('click', '.sset-color', function () {
  1262. subtitleSettings.color = $(this).data('color');
  1263. $('.sset-color, #sset-color-custom').removeClass('active');
  1264. $(this).addClass('active');
  1265. $('#sset-color-custom').val(subtitleSettings.color);
  1266. applySubtitleSettings();
  1267. syncSettingsPreview();
  1268. saveSubtitleSettings();
  1269. });
  1270. $('#sset-color-custom').on('input', function () {
  1271. subtitleSettings.color = $(this).val();
  1272. $('.sset-color').removeClass('active');
  1273. $('#sset-color-custom').addClass('active');
  1274. applySubtitleSettings();
  1275. syncSettingsPreview();
  1276. saveSubtitleSettings();
  1277. });
  1278. }
  1279. // ── Subtitle loading / parsing / display ──────────────────────────────────────
  1280. // Exposed on window so ao_module_openFileSelector can invoke it by name
  1281. window.movieEmbOnSubtitleFile = function (raw) {
  1282. var entry = Array.isArray(raw) ? raw[0] : raw;
  1283. var filePath = (entry && typeof entry === 'object') ? entry.filepath : entry;
  1284. if (!filePath || typeof filePath !== 'string') { return; }
  1285. $.ajax({
  1286. url: MEDIA_API + '?file=' + encodeURIComponent(filePath),
  1287. dataType: 'text',
  1288. success: function (content) {
  1289. var name = filePath.replace(/\\/g, '/').split('/').pop();
  1290. var cues = parseSrt(content);
  1291. var existing = -1;
  1292. loadedSubtitleFiles.forEach(function (sf, i) {
  1293. if (sf.path === filePath) { existing = i; }
  1294. });
  1295. if (existing >= 0) {
  1296. loadedSubtitleFiles[existing].cues = cues;
  1297. activeSubtitleIndex = existing;
  1298. } else {
  1299. loadedSubtitleFiles.push({ path: filePath, name: name, cues: cues });
  1300. activeSubtitleIndex = loadedSubtitleFiles.length - 1;
  1301. }
  1302. showToast('Subtitle loaded: ' + name);
  1303. applyActiveSubtitle(); // a sidecar file replaces any styled track
  1304. updateSubtitleSubmenu();
  1305. },
  1306. error: function () { showToast('Failed to load subtitle file'); }
  1307. });
  1308. };
  1309. function parseSrtTime(t) {
  1310. var m = t.match(/(\d+):(\d+):(\d+)[,.](\d+)/);
  1311. if (!m) { return 0; }
  1312. return parseInt(m[1]) * 3600 + parseInt(m[2]) * 60 + parseInt(m[3]) + parseInt(m[4]) / 1000;
  1313. }
  1314. function parseSrt(content) {
  1315. var cues = [];
  1316. var blocks = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim().split(/\n\n+/);
  1317. blocks.forEach(function (block) {
  1318. var lines = block.split('\n');
  1319. var tcIdx = -1;
  1320. for (var i = 0; i < lines.length; i++) {
  1321. if (lines[i].indexOf('-->') !== -1) { tcIdx = i; break; }
  1322. }
  1323. if (tcIdx < 0) { return; }
  1324. var parts = lines[tcIdx].split('-->');
  1325. if (parts.length < 2) { return; }
  1326. var start = parseSrtTime(parts[0].trim());
  1327. var end = parseSrtTime(parts[1].trim().split(' ')[0]);
  1328. // Strip inline SRT tags like <b>, <i>, <font>, plus any ASS override
  1329. // blocks such as {\an8} or {\pos(x,y)}. ffmpeg's ASS-to-SubRip
  1330. // conversion leaves positioning tags like those behind, so without this
  1331. // they would be shown to the viewer as literal text.
  1332. var text = lines.slice(tcIdx + 1).join('\n').trim()
  1333. .replace(/<[^>]+>/g, '')
  1334. .replace(/\{\\[^}]*\}/g, '')
  1335. .trim();
  1336. if (text) { cues.push({ start: start, end: end, text: text }); }
  1337. });
  1338. return cues;
  1339. }
  1340. function updateSubtitleDisplay() {
  1341. // Styled tracks are drawn by the ASS renderer on its own frame loop
  1342. if (assActive) { $('#subtitle-display').hide(); return; }
  1343. if (activeSubtitleIndex < 0 || !loadedSubtitleFiles[activeSubtitleIndex]) {
  1344. $('#subtitle-display').hide();
  1345. return;
  1346. }
  1347. var currentTime = isTranscodedVideo
  1348. ? (vid.currentTime + transcodeSeekOffset)
  1349. : vid.currentTime;
  1350. var cues = loadedSubtitleFiles[activeSubtitleIndex].cues;
  1351. var found = null;
  1352. for (var i = 0; i < cues.length; i++) {
  1353. if (cues[i].start < subtitleSeekFloor) { continue; } // in flight when we landed
  1354. if (currentTime >= cues[i].start && currentTime <= cues[i].end) { found = cues[i]; break; }
  1355. }
  1356. if (found) {
  1357. $('#subtitle-display').html(escapeHtml(found.text).replace(/\n/g, '<br>')).show();
  1358. } else {
  1359. $('#subtitle-display').hide();
  1360. }
  1361. }
  1362. // ── Embedded subtitle tracks and fonts ────────────────────────────────────────
  1363. // MKV releases usually mux their subtitles (and the fonts they were typeset in)
  1364. // into the container rather than shipping sidecar files. The server lists them
  1365. // and extracts on demand; tracks are converted to SubRip, which keeps the text
  1366. // and timing but drops ASS styling, positioning and karaoke.
  1367. var embeddedSubtitles = []; // [{index, codec, language, title, forced, textual}]
  1368. var embeddedFonts = []; // [{index, filename, mimetype}]
  1369. var embeddedMediaPath = null; // file the two lists above describe
  1370. var embeddedProbeToken = 0; // invalidates in-flight probes on file change
  1371. var embeddedFontFaces = []; // FontFace objects registered for this video
  1372. var embeddedFontsLoaded = {}; // family name -> already fetched
  1373. function resetEmbeddedTracks() {
  1374. embeddedProbeToken++;
  1375. stopAssTrack();
  1376. embeddedSubtitles = [];
  1377. embeddedFonts = [];
  1378. embeddedMediaPath = null;
  1379. // Font families are keyed by attachment ordinal, which means the same name
  1380. // refers to a different font in the next video — drop the old faces.
  1381. embeddedFontFaces.forEach(function (face) {
  1382. try { document.fonts.delete(face); } catch (e) {}
  1383. });
  1384. embeddedFontFaces = [];
  1385. embeddedFontsLoaded = {};
  1386. }
  1387. function loadEmbeddedTrackList(filepath) {
  1388. resetEmbeddedTracks();
  1389. if (!filepath) { return; }
  1390. embeddedMediaPath = filepath;
  1391. var token = embeddedProbeToken;
  1392. fetch(SUBTITLE_API + '?file=' + encodeURIComponent(filepath))
  1393. .then(function (r) { return r.json(); })
  1394. .then(function (info) {
  1395. if (token !== embeddedProbeToken) { return; }
  1396. if (!info || info.error) { return; }
  1397. embeddedSubtitles = info.subtitles || [];
  1398. embeddedFonts = info.fonts || [];
  1399. updateSubtitleSubmenu();
  1400. refreshEmbeddedFontOptions();
  1401. })
  1402. .catch(function () {}); // embedded tracks are a bonus — fail quietly
  1403. }
  1404. function embeddedTrackLabel(track, position) {
  1405. var label = track.title || '';
  1406. if (!label) { label = 'Track ' + (position + 1); }
  1407. if (track.language) { label += ' [' + track.language + ']'; }
  1408. if (track.forced) { label += ' (forced)'; }
  1409. if (!track.textual) { label += ' — image based'; }
  1410. return label;
  1411. }
  1412. // Extraction has to scan the whole container, so it takes a few seconds on a
  1413. // large file. Results are kept in loadedSubtitleFiles, making reselection free.
  1414. function selectEmbeddedSubtitle(track, position) {
  1415. if (!track.textual) {
  1416. showToast('That track is image based and cannot be displayed');
  1417. return;
  1418. }
  1419. var cacheKey = 'embedded#' + track.index + '@' + embeddedMediaPath;
  1420. for (var i = 0; i < loadedSubtitleFiles.length; i++) {
  1421. if (loadedSubtitleFiles[i].path === cacheKey) {
  1422. activeSubtitleIndex = i;
  1423. applyActiveSubtitle();
  1424. updateSubtitleSubmenu();
  1425. return;
  1426. }
  1427. }
  1428. // ASS/SSA is fetched in its native form so the styling survives; everything
  1429. // else comes through as SubRip for the plain renderer.
  1430. var styled = /^(ass|ssa)$/i.test(track.codec) && typeof ASS !== 'undefined';
  1431. var mediaPath = embeddedMediaPath;
  1432. var url = SUBTITLE_API + '?file=' + encodeURIComponent(mediaPath) + '&track=' + track.index
  1433. + (styled ? '&format=ass' : '');
  1434. showToast('Extracting subtitle track…');
  1435. $.ajax({
  1436. url: url,
  1437. dataType: 'text',
  1438. success: function (content) {
  1439. if (mediaPath !== embeddedMediaPath) { return; } // episode changed
  1440. if (styled) {
  1441. var parsed = ASS.parse(content);
  1442. if (!parsed.events.length) {
  1443. showToast('That track contained no readable text');
  1444. return;
  1445. }
  1446. loadedSubtitleFiles.push({
  1447. path: cacheKey,
  1448. name: embeddedTrackLabel(track, position),
  1449. cues: [],
  1450. assTrack: parsed
  1451. });
  1452. activeSubtitleIndex = loadedSubtitleFiles.length - 1;
  1453. applyActiveSubtitle();
  1454. updateSubtitleSubmenu();
  1455. showToast('Subtitle loaded · ' + parsed.events.length + ' styled lines');
  1456. return;
  1457. }
  1458. var cues = parseSrt(content);
  1459. if (cues.length === 0) {
  1460. showToast('That track contained no readable text');
  1461. return;
  1462. }
  1463. loadedSubtitleFiles.push({
  1464. path: cacheKey,
  1465. name: embeddedTrackLabel(track, position),
  1466. cues: cues
  1467. });
  1468. activeSubtitleIndex = loadedSubtitleFiles.length - 1;
  1469. applyActiveSubtitle();
  1470. updateSubtitleSubmenu();
  1471. showToast('Subtitle loaded · ' + cues.length + ' lines');
  1472. },
  1473. error: function () { showToast('Could not extract that subtitle track'); }
  1474. });
  1475. }
  1476. // Switch the display between the styled ASS renderer and the plain SubRip
  1477. // overlay depending on what the newly selected track carries.
  1478. function applyActiveSubtitle() {
  1479. var entry = activeSubtitleIndex >= 0 ? loadedSubtitleFiles[activeSubtitleIndex] : null;
  1480. if (entry && entry.assTrack) {
  1481. startAssTrack(entry.assTrack);
  1482. } else {
  1483. stopAssTrack();
  1484. updateSubtitleDisplay();
  1485. }
  1486. }
  1487. // ── Subtitle seek floor ──────────────────────────────────────────────────────
  1488. // After a seek, any line that had already begun before the landing point is
  1489. // skipped entirely; only lines that start at or after it are shown. Seeking to
  1490. // 1:02 with lines at 1:00-1:03 and 1:05-1:10 therefore shows nothing until 1:05.
  1491. var subtitleSeekFloor = 0;
  1492. function setSubtitleSeekFloor(time) {
  1493. subtitleSeekFloor = Math.max(0, time || 0);
  1494. if (assRenderer) { assRenderer.setSuppressBefore(subtitleSeekFloor); }
  1495. updateSubtitleDisplay();
  1496. }
  1497. function resetSubtitleSeekFloor() { setSubtitleSeekFloor(0); }
  1498. // ── Styled ASS rendering ─────────────────────────────────────────────────────
  1499. // ASS tracks are fetched in their native form and drawn by script/ass.js, which
  1500. // preserves per-line styling and position. That is what makes dual-language
  1501. // releases work: the Japanese and Chinese lines are separate events shown at the
  1502. // same time, and a single-cue renderer can only ever display one of them.
  1503. var assRenderer = null;
  1504. var assActive = false;
  1505. var assFrameReq = null;
  1506. function initAssRenderer() {
  1507. var overlay = document.getElementById('ass-overlay');
  1508. if (overlay && typeof ASS !== 'undefined') { assRenderer = new ASS.Renderer(overlay); }
  1509. }
  1510. // Match the overlay to the letterboxed picture inside the video element, so
  1511. // script coordinates map onto what the viewer actually sees.
  1512. function syncAssOverlayGeometry() {
  1513. if (!assRenderer) { return; }
  1514. var vid = document.getElementById('main-video');
  1515. var overlay = document.getElementById('ass-overlay');
  1516. var cw = vid.clientWidth, ch = vid.clientHeight;
  1517. var vw = vid.videoWidth, vh = vid.videoHeight;
  1518. // Until the decoder reports the picture size there is no way to know where
  1519. // the letterbox bars are. Falling back to the raw element box would scale
  1520. // the script against the black bars too and push bottom-anchored lines down
  1521. // over the controls, so keep the last known good geometry instead.
  1522. if (!(vw > 0 && vh > 0 && cw > 0 && ch > 0)) { return; }
  1523. var scale = Math.min(cw / vw, ch / vh);
  1524. var width = vw * scale;
  1525. var height = vh * scale;
  1526. var left = (cw - width) / 2;
  1527. var top = (ch - height) / 2;
  1528. if (overlay._w !== width || overlay._h !== height || overlay._l !== left || overlay._t !== top) {
  1529. overlay._w = width; overlay._h = height; overlay._l = left; overlay._t = top;
  1530. overlay.style.left = left + 'px';
  1531. overlay.style.top = top + 'px';
  1532. overlay.style.width = width + 'px';
  1533. overlay.style.height = height + 'px';
  1534. assRenderer.resize(width, height);
  1535. }
  1536. }
  1537. function startAssTrack(track) {
  1538. if (!assRenderer) { return; }
  1539. stopAssTrack();
  1540. assRenderer.setTrack(track);
  1541. assActive = true;
  1542. $('#ass-overlay').addClass('active');
  1543. $('#subtitle-display').hide(); // the plain renderer must not double up
  1544. loadAssFonts(track);
  1545. var step = function () {
  1546. if (!assActive) { return; }
  1547. syncAssOverlayGeometry();
  1548. assRenderer.setTime(effectivePlaybackTime());
  1549. assFrameReq = requestAnimationFrame(step);
  1550. };
  1551. step();
  1552. }
  1553. function stopAssTrack() {
  1554. assActive = false;
  1555. if (assFrameReq) { cancelAnimationFrame(assFrameReq); assFrameReq = null; }
  1556. if (assRenderer) { assRenderer.clear(); }
  1557. $('#ass-overlay').removeClass('active');
  1558. }
  1559. // Only pull the fonts the track actually references — a release can attach a
  1560. // dozen and use half of them.
  1561. function loadAssFonts(track) {
  1562. if (typeof ASS === 'undefined') { return; }
  1563. ASS.referencedFonts(track).forEach(function (family) {
  1564. ensureEmbeddedFontLoaded(family);
  1565. });
  1566. }
  1567. // ── Embedded fonts ───────────────────────────────────────────────────────────
  1568. // Registered under the font's own internal family name, which is what ASS styles
  1569. // reference, and offered in Subtitle Settings for SubRip tracks. Fetched lazily:
  1570. // a release can carry a dozen fonts and only a few are ever used.
  1571. function embeddedFontFamily(font) {
  1572. return font.family || ('aroz-embedded-' + font.index);
  1573. }
  1574. function findEmbeddedFontByFamily(family) {
  1575. var wanted = String(family || '').replace(/^@/, '').toLowerCase();
  1576. var found = null;
  1577. embeddedFonts.forEach(function (f) {
  1578. if (embeddedFontFamily(f).toLowerCase() === wanted) { found = f; }
  1579. });
  1580. return found;
  1581. }
  1582. function refreshEmbeddedFontOptions() {
  1583. var $select = $('#sset-font');
  1584. $select.find('optgroup.embedded-fonts').remove();
  1585. if (embeddedFonts.length > 0) {
  1586. var $group = $('<optgroup label="Embedded in this video" class="embedded-fonts"></optgroup>');
  1587. embeddedFonts.forEach(function (font) {
  1588. $group.append($('<option></option>')
  1589. .attr('value', embeddedFontFamily(font))
  1590. .text(font.filename || ('Font ' + (font.index + 1))));
  1591. });
  1592. $select.append($group);
  1593. }
  1594. // A font picked for a previous video may not exist in this one
  1595. var stillOffered = $select.find('option').filter(function () {
  1596. return this.value === subtitleSettings.font;
  1597. }).length > 0;
  1598. if (!stillOffered) {
  1599. subtitleSettings.font = 'system-ui, sans-serif';
  1600. applySubtitleSettings();
  1601. saveSubtitleSettings();
  1602. }
  1603. $select.val(subtitleSettings.font);
  1604. ensureEmbeddedFontLoaded(subtitleSettings.font);
  1605. }
  1606. function ensureEmbeddedFontLoaded(family) {
  1607. if (!family || embeddedFontsLoaded[family] || !embeddedMediaPath) { return; }
  1608. if (typeof FontFace === 'undefined' || !document.fonts) { return; }
  1609. var meta = findEmbeddedFontByFamily(family);
  1610. if (!meta) { return; } // a built-in font, or one this video does not carry
  1611. embeddedFontsLoaded[family] = true; // claim it so we do not refetch in a loop
  1612. var url = SUBTITLE_API + '?file=' + encodeURIComponent(embeddedMediaPath) + '&font=' + meta.index;
  1613. var face = new FontFace(embeddedFontFamily(meta), 'url("' + url + '")');
  1614. face.load().then(function (loaded) {
  1615. document.fonts.add(loaded);
  1616. embeddedFontFaces.push(loaded);
  1617. applySubtitleSettings();
  1618. syncSettingsPreview();
  1619. if (assRenderer) { assRenderer.clear(); } // redraw with the real face
  1620. }).catch(function () {
  1621. embeddedFontsLoaded[family] = false;
  1622. });
  1623. }
  1624. function updateSubtitleSubmenu() {
  1625. $('#ctx-subtitle-sub .ctx-sub-dynamic').remove();
  1626. var disabled = (activeSubtitleIndex < 0);
  1627. $('#ctx-sub-disable')
  1628. .toggleClass('ctx-active', disabled)
  1629. .find('.ctx-icon').text(disabled ? '✓' : '');
  1630. var $load = $('#ctx-sub-load');
  1631. // Tracks muxed into the video, listed whether or not they are loaded yet
  1632. if (embeddedSubtitles.length > 0) {
  1633. $('<div class="ctx-divider ctx-sub-dynamic"></div>').insertBefore($load);
  1634. embeddedSubtitles.forEach(function (track, position) {
  1635. var cacheKey = 'embedded#' + track.index + '@' + embeddedMediaPath;
  1636. var isActive = activeSubtitleIndex >= 0 &&
  1637. loadedSubtitleFiles[activeSubtitleIndex] &&
  1638. loadedSubtitleFiles[activeSubtitleIndex].path === cacheKey;
  1639. $('<div class="ctx-item ctx-sub-dynamic'
  1640. + (isActive ? ' ctx-active' : '')
  1641. + (track.textual ? '' : ' ctx-disabled') + '">'
  1642. + '<i class="ctx-icon">' + (isActive ? '✓' : '') + '</i>'
  1643. + escapeHtml(embeddedTrackLabel(track, position))
  1644. + '</div>')
  1645. .on('click', function () {
  1646. selectEmbeddedSubtitle(track, position);
  1647. $('#player-ctx').hide();
  1648. })
  1649. .insertBefore($load);
  1650. });
  1651. }
  1652. // Sidecar files the user loaded by hand
  1653. var external = [];
  1654. loadedSubtitleFiles.forEach(function (sf, idx) {
  1655. if (String(sf.path).indexOf('embedded#') !== 0) { external.push({ sf: sf, idx: idx }); }
  1656. });
  1657. if (external.length > 0) {
  1658. $('<div class="ctx-divider ctx-sub-dynamic"></div>').insertBefore($load);
  1659. external.forEach(function (entry) {
  1660. var isActive = (entry.idx === activeSubtitleIndex);
  1661. $('<div class="ctx-item ctx-sub-dynamic' + (isActive ? ' ctx-active' : '') + '" data-sub-idx="' + entry.idx + '">'
  1662. + '<i class="ctx-icon">' + (isActive ? '✓' : '') + '</i>'
  1663. + escapeHtml(entry.sf.name)
  1664. + '</div>')
  1665. .on('click', function () {
  1666. activeSubtitleIndex = parseInt($(this).data('sub-idx'), 10);
  1667. applyActiveSubtitle();
  1668. updateSubtitleSubmenu();
  1669. $('#player-ctx').hide();
  1670. })
  1671. .insertBefore($load);
  1672. });
  1673. }
  1674. }
  1675. function initSubtitleMenu() {
  1676. var $ctx = $('#player-ctx');
  1677. var $parent = $('#ctx-subtitle-parent');
  1678. var $sub = $('#ctx-subtitle-sub');
  1679. var subHideTimer;
  1680. function cancelSubHide() { clearTimeout(subHideTimer); }
  1681. function scheduleSubHide() {
  1682. subHideTimer = setTimeout(function () { $sub.hide(); }, 120);
  1683. }
  1684. $parent.on('mouseenter', function () {
  1685. cancelSubHide();
  1686. var ctxRight = $ctx.offset().left + $ctx.outerWidth();
  1687. var containerRight = $('#player-wrap').offset().left + $('#player-wrap').outerWidth();
  1688. if (ctxRight + 200 > containerRight) {
  1689. $sub.css({ left: 'auto', right: '100%' });
  1690. } else {
  1691. $sub.css({ left: '100%', right: 'auto' });
  1692. }
  1693. $sub.show();
  1694. });
  1695. $parent.on('mouseleave', scheduleSubHide);
  1696. $sub.on('mouseenter', cancelSubHide);
  1697. $sub.on('mouseleave', scheduleSubHide);
  1698. $('#ctx-sub-disable').on('click', function () {
  1699. activeSubtitleIndex = -1;
  1700. stopAssTrack();
  1701. $('#subtitle-display').hide();
  1702. updateSubtitleSubmenu();
  1703. $ctx.hide();
  1704. });
  1705. $('#ctx-sub-load').on('click', function () {
  1706. $ctx.hide();
  1707. pickSubtitleFile();
  1708. });
  1709. }
  1710. // Open the ArozOS file selector defaulted to the folder of the playing file
  1711. function pickSubtitleFile() {
  1712. var startDir = 'user:/';
  1713. if (currentFile) {
  1714. var fp = currentFile.filepath.replace(/\\/g, '/');
  1715. var slash = fp.lastIndexOf('/');
  1716. if (slash > 0) { startDir = fp.substring(0, slash); }
  1717. }
  1718. ao_module_openFileSelector(
  1719. window.movieEmbOnSubtitleFile,
  1720. startDir, 'file', false,
  1721. { fnameOverride: 'movieEmbOnSubtitleFile', extAllowed: '.srt' }
  1722. );
  1723. }
  1724. // ── Keyboard shortcuts ────────────────────────────────────────────────────────
  1725. function initKeyboard() {
  1726. $(document).on('keydown', function (e) {
  1727. if ($(e.target).is('input, select, textarea')) { return; }
  1728. switch (e.key) {
  1729. case ' ':
  1730. case 'k':
  1731. e.preventDefault(); togglePlay(); showControls(); break;
  1732. case 'ArrowRight':
  1733. e.preventDefault();
  1734. if (isTranscodedVideo && transcodeDuration > 0 && currentFile) {
  1735. transcodeSeekTo(effectivePlaybackTime() + 10);
  1736. } else {
  1737. vid.currentTime = Math.min(vid.duration || 0, vid.currentTime + 10);
  1738. }
  1739. showControls(); break;
  1740. case 'ArrowLeft':
  1741. e.preventDefault();
  1742. if (isTranscodedVideo && transcodeDuration > 0 && currentFile) {
  1743. transcodeSeekTo(effectivePlaybackTime() - 10);
  1744. } else {
  1745. vid.currentTime = Math.max(0, vid.currentTime - 10);
  1746. }
  1747. showControls(); break;
  1748. case 'ArrowUp':
  1749. e.preventDefault();
  1750. vid.volume = Math.min(1, Math.round((vid.volume + 0.1) * 10) / 10);
  1751. showControls(); break;
  1752. case 'ArrowDown':
  1753. e.preventDefault();
  1754. vid.volume = Math.max(0, Math.round((vid.volume - 0.1) * 10) / 10);
  1755. showControls(); break;
  1756. case 'f':
  1757. case 'F':
  1758. e.preventDefault(); toggleFullscreen(); break;
  1759. case 'm':
  1760. case 'M':
  1761. e.preventDefault(); vid.muted = !vid.muted; break;
  1762. case 'r':
  1763. case 'R':
  1764. e.preventDefault();
  1765. setRepeatSingle(!repeatSingle);
  1766. showToast('Repeat: ' + (repeatSingle ? 'On' : 'Off')); break;
  1767. case 's':
  1768. case 'S':
  1769. e.preventDefault(); toggleSettingsPopup(); break;
  1770. case 'Escape':
  1771. e.preventDefault();
  1772. $('#player-ctx').hide();
  1773. closeSettingsPopup();
  1774. closeVideoInfo();
  1775. closeSubtitleSettings(); break;
  1776. case 'MediaPlayPause':
  1777. e.preventDefault(); togglePlay(); break;
  1778. }
  1779. });
  1780. }
  1781. // ── Init ──────────────────────────────────────────────────────────────────────
  1782. function initMain(){
  1783. initVideoControls();
  1784. initContextMenu();
  1785. initSettingsPopup();
  1786. initScrubPreview();
  1787. initAssRenderer();
  1788. resetSubtitleSeekFloor(); // a freshly opened file starts unsuppressed
  1789. if (currentFile) {
  1790. scheduleStoryboardLoad(currentFile.filepath);
  1791. loadEmbeddedTrackList(currentFile.filepath);
  1792. }
  1793. initSubtitleMenu();
  1794. initSubtitleSettings();
  1795. initKeyboard();
  1796. }
  1797. $(document).ready(function () {
  1798. //Check if there are another instant running. If yes, replace that another instance URL
  1799. if (ao_module_virtualDesktop){
  1800. //If in ao_module mode, try to make this windows the only instance
  1801. if (!ao_module_makeSingleInstance()){
  1802. initMain();
  1803. }
  1804. }else{
  1805. initMain();
  1806. }
  1807. });
  1808. </script>
  1809. </body>
  1810. </html>