| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482 |
- <!DOCTYPE html>
- <meta name="apple-mobile-web-app-capable" content="yes" />
- <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"/>
- <html>
- <head>
- <meta charset="UTF-8">
- <meta name="theme-color" content="#000000">
- <script src="../script/jquery.min.js"></script>
- <script src="../script/ao_module.js"></script>
- <!-- HLS via Media Source, so browsers without native HLS (Firefox,
- Chrome) can play the transcoded playlist without hls.js -->
- <script src="../script/hlsmse.js"></script>
- <script src="backend/common.js"></script>
- <!-- ASS/SSA subtitle parser + renderer (see script/ass.js) -->
- <script src="script/ass.js"></script>
- <style>
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
- :root {
- --accent: #0a84ff;
- --surface: #1c1c1e;
- --surface2: #2c2c2e;
- --text: #f5f5f7;
- --text-sub: #98989d;
- --transition: 0.2s ease;
- --radius: 0.4em;
- }
- html, body { width: 100%; height: 100%; background: #000; overflow: hidden; }
- #player-wrap {
- position: relative;
- width: 100%; height: 100%;
- display: flex; align-items: center; justify-content: center;
- background: #000;
- }
- #main-video {
- width: 100%; height: 100%;
- object-fit: contain; display: block; background: #000;
- }
- /* ── Controls overlay ──────────────────────────────────────────────── */
- #video-controls {
- position: absolute;
- bottom: 0; left: 0; right: 0;
- background: linear-gradient(transparent, rgba(0,0,0,0.85) 100%);
- padding: 40px 14px 12px;
- transition: opacity 0.3s;
- }
- #video-controls.hidden { opacity: 0; pointer-events: none; }
- #player-wrap:has(#video-controls.hidden) { cursor: none; }
- #progress-wrap {
- position: relative;
- height: 4px; background: rgba(255,255,255,0.25);
- border-radius: var(--radius); cursor: pointer; margin-bottom: 12px;
- }
- #progress-wrap:hover { height: 6px; }
- #progress-wrap::before {
- content: ''; position: absolute;
- top: -16px; left: 0; right: 0; height: 16px;
- }
- #progress-bar { height: 100%; border-radius: var(--radius); background: var(--accent); pointer-events: none; }
- #progress-thumb {
- position: absolute; top: 50%; transform: translateY(-50%);
- width: 14px; height: 14px;
- background: #fff; border-radius: 50%; pointer-events: none; display: none;
- }
- #progress-wrap:hover #progress-thumb { display: block; }
- #controls-row { display: flex; align-items: center; gap: 10px; }
- .ctrl-btn {
- background: none; border: none; cursor: pointer;
- color: #fff; padding: 4px; line-height: 1;
- transition: opacity var(--transition); outline: none;
- display: flex; align-items: center; justify-content: center;
- flex-shrink: 0;
- }
- .ctrl-btn:hover { opacity: 0.7; }
- .ctrl-btn img { width: 24px; height: 24px; display: block; }
- .ctrl-cc-icon {
- width: 24px; height: 24px;
- display: flex; align-items: center; justify-content: center;
- font-size: 10px; font-weight: 700; letter-spacing: 0.4px;
- border: 1.5px solid #fff; border-radius: 4px; line-height: 1;
- }
- #volume-wrap { display: flex; align-items: center; gap: 8px; }
- #volume-slider {
- -webkit-appearance: none;
- width: 80px; height: 4px;
- background: rgba(255,255,255,0.3); border-radius: 4px; outline: none; cursor: pointer;
- }
- #volume-slider::-webkit-slider-thumb {
- -webkit-appearance: none;
- width: 12px; height: 12px; background: #fff; border-radius: 50%;
- }
- /* Portrait phones/tablets drive playback volume with the hardware keys,
- so the in-page slider only eats toolbar width. Users who want it back
- can force it on from the settings popup ("Volume bar → Always show"). */
- @media (max-width: 899px) and (orientation: portrait) {
- #volume-slider { display: none; }
- }
- body.always-show-volume #volume-slider { display: block; }
- #time-display {
- font-size: 13px; color: rgba(255,255,255,0.8);
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- margin-left: 4px; white-space: nowrap;
- }
- #spacer { flex: 1; }
- /* ─── ASS subtitle overlay ───────────────────────────────────────────────────── */
- /* Sized in JS to the video's displayed rect so script coordinates land correctly
- regardless of letterboxing. Children are absolutely positioned by the renderer. */
- #ass-overlay {
- display: none;
- position: absolute;
- left: 0; top: 0; width: 0; height: 0;
- pointer-events: none;
- overflow: hidden;
- /* No z-index on purpose: subtitles sit directly after <video> in the DOM,
- so they paint above the (unpositioned) video but below every later
- positioned sibling — scrub preview, controls, menus and modals all stay
- on top of the text instead of being covered by it. */
- /* ...but that only holds if the cues stay *inside* this box. The renderer
- gives each cue an inline z-index so simultaneous lines stack in event
- order (see ass.js boxCss), and a positioned element with z-index:auto is
- not a stacking context — so those cues would otherwise be promoted into
- the player's stacking context and outrank the controls, which are
- themselves z-index:auto. Isolating creates the stacking context that keeps
- cue ordering internal, without giving this layer a z-index of its own. */
- isolation: isolate;
- }
- #ass-overlay.active { display: block; }
- /* ── Scrub-bar hover preview ───────────────────────────────────────── */
- #scrub-preview {
- display: none;
- position: absolute;
- bottom: 100%;
- margin-bottom: 12px;
- transform: translateX(-50%);
- pointer-events: none;
- /* Above the centre play/pause flash, so scrubbing right after a click
- does not put the thumbnail behind it. (ASS cues no longer need
- outranking here — #ass-overlay isolates them.) */
- z-index: 20;
- flex-direction: column;
- align-items: center;
- gap: 6px;
- }
- #scrub-preview.active { display: flex; }
- #scrub-preview-thumb {
- display: none;
- border-radius: 8px;
- background-color: #000;
- background-repeat: no-repeat;
- box-shadow: 0 4px 18px rgba(0,0,0,0.8), 0 0 0 2px rgba(255,255,255,0.14);
- }
- #scrub-preview-thumb.ready { display: block; }
- #scrub-preview-time {
- background: rgba(0,0,0,0.82);
- border-radius: 6px;
- padding: 3px 9px;
- font-size: 12px; font-weight: 600;
- color: #fff; white-space: nowrap;
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- font-variant-numeric: tabular-nums;
- }
- /* ── Transcode-seek freeze frame ───────────────────────────────────── */
- /* Deliberately no z-index: both sit immediately after <video> in the DOM,
- so they paint above the (unpositioned) video but below every later
- positioned sibling — controls and menus stay on top and clickable. */
- #seek-freeze {
- display: none;
- position: absolute; inset: 0;
- width: 100%; height: 100%;
- object-fit: contain;
- background: #000;
- pointer-events: none;
- }
- #seek-spinner {
- display: none;
- position: absolute; inset: 0;
- align-items: center; justify-content: center;
- pointer-events: none;
- }
- #seek-spinner.active { display: flex; }
- .seek-spinner-box {
- display: flex; flex-direction: column;
- align-items: center; gap: 10px;
- background: rgba(0,0,0,0.55);
- backdrop-filter: blur(4px);
- -webkit-backdrop-filter: blur(4px);
- border-radius: 14px;
- padding: 18px 24px;
- font-size: 12px; color: var(--text);
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- }
- .seek-spinner-box .spinner {
- width: 38px; height: 38px;
- border: 3px solid rgba(255,255,255,0.18);
- border-top-color: var(--accent);
- border-radius: 50%;
- animation: seekSpin 0.8s linear infinite;
- }
- @keyframes seekSpin { to { transform: rotate(360deg); } }
- /* ── Subtitle display ──────────────────────────────────────────────── */
- #subtitle-display {
- display: none;
- position: absolute;
- bottom: 72px; left: 50%; transform: translateX(-50%);
- width: 90%; text-align: center;
- pointer-events: none; /* z-index deliberately unset, see #ass-overlay */
- color: #fff; font-size: 22px; font-weight: 500; line-height: 1.45;
- 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);
- }
- /* ── Centre play/pause flash indicator ─────────────────────────────── */
- #play-flash {
- position: absolute;
- top: 50%; left: 50%;
- width: 88px; height: 88px;
- margin: -44px 0 0 -44px;
- border-radius: 50%;
- background: rgba(0,0,0,0.55);
- backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
- display: flex; align-items: center; justify-content: center;
- pointer-events: none;
- opacity: 0; z-index: 18;
- }
- #play-flash img { width: 40px; height: 40px; display: block; }
- #play-flash.flash { animation: playFlash 0.62s ease-out; }
- @keyframes playFlash {
- 0% { opacity: 0; transform: scale(0.68); }
- 18% { opacity: 0.95; transform: scale(0.92); }
- 100% { opacity: 0; transform: scale(1.32); }
- }
- /* ── Resume popup ──────────────────────────────────────────────────── */
- #resume-popup {
- display: none;
- position: absolute; bottom: 90px; right: 20px; z-index: 25;
- background: rgba(22,22,24,0.97); backdrop-filter: blur(16px);
- border-radius: var(--radius); padding: 16px 18px; min-width: 240px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.1);
- animation: slideUpPopup 0.2s ease;
- color: var(--text);
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- }
- #resume-popup.active { display: block; }
- @keyframes slideUpPopup {
- from { opacity: 0; transform: translateY(10px); }
- to { opacity: 1; transform: translateY(0); }
- }
- #resume-popup-title { font-size: 13px; font-weight: 600; margin-bottom: 4px; }
- #resume-popup-sub { font-size: 12px; color: var(--text-sub); margin-bottom: 12px; }
- #resume-popup-btns { display: flex; gap: 8px; }
- .resume-btn {
- flex: 1; padding: 8px; border: none; cursor: pointer;
- border-radius: calc(var(--radius) / 1.6); font-size: 12px; font-weight: 600;
- outline: none; transition: opacity var(--transition);
- }
- .resume-btn:hover { opacity: 0.8; }
- #resume-btn-continue { background: var(--accent); color: #fff; }
- #resume-btn-restart { background: var(--surface2); color: var(--text); }
- /* ── Context menu ──────────────────────────────────────────────────── */
- #player-ctx {
- display: none;
- position: absolute; z-index: 30;
- background: rgba(28,28,30,0.97);
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- border-radius: var(--radius); padding: 4px 0; min-width: 192px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
- user-select: none;
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- }
- .ctx-item {
- padding: 9px 14px; font-size: 13px; cursor: pointer;
- display: flex; align-items: center; gap: 10px;
- color: var(--text); transition: background var(--transition);
- }
- .ctx-item:hover { background: rgba(255,255,255,0.08); }
- .ctx-item.ctx-active { color: var(--accent); }
- .ctx-item.ctx-disabled { opacity: 0.3; pointer-events: none; }
- .ctx-icon { width: 16px; text-align: center; flex-shrink: 0; font-style: normal; }
- img.ctx-icon { height: 16px; opacity: 0.85; display: block; }
- .ctx-divider { height: 1px; background: rgba(255,255,255,0.08); margin: 3px 0; }
- .ctx-has-sub { justify-content: space-between; position: relative; }
- .ctx-sub-arrow { font-style: normal; opacity: 0.55; font-size: 15px; }
- #ctx-subtitle-sub {
- display: none;
- position: absolute; top: 0; left: 100%;
- background: rgba(28,28,30,0.97);
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- border-radius: calc(var(--radius) * 1.5); padding: 4px 0; min-width: 200px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
- z-index: 32;
- overflow-y: auto;
- max-height: 320px;
- }
- #ctx-subtitle-sub::-webkit-scrollbar { width: 8px; }
- #ctx-subtitle-sub::-webkit-scrollbar-track { background: transparent; }
- #ctx-subtitle-sub::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.18); border-radius: 4px; }
- #ctx-subtitle-sub::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.3); }
- /* ── Subtitle settings modal ───────────────────────────────────────── */
- #subtitle-settings-modal {
- display: none;
- position: absolute; top: 50%; left: 50%;
- transform: translate(-50%, -50%);
- z-index: 40;
- background: rgba(18,18,20,0.97);
- backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
- border-radius: calc(var(--radius) / 1.5); padding: 20px 22px 18px; width: 340px;
- box-shadow: 0 8px 40px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.1);
- color: var(--text);
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- }
- #subtitle-settings-modal h3 {
- font-size: 14px; font-weight: 600; margin-bottom: 14px;
- display: flex; align-items: center; justify-content: space-between;
- }
- #sset-close {
- background: none; border: none; cursor: pointer;
- color: var(--text-sub); font-size: 17px; line-height: 1; padding: 0; outline: none;
- }
- #sset-close img { width: 14px; height: 14px; display: block; opacity: 0.55; transition: opacity var(--transition); }
- #sset-close:hover img { opacity: 1; }
- .sset-row {
- display: flex; align-items: center; gap: 10px;
- padding: 8px 0; border-bottom: 1px solid rgba(255,255,255,0.05);
- font-size: 12px;
- }
- .sset-row:last-child { border-bottom: none; }
- .sset-label { color: var(--text-sub); flex-shrink: 0; width: 56px; }
- .sset-seg {
- display: flex; background: var(--surface2);
- border-radius: calc(var(--radius) / 1.6); padding: 2px; gap: 2px; flex: 1;
- }
- .sset-seg-btn {
- flex: 1; padding: 4px 0; font-size: 12px; font-family: inherit;
- border: none; border-radius: calc(var(--radius) / 1.4); cursor: pointer;
- background: transparent; color: var(--text-sub);
- transition: background 0.15s, color 0.15s;
- }
- .sset-seg-btn.active { background: var(--surface); color: var(--text); }
- #sset-size { flex: 1; accent-color: var(--accent); cursor: pointer; }
- #sset-size-val { color: var(--text-sub); font-size: 11px; min-width: 32px; text-align: right; }
- #sset-font {
- flex: 1; background: var(--surface2); color: var(--text);
- border: 1px solid rgba(255,255,255,0.08); border-radius: calc(var(--radius) / 1.6);
- padding: 5px 8px; font-size: 12px; cursor: pointer; outline: none; appearance: auto;
- width: 100%;
- }
- .sset-colors { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; flex: 1; }
- .sset-color {
- width: 22px; height: 22px; border-radius: 50%;
- border: 2px solid transparent; outline: 2px solid transparent;
- cursor: pointer; padding: 0; flex-shrink: 0;
- transition: outline-color 0.15s, transform 0.1s;
- }
- .sset-color:hover { transform: scale(1.12); }
- .sset-color.active { outline-color: var(--text); transform: scale(1.15); }
- #sset-color-custom {
- width: 22px; height: 22px; border-radius: 50%;
- border: 2px solid rgba(255,255,255,0.2); padding: 0;
- cursor: pointer; background: transparent; flex-shrink: 0;
- }
- #sset-color-custom.active { border-color: var(--text); transform: scale(1.15); }
- #sset-preview {
- margin-top: 14px; background: rgba(0,0,0,0.65);
- border-radius: calc(var(--radius) / 1.25); padding: 14px 12px; text-align: center; line-height: 1.4;
- }
- /* ── Video info modal ──────────────────────────────────────────────── */
- #video-info-modal {
- display: none;
- position: absolute; top: 50%; left: 50%;
- transform: translate(-50%, -50%);
- z-index: 40;
- background: rgba(18,18,20,0.97);
- backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
- border-radius: calc(var(--radius) / 1.5); padding: 20px 22px 16px; width: 340px;
- box-shadow: 0 8px 40px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.1);
- color: var(--text);
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- }
- #video-info-modal h3 {
- font-size: 14px; font-weight: 600; margin-bottom: 12px;
- display: flex; align-items: center; justify-content: space-between;
- }
- #video-info-close {
- background: none; border: none; cursor: pointer;
- color: var(--text-sub); font-size: 17px; line-height: 1; padding: 0; outline: none;
- }
- #video-info-close img { width: 14px; height: 14px; display: block; opacity: 0.55; transition: opacity var(--transition); }
- #video-info-close:hover img { opacity: 1; }
- #video-info-tabs {
- display: flex; gap: 3px;
- background: var(--surface2); border-radius: calc(var(--radius) / 1.25); padding: 3px; margin-bottom: 12px;
- }
- .info-tab {
- flex: 1; text-align: center; padding: 5px 0;
- font-size: 12px; font-weight: 500; border-radius: calc(var(--radius) / 1.6); cursor: pointer;
- color: var(--text-sub);
- transition: background var(--transition), color var(--transition);
- }
- .info-tab.active { background: var(--surface); color: var(--text); }
- .info-row {
- display: flex; gap: 8px;
- padding: 5px 0; border-bottom: 1px solid rgba(255,255,255,0.05);
- font-size: 12px; line-height: 1.4;
- }
- .info-row:last-child { border-bottom: none; }
- .info-label { color: var(--text-sub); flex-shrink: 0; width: 110px; }
- .info-value { color: var(--text); word-break: break-all; }
- /* ── Playback settings popup (gear button) ─────────────────────────── */
- #settings-popup {
- display: none;
- position: absolute;
- right: 14px; bottom: 62px;
- z-index: 35;
- background: rgba(28,28,30,0.97);
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- border-radius: calc(var(--radius) * 1.5);
- padding: 6px 0; width: 236px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
- color: var(--text);
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- user-select: none;
- overflow-y: auto;
- max-height: 320px;
- }
- #settings-popup.active { display: block; }
- #settings-popup::-webkit-scrollbar,
- #subtitle-popup::-webkit-scrollbar { width: 8px; }
- #settings-popup::-webkit-scrollbar-track,
- #subtitle-popup::-webkit-scrollbar-track { background: transparent; }
- #settings-popup::-webkit-scrollbar-thumb,
- #subtitle-popup::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.18); border-radius: 4px; }
- #settings-popup::-webkit-scrollbar-thumb:hover,
- #subtitle-popup::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.3); }
- /* ── Subtitle popup (dedicated CC button) ────────────────────────────── */
- #subtitle-popup {
- display: none;
- position: absolute;
- right: 14px; bottom: 62px;
- z-index: 35;
- background: rgba(28,28,30,0.97);
- backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
- border-radius: calc(var(--radius) * 1.5);
- padding: 4px 0; min-width: 220px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
- color: var(--text);
- font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- user-select: none;
- overflow-y: auto;
- max-height: 320px;
- }
- #subtitle-popup.active { display: block; }
- .set-section { padding: 6px 14px 8px; }
- .set-section + .set-section { border-top: 1px solid rgba(255,255,255,0.08); }
- .set-head {
- display: flex; align-items: center; gap: 8px;
- font-size: 11px; font-weight: 600; letter-spacing: 0.3px;
- text-transform: uppercase; color: var(--text-sub);
- margin-bottom: 7px;
- }
- .set-head img { width: 14px; height: 14px; opacity: 0.7; display: block; }
- .set-seg {
- display: flex; background: var(--surface2);
- border-radius: calc(var(--radius) * 1.2); padding: 2px; gap: 2px;
- }
- .set-seg-btn {
- flex: 1; padding: 5px 0; font-size: 12px; font-family: inherit;
- border: none; border-radius: var(--radius); cursor: pointer;
- background: transparent; color: var(--text-sub);
- transition: background 0.15s, color 0.15s; outline: none;
- }
- .set-seg-btn:hover { color: var(--text); }
- .set-seg-btn.active { background: var(--surface); color: var(--text); }
- .speed-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; }
- .speed-btn {
- padding: 5px 0; font-size: 12px; font-family: inherit;
- border: none; border-radius: var(--radius); cursor: pointer;
- background: var(--surface2); color: var(--text-sub);
- transition: background 0.15s, color 0.15s; outline: none;
- }
- .speed-btn:hover { color: var(--text); }
- .speed-btn.active { background: var(--accent); color: #fff; font-weight: 600; }
- .set-link {
- display: flex; align-items: center; gap: 9px;
- padding: 8px 14px; font-size: 13px; cursor: pointer;
- color: var(--text); transition: background var(--transition);
- }
- .set-link:hover { background: rgba(255,255,255,0.08); }
- .set-link img { width: 15px; height: 15px; opacity: 0.8; display: block; }
- /* ── Toast ─────────────────────────────────────────────────────────── */
- #toast {
- position: fixed; bottom: 30px; left: 50%;
- transform: translateX(-50%) translateY(20px);
- background: rgba(30,30,30,0.95); backdrop-filter: blur(8px);
- color: var(--text); padding: 10px 20px; border-radius: 20px;
- font-size: 13px; font-family: -apple-system, BlinkMacSystemFont, sans-serif;
- opacity: 0; transition: opacity 0.3s, transform 0.3s;
- pointer-events: none; z-index: 1000; max-width: min(90vw, 30em);
- text-align: center; line-height: 1.45;
- }
- #toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
- </style>
- </head>
- <body>
- <div id="player-wrap">
- <video id="main-video" preload="metadata"></video>
- <!-- Frozen last frame + spinner, shown while a transcode seek re-buffers.
- Must stay directly after <video> — stacking relies on DOM order. -->
- <canvas id="seek-freeze"></canvas>
- <div id="seek-spinner">
- <div class="seek-spinner-box">
- <div class="spinner"></div>
- <span>Buffering…</span>
- </div>
- </div>
- <!-- Styled ASS/SSA subtitles are drawn here, sized to the video's
- displayed rectangle. The plain #subtitle-display below is used
- for SubRip tracks. -->
- <div id="ass-overlay"></div>
- <!-- Subtitle overlay -->
- <div id="subtitle-display"></div>
- <!-- Centre play/pause flash indicator -->
- <div id="play-flash"><img id="play-flash-icon" src="img/icons/play_white.svg" alt=""></div>
- <!-- Resume popup -->
- <div id="resume-popup">
- <div id="resume-popup-title">Resume playback?</div>
- <div id="resume-popup-sub"></div>
- <div id="resume-popup-btns">
- <button class="resume-btn" id="resume-btn-continue">Resume</button>
- <button class="resume-btn" id="resume-btn-restart">Start over</button>
- </div>
- </div>
- <!-- Context menu -->
- <div id="player-ctx">
- <div class="ctx-item" id="ctx-play"><img class="ctx-icon" src="img/icons/play_white.svg" alt="">Play</div>
- <div class="ctx-item" id="ctx-pause"><img class="ctx-icon" src="img/icons/pause_white.svg" alt="">Pause</div>
- <div class="ctx-divider"></div>
- <div class="ctx-item" id="ctx-repeat"><img class="ctx-icon" src="img/icons/repeat_white.svg" alt="">Repeat: Off</div>
- <div class="ctx-divider"></div>
- <div class="ctx-item ctx-has-sub" id="ctx-subtitle-parent">
- <span>Subtitles</span>
- <i class="ctx-sub-arrow">›</i>
- <div id="ctx-subtitle-sub">
- <div class="ctx-item ctx-active" id="ctx-sub-disable"><i class="ctx-icon">✓</i>Disable</div>
- <div class="ctx-divider"></div>
- <div class="ctx-item" id="ctx-sub-load"><i class="ctx-icon">+</i>Load SRT file…</div>
- </div>
- </div>
- <div class="ctx-divider"></div>
- <div class="ctx-item" id="ctx-subtitle-settings"><img class="ctx-icon" src="img/icons/settings_white.svg" alt="">Subtitle Settings</div>
- <div class="ctx-item" id="ctx-props">Video Properties</div>
- </div>
- <!-- Subtitle settings modal -->
- <div id="subtitle-settings-modal">
- <h3>Subtitle Settings<button id="sset-close" title="Close"><img src="img/icons/close_white.svg" alt=""></button></h3>
- <div class="sset-row">
- <span class="sset-label">Position</span>
- <div class="sset-seg">
- <button class="sset-seg-btn active" data-val="bottom">Bottom</button>
- <button class="sset-seg-btn" data-val="top">Top</button>
- </div>
- </div>
- <div class="sset-row">
- <span class="sset-label">Size</span>
- <input type="range" id="sset-size" min="14" max="52" step="1" value="22">
- <span id="sset-size-val">22px</span>
- </div>
- <div class="sset-row">
- <span class="sset-label">Font</span>
- <select id="sset-font">
- <option value="system-ui, sans-serif">System Default</option>
- <option value="Arial, sans-serif">Arial</option>
- <option value="'Helvetica Neue', Helvetica, sans-serif">Helvetica</option>
- <option value="Georgia, serif">Georgia</option>
- <option value="'Times New Roman', Times, serif">Times New Roman</option>
- <option value="'Courier New', Courier, monospace">Courier New</option>
- <option value="Verdana, sans-serif">Verdana</option>
- <option value="'Trebuchet MS', sans-serif">Trebuchet MS</option>
- <option value="Impact, fantasy">Impact</option>
- </select>
- </div>
- <div class="sset-row">
- <span class="sset-label">Color</span>
- <div class="sset-colors">
- <button class="sset-color active" data-color="#ffffff" style="background:#ffffff" title="White"></button>
- <button class="sset-color" data-color="#ffff00" style="background:#ffff00" title="Yellow"></button>
- <button class="sset-color" data-color="#00ffff" style="background:#00ffff" title="Cyan"></button>
- <button class="sset-color" data-color="#00ff88" style="background:#00ff88" title="Green"></button>
- <button class="sset-color" data-color="#ff8800" style="background:#ff8800" title="Orange"></button>
- <input type="color" id="sset-color-custom" value="#ffffff" title="Custom color">
- </div>
- </div>
- <div id="sset-preview">Sample subtitle text</div>
- </div>
- <!-- Video info / stats modal -->
- <div id="video-info-modal">
- <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>
- <div id="video-info-tabs">
- <div class="info-tab active" onclick="showInfoTab('props')">Properties</div>
- <div class="info-tab" onclick="showInfoTab('stats')">Stats</div>
- </div>
- <div id="video-info-body"></div>
- </div>
- <!-- Playback settings popup -->
- <div id="settings-popup">
- <div class="set-section">
- <div class="set-head"><img src="img/icons/repeat_white.svg" alt="">Repeat</div>
- <div class="set-seg" id="set-repeat-seg">
- <button class="set-seg-btn active" data-repeat="off">Off</button>
- <button class="set-seg-btn" data-repeat="one">Repeat one</button>
- </div>
- </div>
- <div class="set-section">
- <div class="set-head"><img src="img/icons/play_white.svg" alt="">Playback speed</div>
- <div class="speed-grid" id="set-speed-grid">
- <button class="speed-btn" data-speed="0.5">0.5×</button>
- <button class="speed-btn active" data-speed="1">1×</button>
- <button class="speed-btn" data-speed="1.2">1.2×</button>
- <button class="speed-btn" data-speed="1.5">1.5×</button>
- <button class="speed-btn" data-speed="2">2×</button>
- </div>
- </div>
- <div class="set-section">
- <div class="set-head"><img src="img/icons/volume_white.svg" alt="">Volume bar</div>
- <div class="set-seg" id="set-volbar-seg">
- <button class="set-seg-btn active" data-volbar="auto">Auto</button>
- <button class="set-seg-btn" data-volbar="always">Always show</button>
- </div>
- </div>
- <div class="set-section">
- <div class="set-head"><img src="img/icons/movie_white.svg" alt="">Streaming mode</div>
- <div class="set-seg" id="set-stream-seg">
- <button class="set-seg-btn active" data-stream="auto">Auto</button>
- <button class="set-seg-btn" data-stream="mp4">MP4</button>
- <button class="set-seg-btn" data-stream="hls">HLS</button>
- </div>
- </div>
- <div class="set-section" style="padding-left:0;padding-right:0;padding-bottom:2px;">
- <div class="set-link" id="set-video-props">
- <img src="img/icons/menu_white.svg" alt="">Video properties
- </div>
- </div>
- </div>
- <!-- Subtitle popup (dedicated CC button) -->
- <div id="subtitle-popup">
- <div class="ctx-item ctx-active" id="sub-pop-disable"><i class="ctx-icon">✓</i>Disable</div>
- <div class="ctx-divider"></div>
- <div class="ctx-item" id="sub-pop-load"><i class="ctx-icon">+</i>Load SRT file…</div>
- <div class="ctx-divider"></div>
- <div class="set-link" id="sub-pop-settings">
- <img src="img/icons/settings_white.svg" alt="">Subtitle settings
- </div>
- </div>
- <!-- Player controls -->
- <div id="video-controls">
- <div id="progress-wrap">
- <div id="progress-bar" style="width:0%"></div>
- <div id="progress-thumb" style="left:0%"></div>
- <div id="scrub-preview">
- <div id="scrub-preview-thumb"></div>
- <div id="scrub-preview-time">0:00</div>
- </div>
- </div>
- <div id="controls-row">
- <button class="ctrl-btn" id="ctrl-play" title="Play / Pause (Space)">
- <img id="play-icon" src="img/icons/play_white.svg" alt="">
- </button>
- <div id="volume-wrap">
- <button class="ctrl-btn" id="ctrl-mute" title="Mute (M)">
- <img id="mute-icon" src="img/icons/volume_white.svg" alt="">
- </button>
- <input id="volume-slider" type="range" min="0" max="1" step="0.05" value="1">
- </div>
- <span id="time-display">0:00 / 0:00</span>
- <span id="spacer"></span>
- <button class="ctrl-btn" id="ctrl-subtitle" title="Subtitles">
- <span class="ctrl-cc-icon">CC</span>
- </button>
- <button class="ctrl-btn" id="ctrl-settings" title="Playback settings">
- <img src="img/icons/settings_white.svg" alt="">
- </button>
- <button class="ctrl-btn" id="ctrl-fs" title="Fullscreen (F)">
- <img src="img/icons/fullscreen_white.svg" alt="">
- </button>
- </div>
- </div>
- </div><!-- #player-wrap -->
- <div id="toast"></div>
- <script>
- // ── State ─────────────────────────────────────────────────────────────────────
- var vid = document.getElementById('main-video');
- var currentFile = null; // {name, filepath, ext}
- var transcodeSeekOffset = 0; // seconds already streamed before current chunk
- var isTranscodedVideo = false;
- var transcodeDuration = 0; // total duration for transcoded video (from /media/duration/)
- var pendingResumePos = 0;
- var watchSaveInterval = null;
- var controlsTimer = null;
- var repeatSingle = (localStorage.getItem('movie_repeat_one') === '1');
- // Snapped to the nearest preset on load: an earlier build let this be dragged
- // to any value, and the popup highlights presets only.
- // The preset rates offered in the settings popup. Declared here rather than
- // beside setPlaybackSpeed because the initialiser below runs on load, and a
- // `var` further down the file would still be undefined at that point.
- var PLAYBACK_SPEEDS = [0.5, 1, 1.2, 1.5, 2];
- var playbackSpeed = nearestPlaybackSpeed(localStorage.getItem('movie_playback_speed') || '1');
- var alwaysShowVolumeBar = (localStorage.getItem('movie_always_volume_bar') === '1');
- var infoRefreshTimer = null;
- var currentInfoTab = 'props';
- // Subtitle state
- var loadedSubtitleFiles = []; // [{path, name, cues:[{start,end,text}]}]
- var activeSubtitleIndex = -1; // -1 = disabled
- // Subtitle settings (shared with main Movie window via localStorage)
- var subtitleSettings = { position: 'bottom', size: 22, font: 'system-ui, sans-serif', color: '#ffffff' };
- // ── Utilities ─────────────────────────────────────────────────────────────────
- function isWebPlayable(ext) {
- return ['mp4', 'webm', 'ogg'].indexOf(ext) !== -1;
- }
- function formatTime(s) {
- if (isNaN(s) || s < 0) { return '0:00'; }
- var h = Math.floor(s / 3600);
- var m = Math.floor((s % 3600) / 60);
- var sec = Math.floor(s % 60);
- var parts = [];
- if (h > 0) { parts.push(h); }
- parts.push(m);
- parts.push(sec < 10 ? '0' + sec : '' + sec);
- return parts.join(':');
- }
- function escapeHtml(str) {
- if (!str) { return ''; }
- return String(str)
- .replace(/&/g, '&').replace(/</g, '<')
- .replace(/>/g, '>').replace(/"/g, '"');
- }
- // Flash a large play/pause glyph in the centre of the video so the user gets
- // immediate feedback that their click / key press registered.
- function flashPlayState(isPlaying) {
- var $f = $('#play-flash');
- $('#play-flash-icon').attr('src',
- isPlaying ? 'img/icons/play_white.svg' : 'img/icons/pause_white.svg');
- $f.removeClass('flash');
- void $f[0].offsetWidth; // force reflow so the animation restarts
- $f.addClass('flash');
- }
- var toastTimer;
- function showToast(msg) {
- clearTimeout(toastTimer);
- $('#toast').text(msg).addClass('show');
- toastTimer = setTimeout(function () { $('#toast').removeClass('show'); }, 2800);
- }
- // play() returns a promise that rejects when the browser will not start the
- // media — most commonly NotSupportedError on Safari, which refuses a transcoded
- // stream because the endpoint cannot answer byte-range requests. Left
- // unhandled it only shows up as an unhandled rejection in the console, so the
- // player just sits there with no explanation. Surface it instead.
- function playVideo(v) {
- var p = v.play();
- if (p && typeof p.catch === 'function') {
- p.catch(function (err) {
- if (err && err.name === 'AbortError') {
- // Fired whenever a load or a new src interrupts a pending
- // play() — routine during seek-by-reload, not a failure.
- return;
- }
- if (err && err.name === 'NotSupportedError') {
- showToast('This browser cannot play this transcoded format. Try Chrome or Firefox.');
- } else {
- showToast('Playback failed: ' + ((err && err.message) || 'unknown error'));
- }
- });
- }
- return p;
- }
- // ── File loading ──────────────────────────────────────────────────────────────
- var files = ao_module_loadInputFiles();
- if (files && files.length > 0) {
- currentFile = {
- name: files[0].filename,
- filepath: files[0].filepath,
- ext: files[0].filename.split('.').pop().toLowerCase()
- };
- ao_module_setWindowTitle('Movie – ' + currentFile.name);
- vid.autoplay = true;
- // The extension only says the container might be playable; the codec inside
- // decides. An .mp4 holding HEVC or 10-bit H.264 has to be transcoded.
- resolveDirectPlay(currentFile.filepath, currentFile.ext, function (directPlay) {
- beginFileStream(directPlay);
- });
- }
- // Bind the video element to the right stream and arm the resume prompt. Also
- // the retry target when direct playback turns out to fail anyway.
- function beginFileStream(directPlay) {
- if (!currentFile) { return; }
- clearDirectPlaybackWatch(vid);
- detachTranscodeStream(vid);
- isTranscodedVideo = !directPlay;
- transcodeSeekOffset = 0;
- transcodeDuration = 0;
- if (directPlay) {
- vid.src = MEDIA_API + '?file=' + encodeURIComponent(currentFile.filepath);
- vid.load();
- // Last resort: a browser without the platform decoder the probe assumed
- onDirectPlaybackFailure(vid, function () {
- showToast('This browser cannot decode that file — switching to a transcode');
- beginFileStream(false);
- });
- } else if (!attachTranscodeStream(vid, transcodeStreamURL(currentFile.filepath, 0),
- function (reason) { showToast(reason); })) {
- showToast('This browser cannot play the transcoded stream. Switch streaming mode to MP4 in settings.');
- return;
- }
- armResumePrompt();
- }
- // Offer to resume where the viewer left off. Direct playback learns its length
- // from the element; a transcode has to ask the server for it.
- function armResumePrompt() {
- if (!currentFile) { return; }
- if (!isTranscodedVideo) {
- $(vid).off('loadedmetadata.resume').one('loadedmetadata.resume', function () {
- if (vid.duration > 3600 && currentFile) {
- ao_module_agirun(SCRIPT_GET_WATCHTIME, { filepath: currentFile.filepath }, function (data) {
- if (data && !data.error && data.position > 30 && data.position < vid.duration * 0.95) {
- showResumePopup(data.position, vid.duration);
- }
- });
- }
- });
- return;
- }
- // Fetch total duration separately (transcode stream doesn't expose it)
- $(vid).off('loadedmetadata.resume');
- fetch(ao_root + 'media/duration/?file=' + encodeURIComponent(currentFile.filepath))
- .then(function (r) { return r.json(); })
- .then(function (data) {
- if (data.duration > 0) {
- transcodeDuration = data.duration;
- if (transcodeDuration > 3600 && currentFile) {
- ao_module_agirun(SCRIPT_GET_WATCHTIME, { filepath: currentFile.filepath }, function (wdata) {
- if (wdata && !wdata.error && wdata.position > 30 && wdata.position < transcodeDuration * 0.95) {
- showResumePopup(wdata.position, transcodeDuration);
- }
- });
- }
- }
- }).catch(function () {});
- }
- // ── Scrub-bar hover preview (storyboard) ──────────────────────────────────────
- // The server renders one sprite sheet per file holding a downscaled frame every
- // few seconds; we fetch it once and keep it in memory, so hovering the timeline
- // costs nothing. Asking ffmpeg for a frame per hover would be hopeless on a
- // software-decoded H.265 source, which is exactly where previews matter most.
- var storyboard = null; // layout from the server + the loaded sheet URL
- var storyboardToken = 0; // invalidates in-flight loads when the file changes
- var storyboardTimer = null;
- function resetStoryboard() {
- storyboardToken++;
- storyboard = null;
- clearTimeout(storyboardTimer);
- storyboardTimer = null;
- $('#scrub-preview-thumb').removeClass('ready');
- hideScrubPreview();
- }
- // Building the sheet runs ffmpeg, so hold off briefly and let playback (and any
- // transcode) get established before adding more load.
- function scheduleStoryboardLoad(filepath) {
- resetStoryboard();
- if (!filepath) { return; }
- var token = storyboardToken;
- storyboardTimer = setTimeout(function () { loadStoryboard(filepath, token); }, 3000);
- }
- function loadStoryboard(filepath, token) {
- var base = STORYBOARD_API + '?file=' + encodeURIComponent(filepath);
- fetch(base)
- .then(function (r) { return r.json(); })
- .then(function (meta) {
- if (token !== storyboardToken) { return; } // switched file while loading
- if (!meta || meta.error || !meta.interval || !meta.tileWidth) { return; }
- var img = new Image();
- img.onload = function () {
- if (token !== storyboardToken) { return; }
- meta.url = img.src;
- storyboard = meta;
- };
- img.src = base + '&image=1';
- })
- .catch(function () {}); // previews are optional — stay silent on failure
- }
- // Whole-file duration, whichever playback mode is active
- function scrubTotalDuration() {
- if (isTranscodedVideo) { return transcodeDuration; }
- return vid.duration || 0;
- }
- function initScrubPreview() {
- var $wrap = $('#progress-wrap');
- $wrap.on('mousemove', function (e) {
- var total = scrubTotalDuration();
- var rect = this.getBoundingClientRect();
- if (!total || !isFinite(total) || rect.width <= 0) { hideScrubPreview(); return; }
- var ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
- showScrubPreview(ratio * total, ratio, rect.width);
- });
- $wrap.on('mouseleave', hideScrubPreview);
- }
- function showScrubPreview(time, ratio, barWidth) {
- $('#scrub-preview-time').text(formatTime(time));
- var $thumb = $('#scrub-preview-thumb');
- var halfWidth;
- if (storyboard && storyboard.url) {
- var idx = Math.max(0, Math.min(storyboard.count - 1,
- Math.floor(time / storyboard.interval)));
- var col = idx % storyboard.cols;
- var row = Math.floor(idx / storyboard.cols);
- $thumb.addClass('ready').css({
- 'width': storyboard.tileWidth + 'px',
- 'height': storyboard.tileHeight + 'px',
- 'background-image': 'url("' + storyboard.url + '")',
- 'background-position': (-col * storyboard.tileWidth) + 'px '
- + (-row * storyboard.tileHeight) + 'px'
- });
- halfWidth = storyboard.tileWidth / 2;
- } else {
- // Sheet not ready (or unavailable) — the timestamp alone is still useful
- $thumb.removeClass('ready');
- halfWidth = 28;
- }
- // Keep the popup within the bar rather than letting it hang off an edge
- var x = Math.max(halfWidth, Math.min(barWidth - halfWidth, ratio * barWidth));
- $('#scrub-preview').css('left', x + 'px').addClass('active');
- }
- function hideScrubPreview() { $('#scrub-preview').removeClass('active'); }
- // ── Transcode seek (seek-by-reload) ───────────────────────────────────────────
- // Formats the browser can't decode are streamed through ffmpeg, so "seeking"
- // means restarting the transcode at a new offset. Replacing .src blanks the
- // <video> to black until the first frame of the new segment arrives, which can
- // take seconds. Freeze the last painted frame under a spinner instead, and only
- // reveal the live element once it is genuinely playing again.
- var seekFreezeTimer = null;
- function showSeekFreeze() {
- var canvas = document.getElementById('seek-freeze');
- if (canvas && vid.videoWidth > 0 && vid.videoHeight > 0) {
- canvas.width = vid.videoWidth;
- canvas.height = vid.videoHeight;
- try {
- canvas.getContext('2d').drawImage(vid, 0, 0, canvas.width, canvas.height);
- $(canvas).show();
- } catch (e) {
- // No decodable frame right now (e.g. seeking again mid-buffer) —
- // leave whatever is already frozen on screen rather than flashing black.
- }
- }
- $('#seek-spinner').addClass('active');
- clearTimeout(seekFreezeTimer);
- // Safety net: a stalled transcode must never leave the overlay stuck on
- seekFreezeTimer = setTimeout(hideSeekFreeze, 30000);
- }
- function hideSeekFreeze() {
- clearTimeout(seekFreezeTimer);
- seekFreezeTimer = null;
- $('#seek-freeze').hide();
- $('#seek-spinner').removeClass('active');
- }
- // Seek to `seconds` (absolute, whole-file time), clamped to the known duration.
- //
- // An HLS stream keeps every segment produced so far in its playlist, so a seek
- // landing inside the transcoded window is an ordinary <video> seek — no reload,
- // no re-transcode, no black frame. Only a seek past that window (or an MP4
- // stream, which has no seekable history at all) has to restart the transcode at
- // the new offset.
- // Restarting the transcode this close to the end of the file would leave ffmpeg
- // with nothing to encode, and the request comes back with no playable stream at
- // all — so a scrub to the very end lands just short of it instead.
- var TRANSCODE_SEEK_TAIL = 5;
- function transcodeSeekTo(seconds) {
- if (!currentFile) { return; }
- var pos = Math.max(0, seconds);
- if (transcodeDuration > 0) {
- pos = Math.min(Math.max(0, transcodeDuration - TRANSCODE_SEEK_TAIL), pos);
- }
- if (usingHLS() && seekWithinTranscodedWindow(vid, pos)) {
- setSubtitleSeekFloor(pos);
- vid.currentTime = pos - transcodeSeekOffset;
- playVideo(vid);
- return;
- }
- showSeekFreeze();
- setSubtitleSeekFloor(pos);
- transcodeSeekOffset = pos;
- // The freeze frame stays up until the new stream is bound: attaching a
- // playlist waits on the server to start the transcode, so playback resumes
- // from the onReady callback rather than immediately.
- if (!attachTranscodeStream(vid, transcodeStreamURL(currentFile.filepath, pos),
- function (reason) { hideSeekFreeze(); showToast(reason); },
- function () { playVideo(vid); })) {
- hideSeekFreeze();
- showToast('This browser cannot play the HLS stream. Switch streaming mode to MP4 in settings.');
- }
- }
- // Whether `pos` (absolute time) falls inside what the current stream has
- // already produced and can therefore be reached without reloading.
- function seekWithinTranscodedWindow(videoEl, pos) {
- var relative = pos - transcodeSeekOffset;
- if (relative < 0) { return false; }
- if (!videoEl.seekable || videoEl.seekable.length === 0) { return false; }
- var available = videoEl.seekable.end(videoEl.seekable.length - 1);
- // Stay a segment clear of the live edge; seeking right onto it stalls until
- // the next segment lands.
- return relative <= available - 4;
- }
- // ─── HLS stream recovery ──────────────────────────────────────────────────────
- // An HLS transcode lives on the server, and it can disappear from under the
- // player: reaped after a long pause, retired when the same player asked for a
- // different offset, or lost with a restart. The next segment then 404s and the
- // element reports a decode error, which leaves a black frame and no way back.
- // Re-open the stream where it stopped instead.
- var streamRecoveryAttempts = 0;
- var STREAM_RECOVERY_LIMIT = 3; // consecutive tries before giving up
- function recoverTranscodeStream() {
- if (!isTranscodedVideo || !usingHLS() || !currentFile) { return; }
- // A file that genuinely cannot be transcoded fails every time; retrying it
- // forever would replace one dead player with a flickering one.
- if (streamRecoveryAttempts >= STREAM_RECOVERY_LIMIT) { return; }
- streamRecoveryAttempts++;
- var resumeAt = effectivePlaybackTime();
- showSeekFreeze();
- transcodeSeekOffset = resumeAt;
- attachTranscodeStream(vid, transcodeStreamURL(currentFile.filepath, resumeAt),
- function (reason) { hideSeekFreeze(); showToast(reason); },
- function () { playVideo(vid); });
- }
- // Current playback position in whole-file terms (transcode streams restart at 0)
- function effectivePlaybackTime() {
- return isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
- }
- // ── Scrub-bar hover preview (storyboard) ──────────────────────────────────────
- // The server renders one sprite sheet per file holding a downscaled frame every
- // few seconds; we fetch it once and keep it in memory, so hovering the timeline
- // costs nothing. Asking ffmpeg for a frame per hover would be hopeless on a
- // software-decoded H.265 source, which is exactly where previews matter most.
- var storyboard = null; // layout from the server + the loaded sheet URL
- var storyboardToken = 0; // invalidates in-flight loads when the file changes
- var storyboardTimer = null;
- function resetStoryboard() {
- storyboardToken++;
- storyboard = null;
- clearTimeout(storyboardTimer);
- storyboardTimer = null;
- $('#scrub-preview-thumb').removeClass('ready');
- hideScrubPreview();
- }
- // Building the sheet runs ffmpeg, so hold off briefly and let playback (and any
- // transcode) get established before adding more load.
- function scheduleStoryboardLoad(filepath) {
- resetStoryboard();
- if (!filepath) { return; }
- var token = storyboardToken;
- storyboardTimer = setTimeout(function () { loadStoryboard(filepath, token); }, 3000);
- }
- function loadStoryboard(filepath, token) {
- var base = STORYBOARD_API + '?file=' + encodeURIComponent(filepath);
- fetch(base)
- .then(function (r) { return r.json(); })
- .then(function (meta) {
- if (token !== storyboardToken) { return; } // switched file while loading
- if (!meta || meta.error || !meta.interval || !meta.tileWidth) { return; }
- var img = new Image();
- img.onload = function () {
- if (token !== storyboardToken) { return; }
- meta.url = img.src;
- storyboard = meta;
- };
- img.src = base + '&image=1';
- })
- .catch(function () {}); // previews are optional — stay silent on failure
- }
- // Whole-file duration, whichever playback mode is active
- function scrubTotalDuration() {
- if (isTranscodedVideo) { return transcodeDuration; }
- return vid.duration || 0;
- }
- function initScrubPreview() {
- var $wrap = $('#progress-wrap');
- $wrap.on('mousemove', function (e) {
- var total = scrubTotalDuration();
- var rect = this.getBoundingClientRect();
- if (!total || !isFinite(total) || rect.width <= 0) { hideScrubPreview(); return; }
- var ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
- showScrubPreview(ratio * total, ratio, rect.width);
- });
- $wrap.on('mouseleave', hideScrubPreview);
- }
- function showScrubPreview(time, ratio, barWidth) {
- $('#scrub-preview-time').text(formatTime(time));
- var $thumb = $('#scrub-preview-thumb');
- var halfWidth;
- if (storyboard && storyboard.url) {
- var idx = Math.max(0, Math.min(storyboard.count - 1,
- Math.floor(time / storyboard.interval)));
- var col = idx % storyboard.cols;
- var row = Math.floor(idx / storyboard.cols);
- $thumb.addClass('ready').css({
- 'width': storyboard.tileWidth + 'px',
- 'height': storyboard.tileHeight + 'px',
- 'background-image': 'url("' + storyboard.url + '")',
- 'background-position': (-col * storyboard.tileWidth) + 'px '
- + (-row * storyboard.tileHeight) + 'px'
- });
- halfWidth = storyboard.tileWidth / 2;
- } else {
- // Sheet not ready (or unavailable) — the timestamp alone is still useful
- $thumb.removeClass('ready');
- halfWidth = 28;
- }
- // Keep the popup within the bar rather than letting it hang off an edge
- var x = Math.max(halfWidth, Math.min(barWidth - halfWidth, ratio * barWidth));
- $('#scrub-preview').css('left', x + 'px').addClass('active');
- }
- function hideScrubPreview() { $('#scrub-preview').removeClass('active'); }
- // ── Transcode seek (seek-by-reload) ───────────────────────────────────────────
- // Formats the browser can't decode are streamed through ffmpeg, so "seeking"
- // means restarting the transcode at a new offset. Replacing .src blanks the
- // <video> to black until the first frame of the new segment arrives, which can
- // take seconds. Freeze the last painted frame under a spinner instead, and only
- // reveal the live element once it is genuinely playing again.
- var seekFreezeTimer = null;
- function showSeekFreeze() {
- var canvas = document.getElementById('seek-freeze');
- if (canvas && vid.videoWidth > 0 && vid.videoHeight > 0) {
- canvas.width = vid.videoWidth;
- canvas.height = vid.videoHeight;
- try {
- canvas.getContext('2d').drawImage(vid, 0, 0, canvas.width, canvas.height);
- $(canvas).show();
- } catch (e) {
- // No decodable frame right now (e.g. seeking again mid-buffer) —
- // leave whatever is already frozen on screen rather than flashing black.
- }
- }
- $('#seek-spinner').addClass('active');
- clearTimeout(seekFreezeTimer);
- // Safety net: a stalled transcode must never leave the overlay stuck on
- seekFreezeTimer = setTimeout(hideSeekFreeze, 30000);
- }
- function hideSeekFreeze() {
- clearTimeout(seekFreezeTimer);
- seekFreezeTimer = null;
- $('#seek-freeze').hide();
- $('#seek-spinner').removeClass('active');
- }
- // Restart the transcode stream at `seconds`, holding the last frame until the
- // new segment plays. Clamped to the known duration.
- function transcodeSeekTo(seconds) {
- if (!currentFile) { return; }
- var pos = Math.max(0, seconds);
- if (transcodeDuration > 0) { pos = Math.min(transcodeDuration, pos); }
- showSeekFreeze();
- setSubtitleSeekFloor(pos);
- transcodeSeekOffset = pos;
- vid.src = TRANSCODE_API + '?file=' + encodeURIComponent(currentFile.filepath)
- + '&start=' + pos.toFixed(3);
- vid.load();
- vid.play();
- }
- // Current playback position in whole-file terms (transcode streams restart at 0)
- function effectivePlaybackTime() {
- return isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
- }
- // ── Video controls ────────────────────────────────────────────────────────────
- function initVideoControls() {
- var $prog = $('#progress-bar');
- var $thumb = $('#progress-thumb');
- var $time = $('#time-display');
- // Restore saved volume
- var savedVol = parseFloat(localStorage.getItem('movie_volume'));
- if (!isNaN(savedVol) && savedVol >= 0 && savedVol <= 1) {
- vid.volume = savedVol;
- $('#volume-slider').val(savedVol);
- }
- if (localStorage.getItem('movie_muted') === '1') { vid.muted = true; }
- $('#ctrl-play').on('click', togglePlay);
- $(vid).on('click', togglePlay);
- $('#ctrl-mute').on('click', function () { vid.muted = !vid.muted; updateMuteIcon(); });
- $('#volume-slider').on('input', function () {
- vid.volume = parseFloat($(this).val());
- updateMuteIcon();
- });
- $('#ctrl-fs').on('click', toggleFullscreen);
- // Progress bar — seek-by-reload for transcoded streams
- $('#progress-wrap').on('click', function (e) {
- if (isTranscodedVideo && transcodeDuration > 0 && currentFile) {
- transcodeSeekTo((e.offsetX / $(this).width()) * transcodeDuration);
- return;
- }
- if (vid.duration) {
- vid.currentTime = (e.offsetX / $(this).width()) * vid.duration;
- }
- });
- // Progress + subtitle update on timeupdate
- $(vid).on('timeupdate', function () {
- updateSubtitleDisplay();
- if (isTranscodedVideo) {
- var displayTime = vid.currentTime + transcodeSeekOffset;
- if (transcodeDuration > 0) {
- var pct = (displayTime / transcodeDuration) * 100;
- $prog.css('width', pct + '%');
- $thumb.css('left', 'calc(' + pct + '% - 7px)');
- $time.text(formatTime(displayTime) + ' / ' + formatTime(transcodeDuration));
- } else {
- $time.text(formatTime(displayTime) + ' / --:--');
- }
- return;
- }
- if (!vid.duration) { return; }
- var pct = (vid.currentTime / vid.duration) * 100;
- $prog.css('width', pct + '%');
- $thumb.css('left', 'calc(' + pct + '% - 7px)');
- $time.text(formatTime(vid.currentTime) + ' / ' + formatTime(vid.duration));
- });
- $(vid).on('play', function () {
- $('#play-icon').attr('src', 'img/icons/pause_white.svg');
- if (watchSaveInterval) { clearInterval(watchSaveInterval); }
- watchSaveInterval = setInterval(function () {
- var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
- if (!vid.paused && effectiveDuration > 3600) { saveWatchPosition(); }
- }, 30000);
- });
- $(vid).on('pause', function () {
- $('#play-icon').attr('src', 'img/icons/play_white.svg');
- if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
- var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
- var effectiveTime = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
- if (effectiveDuration > 3600 && effectiveTime > 30) { saveWatchPosition(); }
- showControls();
- });
- $(vid).on('ended', function () {
- clearWatchPosition();
- if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
- if (!repeatSingle) { return; }
- if (isTranscodedVideo && transcodeSeekOffset > 0 && currentFile) {
- // The stream started part-way in — restart it from the beginning
- transcodeSeekTo(0);
- } else {
- vid.currentTime = 0;
- playVideo(vid);
- }
- });
- $(vid).on('volumechange', function () {
- updateMuteIcon();
- localStorage.setItem('movie_volume', vid.volume);
- localStorage.setItem('movie_muted', vid.muted ? '1' : '0');
- });
- // Drop the transcode-seek freeze frame the moment the new segment is live.
- // 'playing' is the accurate signal; 'loadeddata' covers a seek made while
- // paused (where 'playing' never fires), and 'error' avoids a stuck overlay.
- // Any seek — native or transcode reload — re-bases the subtitle floor
- $(vid).on('seeking', function () { setSubtitleSeekFloor(effectivePlaybackTime()); });
- $(vid).on('playing', function () {
- hideSeekFreeze();
- streamRecoveryAttempts = 0; // the stream is healthy again
- });
- $(vid).on('loadeddata', function () { if (vid.paused) { hideSeekFreeze(); } });
- $(vid).on('error', function () {
- hideSeekFreeze();
- recoverTranscodeStream();
- });
- // Auto-hide controls on mouse movement
- $('#player-wrap').on('mousemove touchstart', showControls);
- document.addEventListener('fullscreenchange', function () {
- if (!document.fullscreenElement) { showControls(); }
- });
- }
- function updateMuteIcon() {
- var isMuted = vid.muted || vid.volume === 0;
- $('#mute-icon').attr('src', isMuted ? 'img/icons/mute_white.svg' : 'img/icons/volume_white.svg');
- $('#volume-slider').val(vid.muted ? 0 : vid.volume);
- }
- function togglePlay() {
- $('#resume-popup').removeClass('active');
- var willPlay = vid.paused;
- if (willPlay) { playVideo(vid); } else { vid.pause(); }
- flashPlayState(willPlay);
- }
- function showControls() {
- $('#video-controls').removeClass('hidden');
- clearTimeout(controlsTimer);
- controlsTimer = setTimeout(function () {
- // Keep the bar up while a popup is open — both are anchored to it
- if (!vid.paused && !$('#settings-popup').hasClass('active') && !$('#subtitle-popup').hasClass('active')) {
- $('#video-controls').addClass('hidden');
- }
- }, 3000);
- }
- function toggleFullscreen() {
- var el = document.getElementById('player-wrap');
- if (!document.fullscreenElement) {
- (el.requestFullscreen || el.webkitRequestFullscreen || el.mozRequestFullScreen).call(el);
- } else {
- (document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen).call(document);
- }
- }
- // ── Watch position (resume) ───────────────────────────────────────────────────
- function saveWatchPosition() {
- if (!currentFile) { return; }
- var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
- var effectiveTime = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
- if (!effectiveDuration || effectiveDuration < 3600 || effectiveTime < 10) { return; }
- ao_module_agirun(SCRIPT_SET_WATCHTIME, {
- filepath: currentFile.filepath,
- position: Math.floor(effectiveTime),
- duration: Math.floor(effectiveDuration)
- }, function () {}, function () {});
- }
- function clearWatchPosition() {
- if (!currentFile) { return; }
- ao_module_agirun(SCRIPT_SET_WATCHTIME,
- { filepath: currentFile.filepath, position: 0, duration: 0 },
- function () {}, function () {});
- }
- function showResumePopup(savedPos, duration) {
- vid.pause();
- pendingResumePos = savedPos;
- $('#resume-popup-sub').text(
- 'Last position: ' + formatTime(savedPos) + ' of ' + formatTime(duration)
- );
- $('#resume-popup').addClass('active');
- showControls();
- $('#resume-btn-continue').off('click').on('click', function () {
- if (isTranscodedVideo && currentFile) {
- transcodeSeekTo(pendingResumePos);
- } else {
- vid.currentTime = pendingResumePos;
- playVideo(vid);
- }
- $('#resume-popup').removeClass('active');
- });
- $('#resume-btn-restart').off('click').on('click', function () {
- playVideo(vid);
- $('#resume-popup').removeClass('active');
- });
- }
- // ── Context menu ──────────────────────────────────────────────────────────────
- function initContextMenu() {
- var $ctx = $('#player-ctx');
- $('#player-wrap').on('contextmenu', function (e) {
- e.preventDefault();
- if (!currentFile) { return; }
- $('#ctx-play').toggleClass('ctx-disabled', !vid.paused);
- $('#ctx-pause').toggleClass('ctx-disabled', vid.paused);
- $('#ctx-repeat')
- .toggleClass('ctx-active', repeatSingle)
- .html('<img class="ctx-icon" src="img/icons/'
- + (repeatSingle ? 'repeat_one_white.svg' : 'repeat_white.svg')
- + '" alt="">Repeat: ' + (repeatSingle ? 'On' : 'Off'));
- $('#ctx-subtitle-sub').hide();
- closeSettingsPopup();
- closeSubtitlePopup();
- var rect = this.getBoundingClientRect();
- var x = e.clientX - rect.left;
- var y = e.clientY - rect.top;
- $ctx.css({ left: x, top: y, display: 'block' });
- var mw = $ctx.outerWidth(), mh = $ctx.outerHeight();
- if (x + mw > rect.width) { $ctx.css('left', Math.max(0, x - mw)); }
- if (y + mh > rect.height) { $ctx.css('top', Math.max(0, y - mh)); }
- showControls();
- });
- $(document).on('mousedown.ctx', function (e) {
- if (!$(e.target).closest('#player-ctx').length) { $ctx.hide(); }
- });
- $('#ctx-play').on('click', function () { playVideo(vid); flashPlayState(true); $ctx.hide(); });
- $('#ctx-pause').on('click', function () { vid.pause(); flashPlayState(false); $ctx.hide(); });
- $('#ctx-repeat').on('click', function () { setRepeatSingle(!repeatSingle); $ctx.hide(); });
- $('#ctx-subtitle-settings').on('click', function () { $ctx.hide(); openSubtitleSettings(); });
- $('#ctx-props').on('click', function () { $ctx.hide(); openVideoInfo('props'); });
- }
- // ── Playback settings popup (gear button) ─────────────────────────────────────
- function setAlwaysShowVolumeBar(on) {
- alwaysShowVolumeBar = !!on;
- localStorage.setItem('movie_always_volume_bar', alwaysShowVolumeBar ? '1' : '0');
- $('body').toggleClass('always-show-volume', alwaysShowVolumeBar);
- $('#set-volbar-seg .set-seg-btn').removeClass('active')
- .filter('[data-volbar="' + (alwaysShowVolumeBar ? 'always' : 'auto') + '"]').addClass('active');
- }
- function setRepeatSingle(on) {
- repeatSingle = !!on;
- vid.loop = false; // handled manually in the 'ended' handler
- localStorage.setItem('movie_repeat_one', repeatSingle ? '1' : '0');
- $('#set-repeat-seg .set-seg-btn').removeClass('active')
- .filter('[data-repeat="' + (repeatSingle ? 'one' : 'off') + '"]').addClass('active');
- }
- function setPlaybackSpeed(rate) {
- playbackSpeed = parseFloat(rate) || 1;
- vid.playbackRate = playbackSpeed;
- localStorage.setItem('movie_playback_speed', String(playbackSpeed));
- $('#set-speed-grid .speed-btn').removeClass('active')
- .filter('[data-speed="' + playbackSpeed + '"]').addClass('active');
- }
- // Snap an arbitrary stored rate onto the nearest preset, so the popup always
- // has exactly one button highlighted. Needed because an earlier build persisted
- // free-form rates from a drag slider.
- function nearestPlaybackSpeed(rate) {
- var value = parseFloat(rate);
- if (!value || value <= 0) { return 1; }
- return PLAYBACK_SPEEDS.reduce(function (best, preset) {
- return Math.abs(preset - value) < Math.abs(best - value) ? preset : best;
- }, PLAYBACK_SPEEDS[0]);
- }
- // Apply a streaming mode. Changing it mid-playback re-opens the current file on
- // the other transport, resuming where the viewer was.
- function applyStreamMode(mode, reloadCurrent) {
- var previous = getStreamMode();
- setStreamMode(mode);
- $('#set-stream-seg .set-seg-btn').removeClass('active')
- .filter('[data-stream="' + getStreamMode() + '"]').addClass('active');
- if (!reloadCurrent || previous === getStreamMode()) { return; }
- // Warn only when the viewer actively picks a mode this browser cannot play
- warnIfStreamModeUnplayable();
- if (!isTranscodedVideo || !currentFile) { return; }
- // Opening the file directly at the current position rather than at zero
- // avoids starting a transcode from the beginning only to abandon it.
- var resumeAt = effectivePlaybackTime();
- var startAt = resumeAt > 1 ? resumeAt : 0;
- transcodeSeekOffset = startAt;
- if (!attachTranscodeStream(vid, transcodeStreamURL(currentFile.filepath, startAt),
- function (reason) { showToast(reason); },
- function () { playVideo(vid); })) {
- showToast('This browser cannot play the HLS stream.');
- }
- }
- function playerVideoElement() { return vid; }
- // Surface the two streaming modes that cannot work on a given browser. Anything
- // that is simply working says nothing at all.
- function warnIfStreamModeUnplayable() {
- var mode = getStreamMode();
- if (mode === 'mp4' && isWebKitClient()) {
- showToast('This browser cannot play the MP4 stream. Use Auto or HLS.');
- } else if (mode === 'hls' && !hlsPlaybackSupported(playerVideoElement())) {
- showToast('This browser has no HLS support (needs Media Source Extensions).');
- }
- }
- // Cap a bottom-anchored popup's height so it never runs past the top edge of
- // the player (it only ever opens upward) — the popup's own scrollbar takes
- // over for whatever doesn't fit.
- function clampBottomPopupHeight($popup) {
- var container = document.getElementById('player-wrap');
- if (!container) { return; }
- var margin = 10;
- var containerRect = container.getBoundingClientRect();
- var popupRect = $popup[0].getBoundingClientRect();
- var available = popupRect.bottom - containerRect.top - margin;
- $popup.css('max-height', Math.max(120, available) + 'px');
- }
- function openSettingsPopup() {
- setRepeatSingle(repeatSingle);
- setPlaybackSpeed(playbackSpeed);
- setAlwaysShowVolumeBar(alwaysShowVolumeBar);
- applyStreamMode(getStreamMode(), false);
- $('#player-ctx').hide();
- closeSubtitlePopup();
- $('#settings-popup').addClass('active');
- clampBottomPopupHeight($('#settings-popup'));
- showControls();
- }
- function closeSettingsPopup() { $('#settings-popup').removeClass('active'); }
- function toggleSettingsPopup() {
- if ($('#settings-popup').hasClass('active')) { closeSettingsPopup(); }
- else { openSettingsPopup(); }
- }
- // ── Subtitle popup (dedicated CC button) ────────────────────────────────────
- function openSubtitlePopup() {
- updateSubtitleSubmenu();
- $('#player-ctx').hide();
- closeSettingsPopup();
- $('#subtitle-popup').addClass('active');
- clampBottomPopupHeight($('#subtitle-popup'));
- showControls();
- }
- function closeSubtitlePopup() { $('#subtitle-popup').removeClass('active'); }
- function toggleSubtitlePopup() {
- if ($('#subtitle-popup').hasClass('active')) { closeSubtitlePopup(); }
- else { openSubtitlePopup(); }
- }
- function initSubtitlePopup() {
- $('#ctrl-subtitle').on('click', function (e) {
- e.stopPropagation();
- toggleSubtitlePopup();
- });
- $(document).on('mousedown.subpop', function (e) {
- if (!$(e.target).closest('#subtitle-popup, #ctrl-subtitle').length) {
- closeSubtitlePopup();
- }
- });
- $('#sub-pop-disable').on('click', function () {
- activeSubtitleIndex = -1;
- stopAssTrack();
- $('#subtitle-display').hide();
- updateSubtitleSubmenu();
- closeSubtitlePopup();
- });
- $('#sub-pop-load').on('click', function () { closeSubtitlePopup(); pickSubtitleFile(); });
- $('#sub-pop-settings').on('click', function () { closeSubtitlePopup(); openSubtitleSettings(); });
- }
- function initSettingsPopup() {
- $('#ctrl-settings').on('click', function (e) {
- e.stopPropagation();
- toggleSettingsPopup();
- });
- // Dismiss when clicking anywhere outside the popup or its button
- $(document).on('mousedown.setpop', function (e) {
- if (!$(e.target).closest('#settings-popup, #ctrl-settings').length) {
- closeSettingsPopup();
- }
- });
- $('#set-repeat-seg').on('click', '.set-seg-btn', function () {
- setRepeatSingle($(this).data('repeat') === 'one');
- });
- $('#set-speed-grid').on('click', '.speed-btn', function () {
- setPlaybackSpeed($(this).data('speed'));
- });
- $('#set-volbar-seg').on('click', '.set-seg-btn', function () {
- setAlwaysShowVolumeBar($(this).data('volbar') === 'always');
- });
- $('#set-stream-seg').on('click', '.set-seg-btn', function () {
- applyStreamMode(String($(this).data('stream')), true);
- });
- $('#set-video-props').on('click', function () { closeSettingsPopup(); openVideoInfo('props'); });
- // Apply persisted values to the video element
- setRepeatSingle(repeatSingle);
- setPlaybackSpeed(playbackSpeed);
- setAlwaysShowVolumeBar(alwaysShowVolumeBar);
- applyStreamMode(getStreamMode(), false);
- // A transcode seek replaces the media source, which resets playbackRate —
- // reapply the chosen speed every time new media is loaded.
- $(vid).on('loadedmetadata', function () { vid.playbackRate = playbackSpeed; });
- }
- // ── Video info / stats modal ──────────────────────────────────────────────────
- function openVideoInfo(tab) {
- currentInfoTab = tab || 'props';
- $('#video-info-modal').show();
- $('.info-tab').removeClass('active').eq(currentInfoTab === 'props' ? 0 : 1).addClass('active');
- $('#video-info-title').text(currentInfoTab === 'props' ? 'Video Properties' : 'Streaming Stats');
- renderInfoContent();
- if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
- if (currentInfoTab === 'stats') {
- infoRefreshTimer = setInterval(renderInfoContent, 1000);
- }
- }
- function closeVideoInfo() {
- $('#video-info-modal').hide();
- if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
- }
- function showInfoTab(tab) {
- currentInfoTab = tab;
- $('.info-tab').removeClass('active').eq(tab === 'props' ? 0 : 1).addClass('active');
- $('#video-info-title').text(tab === 'props' ? 'Video Properties' : 'Streaming Stats');
- if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
- if (tab === 'stats') { infoRefreshTimer = setInterval(renderInfoContent, 1000); }
- renderInfoContent();
- }
- function infoRow(label, value) {
- return '<div class="info-row"><span class="info-label">' + escapeHtml(String(label)) + '</span>'
- + '<span class="info-value">' + escapeHtml(String(value)) + '</span></div>';
- }
- function renderInfoContent() {
- var html = '';
- if (currentInfoTab === 'props') {
- html += infoRow('Title', currentFile ? currentFile.name : '–');
- html += infoRow('Resolution', (vid.videoWidth && vid.videoHeight)
- ? vid.videoWidth + ' × ' + vid.videoHeight : '–');
- var infoDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
- var infoPosition = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
- html += infoRow('Duration', infoDuration ? formatTime(infoDuration) : '–');
- html += infoRow('Position', infoPosition ? formatTime(infoPosition) : '–');
- html += infoRow('Playback speed', vid.playbackRate + '×');
- html += infoRow('Volume', vid.muted ? 'Muted' : Math.round(vid.volume * 100) + '%');
- if (currentFile) { html += infoRow('File path', currentFile.filepath || '–'); }
- } else {
- var rsLabels = ['No info', 'Metadata only', 'Have current data', 'Have future data', 'Enough data'];
- var nsLabels = ['Empty', 'Idle', 'Loading', 'No source'];
- html += infoRow('Ready state', rsLabels[vid.readyState] || vid.readyState);
- html += infoRow('Network state', nsLabels[vid.networkState] || vid.networkState);
- var bufEnd = 0;
- if (vid.buffered && vid.buffered.length > 0) {
- for (var i = 0; i < vid.buffered.length; i++) {
- if (vid.buffered.start(i) <= vid.currentTime + 0.1) {
- bufEnd = Math.max(bufEnd, vid.buffered.end(i));
- }
- }
- }
- html += infoRow('Buffer ahead', Math.max(0, bufEnd - vid.currentTime).toFixed(1) + 's');
- html += infoRow('Total buffered', vid.buffered.length > 0
- ? formatTime(vid.buffered.end(vid.buffered.length - 1)) : '–');
- if (vid.getVideoPlaybackQuality) {
- var q = vid.getVideoPlaybackQuality();
- html += infoRow('Frames decoded', q.totalVideoFrames || 0);
- html += infoRow('Frames dropped', q.droppedVideoFrames || 0);
- }
- html += infoRow('Stalled / ended', vid.ended ? 'Ended' : (vid.readyState < 3 ? 'Yes' : 'No'));
- }
- $('#video-info-body').html(html);
- }
- // ── Subtitle settings ─────────────────────────────────────────────────────────
- function loadSubtitleSettings() {
- try {
- var s = JSON.parse(localStorage.getItem('movie_subtitle_settings') || 'null');
- if (s) { Object.assign(subtitleSettings, s); }
- } catch (e) {}
- }
- function saveSubtitleSettings() {
- localStorage.setItem('movie_subtitle_settings', JSON.stringify(subtitleSettings));
- }
- function applySubtitleSettings() {
- var s = subtitleSettings;
- $('#subtitle-display').css({
- 'font-size': s.size + 'px',
- 'font-family': s.font,
- 'color': s.color,
- 'bottom': s.position === 'bottom' ? '72px' : 'auto',
- 'top': s.position === 'top' ? '72px' : 'auto',
- 'transform': 'translateX(-50%)'
- });
- }
- function syncSettingsPreview() {
- var s = subtitleSettings;
- $('#sset-preview').css({
- 'font-size': s.size + 'px',
- 'font-family': s.font,
- 'color': s.color,
- '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)'
- });
- }
- function openSubtitleSettings() {
- var s = subtitleSettings;
- $('.sset-seg-btn').removeClass('active').filter('[data-val="' + s.position + '"]').addClass('active');
- $('#sset-size').val(s.size);
- $('#sset-size-val').text(s.size + 'px');
- $('#sset-font').val(s.font);
- var swatchMatch = $('.sset-color[data-color="' + s.color.toLowerCase() + '"]');
- $('.sset-color, #sset-color-custom').removeClass('active');
- if (swatchMatch.length) { swatchMatch.addClass('active'); }
- else { $('#sset-color-custom').addClass('active'); }
- $('#sset-color-custom').val(s.color);
- syncSettingsPreview();
- $('#subtitle-settings-modal').show();
- }
- function closeSubtitleSettings() { $('#subtitle-settings-modal').hide(); }
- function initSubtitleSettings() {
- loadSubtitleSettings();
- applySubtitleSettings();
- $('#sset-close').on('click', closeSubtitleSettings);
- $(document).on('click', '.sset-seg-btn', function () {
- subtitleSettings.position = $(this).data('val');
- $('.sset-seg-btn').removeClass('active');
- $(this).addClass('active');
- applySubtitleSettings();
- saveSubtitleSettings();
- });
- $('#sset-size').on('input', function () {
- subtitleSettings.size = parseInt($(this).val(), 10);
- $('#sset-size-val').text(subtitleSettings.size + 'px');
- applySubtitleSettings();
- syncSettingsPreview();
- saveSubtitleSettings();
- });
- $('#sset-font').on('change', function () {
- subtitleSettings.font = $(this).val();
- ensureEmbeddedFontLoaded(subtitleSettings.font); // no-op for built-in fonts
- applySubtitleSettings();
- syncSettingsPreview();
- saveSubtitleSettings();
- });
- $(document).on('click', '.sset-color', function () {
- subtitleSettings.color = $(this).data('color');
- $('.sset-color, #sset-color-custom').removeClass('active');
- $(this).addClass('active');
- $('#sset-color-custom').val(subtitleSettings.color);
- applySubtitleSettings();
- syncSettingsPreview();
- saveSubtitleSettings();
- });
- $('#sset-color-custom').on('input', function () {
- subtitleSettings.color = $(this).val();
- $('.sset-color').removeClass('active');
- $('#sset-color-custom').addClass('active');
- applySubtitleSettings();
- syncSettingsPreview();
- saveSubtitleSettings();
- });
- }
- // ── Subtitle loading / parsing / display ──────────────────────────────────────
- // Exposed on window so ao_module_openFileSelector can invoke it by name
- window.movieEmbOnSubtitleFile = function (raw) {
- var entry = Array.isArray(raw) ? raw[0] : raw;
- var filePath = (entry && typeof entry === 'object') ? entry.filepath : entry;
- if (!filePath || typeof filePath !== 'string') { return; }
- $.ajax({
- url: MEDIA_API + '?file=' + encodeURIComponent(filePath),
- dataType: 'text',
- success: function (content) {
- var name = filePath.replace(/\\/g, '/').split('/').pop();
- var cues = parseSrt(content);
- var existing = -1;
- loadedSubtitleFiles.forEach(function (sf, i) {
- if (sf.path === filePath) { existing = i; }
- });
- if (existing >= 0) {
- loadedSubtitleFiles[existing].cues = cues;
- activeSubtitleIndex = existing;
- } else {
- loadedSubtitleFiles.push({ path: filePath, name: name, cues: cues });
- activeSubtitleIndex = loadedSubtitleFiles.length - 1;
- }
- showToast('Subtitle loaded: ' + name);
- applyActiveSubtitle(); // a sidecar file replaces any styled track
- updateSubtitleSubmenu();
- },
- error: function () { showToast('Failed to load subtitle file'); }
- });
- };
- function parseSrtTime(t) {
- var m = t.match(/(\d+):(\d+):(\d+)[,.](\d+)/);
- if (!m) { return 0; }
- return parseInt(m[1]) * 3600 + parseInt(m[2]) * 60 + parseInt(m[3]) + parseInt(m[4]) / 1000;
- }
- function parseSrt(content) {
- var cues = [];
- var blocks = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim().split(/\n\n+/);
- blocks.forEach(function (block) {
- var lines = block.split('\n');
- var tcIdx = -1;
- for (var i = 0; i < lines.length; i++) {
- if (lines[i].indexOf('-->') !== -1) { tcIdx = i; break; }
- }
- if (tcIdx < 0) { return; }
- var parts = lines[tcIdx].split('-->');
- if (parts.length < 2) { return; }
- var start = parseSrtTime(parts[0].trim());
- var end = parseSrtTime(parts[1].trim().split(' ')[0]);
- // Strip inline SRT tags like <b>, <i>, <font>, plus any ASS override
- // blocks such as {\an8} or {\pos(x,y)}. ffmpeg's ASS-to-SubRip
- // conversion leaves positioning tags like those behind, so without this
- // they would be shown to the viewer as literal text.
- var text = lines.slice(tcIdx + 1).join('\n').trim()
- .replace(/<[^>]+>/g, '')
- .replace(/\{\\[^}]*\}/g, '')
- .trim();
- if (text) { cues.push({ start: start, end: end, text: text }); }
- });
- return cues;
- }
- function updateSubtitleDisplay() {
- // Styled tracks are drawn by the ASS renderer on its own frame loop
- if (assActive) { $('#subtitle-display').hide(); return; }
- if (activeSubtitleIndex < 0 || !loadedSubtitleFiles[activeSubtitleIndex]) {
- $('#subtitle-display').hide();
- return;
- }
- var currentTime = isTranscodedVideo
- ? (vid.currentTime + transcodeSeekOffset)
- : vid.currentTime;
- var cues = loadedSubtitleFiles[activeSubtitleIndex].cues;
- var found = null;
- for (var i = 0; i < cues.length; i++) {
- if (cues[i].start < subtitleSeekFloor) { continue; } // in flight when we landed
- if (currentTime >= cues[i].start && currentTime <= cues[i].end) { found = cues[i]; break; }
- }
- if (found) {
- $('#subtitle-display').html(escapeHtml(found.text).replace(/\n/g, '<br>')).show();
- } else {
- $('#subtitle-display').hide();
- }
- }
- // ── Embedded subtitle tracks and fonts ────────────────────────────────────────
- // MKV releases usually mux their subtitles (and the fonts they were typeset in)
- // into the container rather than shipping sidecar files. The server lists them
- // and extracts on demand; tracks are converted to SubRip, which keeps the text
- // and timing but drops ASS styling, positioning and karaoke.
- var embeddedSubtitles = []; // [{index, codec, language, title, forced, textual}]
- var embeddedFonts = []; // [{index, filename, mimetype}]
- var embeddedMediaPath = null; // file the two lists above describe
- var embeddedProbeToken = 0; // invalidates in-flight probes on file change
- var embeddedFontFaces = []; // FontFace objects registered for this video
- var embeddedFontsLoaded = {}; // family name -> already fetched
- function resetEmbeddedTracks() {
- embeddedProbeToken++;
- stopAssTrack();
- embeddedSubtitles = [];
- embeddedFonts = [];
- embeddedMediaPath = null;
- // Font families are keyed by attachment ordinal, which means the same name
- // refers to a different font in the next video — drop the old faces.
- embeddedFontFaces.forEach(function (face) {
- try { document.fonts.delete(face); } catch (e) {}
- });
- embeddedFontFaces = [];
- embeddedFontsLoaded = {};
- }
- function loadEmbeddedTrackList(filepath) {
- resetEmbeddedTracks();
- if (!filepath) { return; }
- embeddedMediaPath = filepath;
- var token = embeddedProbeToken;
- fetch(SUBTITLE_API + '?file=' + encodeURIComponent(filepath))
- .then(function (r) { return r.json(); })
- .then(function (info) {
- if (token !== embeddedProbeToken) { return; }
- if (!info || info.error) { return; }
- embeddedSubtitles = info.subtitles || [];
- embeddedFonts = info.fonts || [];
- updateSubtitleSubmenu();
- refreshEmbeddedFontOptions();
- })
- .catch(function () {}); // embedded tracks are a bonus — fail quietly
- }
- function embeddedTrackLabel(track, position) {
- var label = track.title || '';
- if (!label) { label = 'Track ' + (position + 1); }
- if (track.language) { label += ' [' + track.language + ']'; }
- if (track.forced) { label += ' (forced)'; }
- if (!track.textual) { label += ' — image based'; }
- return label;
- }
- // Extraction has to scan the whole container, so it takes a few seconds on a
- // large file. Results are kept in loadedSubtitleFiles, making reselection free.
- function selectEmbeddedSubtitle(track, position) {
- if (!track.textual) {
- showToast('That track is image based and cannot be displayed');
- return;
- }
- var cacheKey = 'embedded#' + track.index + '@' + embeddedMediaPath;
- for (var i = 0; i < loadedSubtitleFiles.length; i++) {
- if (loadedSubtitleFiles[i].path === cacheKey) {
- activeSubtitleIndex = i;
- applyActiveSubtitle();
- updateSubtitleSubmenu();
- return;
- }
- }
- // ASS/SSA is fetched in its native form so the styling survives; everything
- // else comes through as SubRip for the plain renderer.
- var styled = /^(ass|ssa)$/i.test(track.codec) && typeof ASS !== 'undefined';
- var mediaPath = embeddedMediaPath;
- var url = SUBTITLE_API + '?file=' + encodeURIComponent(mediaPath) + '&track=' + track.index
- + (styled ? '&format=ass' : '');
- showToast('Extracting subtitle track…');
- $.ajax({
- url: url,
- dataType: 'text',
- success: function (content) {
- if (mediaPath !== embeddedMediaPath) { return; } // episode changed
- if (styled) {
- var parsed = ASS.parse(content);
- if (!parsed.events.length) {
- showToast('That track contained no readable text');
- return;
- }
- loadedSubtitleFiles.push({
- path: cacheKey,
- name: embeddedTrackLabel(track, position),
- cues: [],
- assTrack: parsed
- });
- activeSubtitleIndex = loadedSubtitleFiles.length - 1;
- applyActiveSubtitle();
- updateSubtitleSubmenu();
- showToast('Subtitle loaded · ' + parsed.events.length + ' styled lines');
- return;
- }
- var cues = parseSrt(content);
- if (cues.length === 0) {
- showToast('That track contained no readable text');
- return;
- }
- loadedSubtitleFiles.push({
- path: cacheKey,
- name: embeddedTrackLabel(track, position),
- cues: cues
- });
- activeSubtitleIndex = loadedSubtitleFiles.length - 1;
- applyActiveSubtitle();
- updateSubtitleSubmenu();
- showToast('Subtitle loaded · ' + cues.length + ' lines');
- },
- error: function () { showToast('Could not extract that subtitle track'); }
- });
- }
- // Switch the display between the styled ASS renderer and the plain SubRip
- // overlay depending on what the newly selected track carries.
- function applyActiveSubtitle() {
- var entry = activeSubtitleIndex >= 0 ? loadedSubtitleFiles[activeSubtitleIndex] : null;
- if (entry && entry.assTrack) {
- startAssTrack(entry.assTrack);
- } else {
- stopAssTrack();
- updateSubtitleDisplay();
- }
- }
- // ── Subtitle seek floor ──────────────────────────────────────────────────────
- // After a seek, any line that had already begun before the landing point is
- // skipped entirely; only lines that start at or after it are shown. Seeking to
- // 1:02 with lines at 1:00-1:03 and 1:05-1:10 therefore shows nothing until 1:05.
- var subtitleSeekFloor = 0;
- function setSubtitleSeekFloor(time) {
- subtitleSeekFloor = Math.max(0, time || 0);
- if (assRenderer) { assRenderer.setSuppressBefore(subtitleSeekFloor); }
- updateSubtitleDisplay();
- }
- function resetSubtitleSeekFloor() { setSubtitleSeekFloor(0); }
- // ── Styled ASS rendering ─────────────────────────────────────────────────────
- // ASS tracks are fetched in their native form and drawn by script/ass.js, which
- // preserves per-line styling and position. That is what makes dual-language
- // releases work: the Japanese and Chinese lines are separate events shown at the
- // same time, and a single-cue renderer can only ever display one of them.
- var assRenderer = null;
- var assActive = false;
- var assFrameReq = null;
- function initAssRenderer() {
- var overlay = document.getElementById('ass-overlay');
- if (overlay && typeof ASS !== 'undefined') { assRenderer = new ASS.Renderer(overlay); }
- }
- // Match the overlay to the letterboxed picture inside the video element, so
- // script coordinates map onto what the viewer actually sees.
- function syncAssOverlayGeometry() {
- if (!assRenderer) { return; }
- var vid = document.getElementById('main-video');
- var overlay = document.getElementById('ass-overlay');
- var cw = vid.clientWidth, ch = vid.clientHeight;
- var vw = vid.videoWidth, vh = vid.videoHeight;
- // Until the decoder reports the picture size there is no way to know where
- // the letterbox bars are. Falling back to the raw element box would scale
- // the script against the black bars too and push bottom-anchored lines down
- // over the controls, so keep the last known good geometry instead.
- if (!(vw > 0 && vh > 0 && cw > 0 && ch > 0)) { return; }
- var scale = Math.min(cw / vw, ch / vh);
- var width = vw * scale;
- var height = vh * scale;
- var left = (cw - width) / 2;
- var top = (ch - height) / 2;
- if (overlay._w !== width || overlay._h !== height || overlay._l !== left || overlay._t !== top) {
- overlay._w = width; overlay._h = height; overlay._l = left; overlay._t = top;
- overlay.style.left = left + 'px';
- overlay.style.top = top + 'px';
- overlay.style.width = width + 'px';
- overlay.style.height = height + 'px';
- assRenderer.resize(width, height);
- }
- }
- function startAssTrack(track) {
- if (!assRenderer) { return; }
- stopAssTrack();
- assRenderer.setTrack(track);
- assActive = true;
- $('#ass-overlay').addClass('active');
- $('#subtitle-display').hide(); // the plain renderer must not double up
- loadAssFonts(track);
- var step = function () {
- if (!assActive) { return; }
- syncAssOverlayGeometry();
- assRenderer.setTime(effectivePlaybackTime());
- assFrameReq = requestAnimationFrame(step);
- };
- step();
- }
- function stopAssTrack() {
- assActive = false;
- if (assFrameReq) { cancelAnimationFrame(assFrameReq); assFrameReq = null; }
- if (assRenderer) { assRenderer.clear(); }
- $('#ass-overlay').removeClass('active');
- }
- // Only pull the fonts the track actually references — a release can attach a
- // dozen and use half of them.
- function loadAssFonts(track) {
- if (typeof ASS === 'undefined') { return; }
- ASS.referencedFonts(track).forEach(function (family) {
- ensureEmbeddedFontLoaded(family);
- });
- }
- // ── Embedded fonts ───────────────────────────────────────────────────────────
- // Registered under the font's own internal family name, which is what ASS styles
- // reference, and offered in Subtitle Settings for SubRip tracks. Fetched lazily:
- // a release can carry a dozen fonts and only a few are ever used.
- function embeddedFontFamily(font) {
- return font.family || ('aroz-embedded-' + font.index);
- }
- function findEmbeddedFontByFamily(family) {
- var wanted = String(family || '').replace(/^@/, '').toLowerCase();
- var found = null;
- embeddedFonts.forEach(function (f) {
- if (embeddedFontFamily(f).toLowerCase() === wanted) { found = f; }
- });
- return found;
- }
- function refreshEmbeddedFontOptions() {
- var $select = $('#sset-font');
- $select.find('optgroup.embedded-fonts').remove();
- if (embeddedFonts.length > 0) {
- var $group = $('<optgroup label="Embedded in this video" class="embedded-fonts"></optgroup>');
- embeddedFonts.forEach(function (font) {
- $group.append($('<option></option>')
- .attr('value', embeddedFontFamily(font))
- .text(font.filename || ('Font ' + (font.index + 1))));
- });
- $select.append($group);
- }
- // A font picked for a previous video may not exist in this one
- var stillOffered = $select.find('option').filter(function () {
- return this.value === subtitleSettings.font;
- }).length > 0;
- if (!stillOffered) {
- subtitleSettings.font = 'system-ui, sans-serif';
- applySubtitleSettings();
- saveSubtitleSettings();
- }
- $select.val(subtitleSettings.font);
- ensureEmbeddedFontLoaded(subtitleSettings.font);
- }
- function ensureEmbeddedFontLoaded(family) {
- if (!family || embeddedFontsLoaded[family] || !embeddedMediaPath) { return; }
- if (typeof FontFace === 'undefined' || !document.fonts) { return; }
- var meta = findEmbeddedFontByFamily(family);
- if (!meta) { return; } // a built-in font, or one this video does not carry
- embeddedFontsLoaded[family] = true; // claim it so we do not refetch in a loop
- var url = SUBTITLE_API + '?file=' + encodeURIComponent(embeddedMediaPath) + '&font=' + meta.index;
- var face = new FontFace(embeddedFontFamily(meta), 'url("' + url + '")');
- face.load().then(function (loaded) {
- document.fonts.add(loaded);
- embeddedFontFaces.push(loaded);
- applySubtitleSettings();
- syncSettingsPreview();
- // The renderer sizes every run off the face's own ascent/descent, so a
- // face arriving late invalidates the measurements taken against the
- // fallback it was standing in for.
- if (typeof ASS !== 'undefined' && ASS.invalidateFontMetrics) { ASS.invalidateFontMetrics(); }
- if (assRenderer) { assRenderer.clear(); } // redraw with the real face
- }).catch(function () {
- embeddedFontsLoaded[family] = false;
- });
- }
- // Builds the track list (Disable / embedded tracks / loaded sidecar files) into
- // one menu, given its "Disable" and "Load" anchor items — shared by the
- // right-click context submenu and the dedicated CC button popup so both stay
- // in sync from a single call to updateSubtitleSubmenu().
- function populateSubtitleTrackList($disable, $load, onSelect) {
- $disable.siblings('.ctx-sub-dynamic').remove();
- var disabled = (activeSubtitleIndex < 0);
- $disable.toggleClass('ctx-active', disabled)
- .find('.ctx-icon').text(disabled ? '✓' : '');
- // Tracks muxed into the video, listed whether or not they are loaded yet
- if (embeddedSubtitles.length > 0) {
- $('<div class="ctx-divider ctx-sub-dynamic"></div>').insertBefore($load);
- embeddedSubtitles.forEach(function (track, position) {
- var cacheKey = 'embedded#' + track.index + '@' + embeddedMediaPath;
- var isActive = activeSubtitleIndex >= 0 &&
- loadedSubtitleFiles[activeSubtitleIndex] &&
- loadedSubtitleFiles[activeSubtitleIndex].path === cacheKey;
- $('<div class="ctx-item ctx-sub-dynamic'
- + (isActive ? ' ctx-active' : '')
- + (track.textual ? '' : ' ctx-disabled') + '">'
- + '<i class="ctx-icon">' + (isActive ? '✓' : '') + '</i>'
- + escapeHtml(embeddedTrackLabel(track, position))
- + '</div>')
- .on('click', function () {
- selectEmbeddedSubtitle(track, position);
- onSelect();
- })
- .insertBefore($load);
- });
- }
- // Sidecar files the user loaded by hand
- var external = [];
- loadedSubtitleFiles.forEach(function (sf, idx) {
- if (String(sf.path).indexOf('embedded#') !== 0) { external.push({ sf: sf, idx: idx }); }
- });
- if (external.length > 0) {
- $('<div class="ctx-divider ctx-sub-dynamic"></div>').insertBefore($load);
- external.forEach(function (entry) {
- var isActive = (entry.idx === activeSubtitleIndex);
- $('<div class="ctx-item ctx-sub-dynamic' + (isActive ? ' ctx-active' : '') + '" data-sub-idx="' + entry.idx + '">'
- + '<i class="ctx-icon">' + (isActive ? '✓' : '') + '</i>'
- + escapeHtml(entry.sf.name)
- + '</div>')
- .on('click', function () {
- activeSubtitleIndex = parseInt($(this).data('sub-idx'), 10);
- applyActiveSubtitle();
- updateSubtitleSubmenu();
- onSelect();
- })
- .insertBefore($load);
- });
- }
- }
- function updateSubtitleSubmenu() {
- populateSubtitleTrackList($('#ctx-sub-disable'), $('#ctx-sub-load'), function () {
- $('#player-ctx').hide();
- });
- populateSubtitleTrackList($('#sub-pop-disable'), $('#sub-pop-load'), function () {
- closeSubtitlePopup();
- });
- if ($('#subtitle-popup').hasClass('active')) { clampBottomPopupHeight($('#subtitle-popup')); }
- }
- function initSubtitleMenu() {
- var $ctx = $('#player-ctx');
- var $parent = $('#ctx-subtitle-parent');
- var $sub = $('#ctx-subtitle-sub');
- var subHideTimer;
- function cancelSubHide() { clearTimeout(subHideTimer); }
- function scheduleSubHide() {
- subHideTimer = setTimeout(function () { $sub.hide(); }, 120);
- }
- $parent.on('mouseenter', function () {
- cancelSubHide();
- var ctxRight = $ctx.offset().left + $ctx.outerWidth();
- var containerRight = $('#player-wrap').offset().left + $('#player-wrap').outerWidth();
- if (ctxRight + 200 > containerRight) {
- $sub.css({ left: 'auto', right: '100%' });
- } else {
- $sub.css({ left: '100%', right: 'auto' });
- }
- // Clamp vertically so the submenu never runs past the player edge —
- // flip to open upward when there's more room above than below, and
- // cap its height to whichever side it opens on (scrollbar handles the rest).
- var margin = 10;
- var containerRect = document.getElementById('player-wrap').getBoundingClientRect();
- var parentRect = this.getBoundingClientRect();
- var spaceBelow = containerRect.bottom - parentRect.top - margin;
- var spaceAbove = parentRect.bottom - containerRect.top - margin;
- if (spaceBelow < 160 && spaceAbove > spaceBelow) {
- $sub.css({ top: 'auto', bottom: 0, maxHeight: Math.max(120, spaceAbove) + 'px' });
- } else {
- $sub.css({ top: 0, bottom: 'auto', maxHeight: Math.max(120, spaceBelow) + 'px' });
- }
- $sub.show();
- });
- $parent.on('mouseleave', scheduleSubHide);
- $sub.on('mouseenter', cancelSubHide);
- $sub.on('mouseleave', scheduleSubHide);
- $('#ctx-sub-disable').on('click', function () {
- activeSubtitleIndex = -1;
- stopAssTrack();
- $('#subtitle-display').hide();
- updateSubtitleSubmenu();
- $ctx.hide();
- });
- $('#ctx-sub-load').on('click', function () {
- $ctx.hide();
- pickSubtitleFile();
- });
- }
- // Open the ArozOS file selector defaulted to the folder of the playing file
- function pickSubtitleFile() {
- var startDir = 'user:/';
- if (currentFile) {
- var fp = currentFile.filepath.replace(/\\/g, '/');
- var slash = fp.lastIndexOf('/');
- if (slash > 0) { startDir = fp.substring(0, slash); }
- }
- ao_module_openFileSelector(
- window.movieEmbOnSubtitleFile,
- startDir, 'file', false,
- { fnameOverride: 'movieEmbOnSubtitleFile', extAllowed: '.srt' }
- );
- }
- // ── Keyboard shortcuts ────────────────────────────────────────────────────────
- function initKeyboard() {
- $(document).on('keydown', function (e) {
- if ($(e.target).is('input, select, textarea')) { return; }
- switch (e.key) {
- case ' ':
- case 'k':
- e.preventDefault(); togglePlay(); showControls(); break;
- case 'ArrowRight':
- e.preventDefault();
- if (isTranscodedVideo && transcodeDuration > 0 && currentFile) {
- transcodeSeekTo(effectivePlaybackTime() + 10);
- } else {
- vid.currentTime = Math.min(vid.duration || 0, vid.currentTime + 10);
- }
- showControls(); break;
- case 'ArrowLeft':
- e.preventDefault();
- if (isTranscodedVideo && transcodeDuration > 0 && currentFile) {
- transcodeSeekTo(effectivePlaybackTime() - 10);
- } else {
- vid.currentTime = Math.max(0, vid.currentTime - 10);
- }
- showControls(); break;
- case 'ArrowUp':
- e.preventDefault();
- vid.volume = Math.min(1, Math.round((vid.volume + 0.1) * 10) / 10);
- showControls(); break;
- case 'ArrowDown':
- e.preventDefault();
- vid.volume = Math.max(0, Math.round((vid.volume - 0.1) * 10) / 10);
- showControls(); break;
- case 'f':
- case 'F':
- e.preventDefault(); toggleFullscreen(); break;
- case 'm':
- case 'M':
- e.preventDefault(); vid.muted = !vid.muted; break;
- case 'r':
- case 'R':
- e.preventDefault();
- setRepeatSingle(!repeatSingle);
- showToast('Repeat: ' + (repeatSingle ? 'On' : 'Off')); break;
- case 's':
- case 'S':
- e.preventDefault(); toggleSettingsPopup(); break;
- case 'Escape':
- e.preventDefault();
- $('#player-ctx').hide();
- closeSettingsPopup();
- closeSubtitlePopup();
- closeVideoInfo();
- closeSubtitleSettings(); break;
- case 'MediaPlayPause':
- e.preventDefault(); togglePlay(); break;
- }
- });
- }
- // ── Init ──────────────────────────────────────────────────────────────────────
- function initMain(){
- initVideoControls();
- initContextMenu();
- initSettingsPopup();
- initSubtitlePopup();
- initScrubPreview();
- initAssRenderer();
- resetSubtitleSeekFloor(); // a freshly opened file starts unsuppressed
- if (currentFile) {
- scheduleStoryboardLoad(currentFile.filepath);
- loadEmbeddedTrackList(currentFile.filepath);
- }
- initSubtitleMenu();
- initSubtitleSettings();
- initKeyboard();
- }
- $(document).ready(function () {
- //Check if there are another instant running. If yes, replace that another instance URL
- if (ao_module_virtualDesktop){
- //If in ao_module mode, try to make this windows the only instance
- if (!ao_module_makeSingleInstance()){
- initMain();
- }
- }else{
- initMain();
- }
- });
- </script>
- </body>
- </html>
|