index.html 231 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  6. <meta name="apple-mobile-web-app-capable" content="yes">
  7. <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  8. <meta name="theme-color" content="#000000">
  9. <link rel="manifest" crossorigin="use-credentials" href="manifest.json">
  10. <title>Movie</title>
  11. <!-- ArozOS module helpers -->
  12. <script src="../script/jquery.min.js"></script>
  13. <script src="../script/ao_module.js"></script>
  14. <!-- App path config (single source of truth for all API paths) -->
  15. <!-- HLS via Media Source, so browsers without native HLS (Firefox,
  16. Chrome) can play the transcoded playlist without hls.js -->
  17. <script src="../script/hlsmse.js"></script>
  18. <script src="backend/common.js"></script>
  19. <!-- ASS/SSA subtitle parser + renderer (see script/ass.js) -->
  20. <script src="script/ass.js"></script>
  21. <style>
  22. /* ─── Reset & base ──────────────────────────────────────────────────────────── */
  23. *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  24. :root {
  25. --bg: #0a0a0a;
  26. --surface: #1c1c1e;
  27. --surface2: #2c2c2e;
  28. --accent: #0a84ff;
  29. --accent2: #30d158;
  30. --text: #f5f5f7;
  31. --text-sub: #98989d;
  32. --radius: 12px;
  33. --card-w: 180px;
  34. --card-ratio: 1.5; /* height = width * ratio (poster aspect) */
  35. --header-h: 56px;
  36. --transition: 0.2s ease;
  37. }
  38. html, body {
  39. background: var(--bg);
  40. color: var(--text);
  41. font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Helvetica Neue", sans-serif;
  42. height: 100%;
  43. overflow: hidden;
  44. }
  45. /* ─── App shell ──────────────────────────────────────────────────────────────── */
  46. #app { width: 100vw; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
  47. /* ─── Top nav bar ────────────────────────────────────────────────────────────── */
  48. #topbar {
  49. flex-shrink: 0;
  50. height: var(--header-h);
  51. display: flex;
  52. align-items: center;
  53. padding: 0 20px;
  54. gap: 16px;
  55. background: linear-gradient(to bottom, rgba(0,0,0,0.9) 0%, transparent 100%);
  56. position: relative;
  57. z-index: 10;
  58. }
  59. #topbar h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.3px; }
  60. #topbar h1 span { color: var(--accent); }
  61. #search-wrap { margin-left: auto; display: flex; align-items: center; gap: 8px; }
  62. #search-input {
  63. background: var(--surface2);
  64. border: none;
  65. border-radius: 20px;
  66. color: var(--text);
  67. font-size: 14px;
  68. padding: 7px 14px;
  69. width: 200px;
  70. outline: none;
  71. transition: width var(--transition);
  72. }
  73. #search-input:focus { width: 280px; box-shadow: 0 0 0 2px var(--accent); }
  74. #search-input::placeholder { color: var(--text-sub); }
  75. /* ─── View containers ────────────────────────────────────────────────────────── */
  76. .view { display: none; flex: 1; overflow: hidden; flex-direction: column; }
  77. .view.active { display: flex; }
  78. /* ─── Library view ───────────────────────────────────────────────────────────── */
  79. #view-library { padding: 0; }
  80. /* Status bar ─────────────────────────────────────────────────────────────────── */
  81. #library-status-bar {
  82. flex-shrink: 0;
  83. display: flex;
  84. align-items: center;
  85. gap: 7px;
  86. padding: 3px 22px;
  87. font-size: 11px;
  88. color: var(--text-sub);
  89. border-bottom: 1px solid rgba(255,255,255,0.04);
  90. min-height: 26px;
  91. }
  92. .spinner-sm {
  93. width: 11px; height: 11px; flex-shrink: 0;
  94. border: 2px solid rgba(255,255,255,0.15);
  95. border-top-color: var(--accent);
  96. border-radius: 50%;
  97. animation: spin 0.8s linear infinite;
  98. }
  99. #library-refresh-btn {
  100. background: none; border: none; cursor: pointer;
  101. color: var(--accent); font-size: 11px; font-weight: 500;
  102. padding: 0; outline: none; transition: opacity var(--transition);
  103. }
  104. #library-refresh-btn:hover { opacity: 0.7; }
  105. #library-refresh-btn:disabled { opacity: 0.35; cursor: default; }
  106. #library-scroll {
  107. flex: 1;
  108. overflow-y: auto;
  109. overflow-x: hidden;
  110. padding: 8px 20px 40px;
  111. scroll-behavior: smooth;
  112. }
  113. #library-scroll::-webkit-scrollbar { width: 4px; }
  114. #library-scroll::-webkit-scrollbar-track { background: transparent; }
  115. #library-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
  116. #no-content {
  117. display: none;
  118. flex-direction: column;
  119. align-items: center;
  120. justify-content: center;
  121. height: 60%;
  122. gap: 12px;
  123. color: var(--text-sub);
  124. font-size: 16px;
  125. }
  126. #no-content .icon img { width: 80px; height: 80px; opacity: 0.3; }
  127. #loading-overlay {
  128. position: absolute; inset: 0;
  129. background: var(--bg);
  130. display: flex;
  131. flex-direction: column;
  132. align-items: center;
  133. justify-content: center;
  134. gap: 16px;
  135. z-index: 100;
  136. font-size: 15px;
  137. color: var(--text-sub);
  138. }
  139. .spinner {
  140. width: 40px; height: 40px;
  141. border: 3px solid var(--surface2);
  142. border-top-color: var(--accent);
  143. border-radius: 50%;
  144. animation: spin 0.8s linear infinite;
  145. }
  146. @keyframes spin { to { transform: rotate(360deg); } }
  147. /* ─── Section heading ────────────────────────────────────────────────────────── */
  148. .section-title {
  149. font-size: 20px;
  150. font-weight: 600;
  151. margin: 24px 0 12px;
  152. color: var(--text);
  153. }
  154. /* ─── Album grid ─────────────────────────────────────────────────────────────── */
  155. .album-grid {
  156. display: grid;
  157. grid-template-columns: repeat(auto-fill, minmax(var(--card-w), 1fr));
  158. gap: 16px;
  159. }
  160. .album-card {
  161. cursor: pointer;
  162. border-radius: var(--radius);
  163. overflow: hidden;
  164. background: var(--surface);
  165. transition: transform var(--transition), box-shadow var(--transition);
  166. outline: none;
  167. position: relative;
  168. }
  169. .album-card:hover,
  170. .album-card.focused {
  171. transform: scale(1.04);
  172. box-shadow: 0 8px 32px rgba(0,0,0,0.7), 0 0 0 2px var(--accent);
  173. z-index: 2;
  174. }
  175. .album-card .poster {
  176. width: 100%;
  177. aspect-ratio: 16 / 9;
  178. object-fit: cover;
  179. display: block;
  180. background: var(--surface2);
  181. }
  182. .poster-placeholder {
  183. width: 100%;
  184. aspect-ratio: 16 / 9;
  185. background: linear-gradient(135deg, var(--surface) 0%, var(--surface2) 100%);
  186. display: flex;
  187. align-items: center;
  188. justify-content: center;
  189. }
  190. .poster-placeholder img { width: 100%; opacity: 1; }
  191. .album-card .card-info {
  192. padding: 8px 10px 10px;
  193. }
  194. .album-card .card-title {
  195. font-size: 13px;
  196. font-weight: 600;
  197. white-space: nowrap;
  198. overflow: hidden;
  199. text-overflow: ellipsis;
  200. }
  201. .album-card .card-meta {
  202. font-size: 11px;
  203. color: var(--text-sub);
  204. margin-top: 2px;
  205. }
  206. .badge {
  207. position: absolute;
  208. top: 7px; right: 7px;
  209. background: rgba(0,0,0,0.65);
  210. backdrop-filter: blur(4px);
  211. border-radius: 6px;
  212. font-size: 10px;
  213. font-weight: 600;
  214. padding: 2px 6px;
  215. color: #fff;
  216. letter-spacing: 0.3px;
  217. text-transform: uppercase;
  218. }
  219. .badge.series { color: var(--accent2); }
  220. .badge.anime { color: #ff9f0a; } /* warm orange for anime */
  221. /* ─── Detail view ────────────────────────────────────────────────────────────── */
  222. #view-detail { position: relative; }
  223. #detail-hero {
  224. flex-shrink: 0;
  225. height: 38vh;
  226. min-height: 200px;
  227. position: relative;
  228. overflow: hidden;
  229. }
  230. #detail-hero-bg {
  231. position: absolute; inset: 0;
  232. background-size: cover;
  233. background-position: center top;
  234. filter: blur(4px) brightness(0.55);
  235. transform: scale(1.1);
  236. }
  237. #detail-hero-content {
  238. position: relative;
  239. display: flex;
  240. align-items: flex-end;
  241. height: 100%;
  242. padding: 0 28px 20px;
  243. gap: 20px;
  244. }
  245. #detail-poster {
  246. width: 120px;
  247. flex-shrink: 0;
  248. border-radius: 8px;
  249. overflow: hidden;
  250. box-shadow: 0 8px 24px rgba(0,0,0,0.6);
  251. }
  252. #detail-poster img, #detail-poster .poster-placeholder {
  253. width: 120px;
  254. aspect-ratio: 2 / 3;
  255. object-fit: cover;
  256. display: block;
  257. }
  258. #detail-meta { flex: 1; min-width: 0; }
  259. #detail-title { font-size: 26px; font-weight: 700; line-height: 1.15; overflow-wrap: anywhere; }
  260. #detail-subtitle { font-size: 14px; color: var(--text-sub); margin-top: 4px; }
  261. #detail-actions { display: flex; gap: 10px; margin-top: 14px; flex-wrap: wrap; }
  262. .btn {
  263. border: none; cursor: pointer; border-radius: 8px;
  264. font-size: 14px; font-weight: 600; padding: 10px 22px;
  265. transition: opacity var(--transition), transform var(--transition);
  266. outline: none;
  267. }
  268. .btn:hover, .btn.focused { opacity: 0.85; transform: scale(1.03); }
  269. .btn-primary { background: var(--text); color: #000; }
  270. .btn-secondary { background: var(--surface2); color: var(--text); }
  271. /* ─── Season tabs ────────────────────────────────────────────────────────────── */
  272. #season-tabs {
  273. flex-shrink: 0;
  274. display: flex;
  275. flex-wrap: wrap;
  276. gap: 6px 8px;
  277. padding: 10px 28px 8px;
  278. max-height: 120px; /* ~3 rows before scrolling */
  279. overflow-y: auto;
  280. scrollbar-width: thin;
  281. scrollbar-color: var(--surface2) transparent;
  282. }
  283. #season-tabs::-webkit-scrollbar { width: 3px; height: 3px; }
  284. #season-tabs::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 3px; }
  285. .season-tab {
  286. flex-shrink: 0;
  287. background: var(--surface2);
  288. border: none; cursor: pointer;
  289. border-radius: 20px;
  290. color: var(--text-sub);
  291. font-size: 13px; font-weight: 500;
  292. padding: 6px 16px;
  293. transition: background var(--transition), color var(--transition);
  294. outline: none;
  295. /* Season names can be as long as the whole release title — keep the pill
  296. inside the panel and ellipsise instead of running off the edge. */
  297. max-width: 100%;
  298. overflow: hidden;
  299. text-overflow: ellipsis;
  300. white-space: nowrap;
  301. }
  302. .season-tab.active, .season-tab.focused {
  303. background: var(--text);
  304. color: #000;
  305. }
  306. /* ─── Episode list ───────────────────────────────────────────────────────────── */
  307. #episode-scroll {
  308. flex: 1;
  309. overflow-y: auto;
  310. padding: 12px 28px 40px;
  311. scroll-behavior: smooth;
  312. }
  313. #episode-scroll::-webkit-scrollbar { width: 4px; }
  314. #episode-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
  315. .episode-item {
  316. display: flex;
  317. align-items: center;
  318. gap: 14px;
  319. padding: 10px 12px;
  320. border-radius: var(--radius);
  321. cursor: pointer;
  322. transition: background var(--transition);
  323. outline: none;
  324. }
  325. .episode-item:hover, .episode-item.focused {
  326. background: var(--surface);
  327. box-shadow: 0 0 0 2px var(--accent);
  328. }
  329. .episode-item.playing { background: rgba(10,132,255,0.15); }
  330. .ep-thumb {
  331. width: 100px; flex-shrink: 0;
  332. aspect-ratio: 16 / 9;
  333. border-radius: 6px;
  334. overflow: hidden;
  335. background: var(--surface2);
  336. }
  337. .ep-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
  338. .ep-thumb-placeholder {
  339. width: 100%; height: 100%;
  340. display: flex; align-items: center; justify-content: center;
  341. }
  342. .ep-thumb-placeholder img { width: 22px; height: 22px; opacity: 0.5; }
  343. .ep-info { flex: 1; min-width: 0; }
  344. .ep-name { font-size: 14px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  345. .ep-path { font-size: 11px; color: var(--text-sub); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  346. .ep-play-icon {
  347. flex-shrink: 0;
  348. width: 32px; height: 32px;
  349. background: var(--surface2);
  350. border-radius: 50%;
  351. display: flex; align-items: center; justify-content: center;
  352. transition: background var(--transition);
  353. }
  354. .ep-play-icon img { width: 16px; height: 16px; }
  355. .episode-item.focused .ep-play-icon,
  356. .episode-item:hover .ep-play-icon { background: var(--accent); }
  357. #detail-back {
  358. position: absolute;
  359. top: 12px; left: 16px;
  360. background: rgba(0,0,0,0.5);
  361. backdrop-filter: blur(8px);
  362. border: none; cursor: pointer;
  363. border-radius: 20px;
  364. color: var(--text);
  365. font-size: 13px; font-weight: 500;
  366. padding: 6px 16px;
  367. z-index: 5;
  368. transition: background var(--transition);
  369. outline: none;
  370. }
  371. #detail-back:hover, #detail-back.focused { background: var(--accent); }
  372. /* ─── Player view ────────────────────────────────────────────────────────────── */
  373. #view-player {
  374. position: fixed; inset: 0;
  375. background: #000;
  376. z-index: 200;
  377. flex-direction: row;
  378. }
  379. #view-player.active { display: flex; }
  380. #video-container {
  381. flex: 1;
  382. display: flex;
  383. flex-direction: column;
  384. position: relative;
  385. overflow: hidden;
  386. }
  387. #main-video {
  388. width: 100%; height: 100%;
  389. object-fit: contain;
  390. background: #000;
  391. display: block;
  392. }
  393. /* ─── Custom video controls ──────────────────────────────────────────────────── */
  394. #video-controls {
  395. position: absolute;
  396. bottom: 0; left: 0; right: 0;
  397. background: linear-gradient(transparent, rgba(0,0,0,0.85) 100%);
  398. padding: 40px 20px 16px;
  399. transition: opacity 0.3s;
  400. }
  401. #video-controls.hidden { opacity: 0; pointer-events: none; }
  402. /* Hide cursor when controls auto-hide */
  403. #video-container:has(#video-controls.hidden) { cursor: none; }
  404. #progress-wrap {
  405. position: relative;
  406. height: 4px;
  407. background: rgba(255,255,255,0.25);
  408. border-radius: 4px;
  409. cursor: pointer;
  410. margin-bottom: 12px;
  411. }
  412. #progress-bar {
  413. height: 100%; border-radius: 4px;
  414. background: var(--accent);
  415. pointer-events: none;
  416. }
  417. #progress-wrap:hover { height: 6px; }
  418. /* Transparent hit-zone 16px above the visual bar */
  419. #progress-wrap::before {
  420. content: '';
  421. position: absolute;
  422. top: -16px; left: 0; right: 0;
  423. height: 16px;
  424. }
  425. #progress-thumb {
  426. position: absolute;
  427. top: 50%; transform: translateY(-50%);
  428. width: 14px; height: 14px;
  429. background: #fff; border-radius: 50%;
  430. pointer-events: none;
  431. display: none;
  432. }
  433. #progress-wrap:hover #progress-thumb { display: block; }
  434. #controls-row {
  435. display: flex;
  436. align-items: center;
  437. gap: 10px;
  438. }
  439. .ctrl-btn {
  440. background: none; border: none; cursor: pointer;
  441. color: #fff; padding: 4px;
  442. line-height: 1;
  443. transition: opacity var(--transition);
  444. outline: none;
  445. display: flex; align-items: center; justify-content: center;
  446. }
  447. .ctrl-btn img { width: 24px; height: 24px; display: block; }
  448. .ctrl-cc-icon {
  449. width: 24px; height: 24px;
  450. display: flex; align-items: center; justify-content: center;
  451. font-size: 10px; font-weight: 700; letter-spacing: 0.4px;
  452. border: 1.5px solid #fff; border-radius: 4px; line-height: 1;
  453. }
  454. .ctrl-btn:hover { opacity: 0.7; }
  455. .ctrl-btn.focused { background: rgba(10,132,255,0.18); border-radius: 6px; }
  456. #volume-wrap { display: flex; align-items: center; gap: 8px; }
  457. #volume-slider {
  458. -webkit-appearance: none;
  459. width: 80px; height: 4px;
  460. background: rgba(255,255,255,0.3);
  461. border-radius: 4px; outline: none;
  462. }
  463. #volume-slider::-webkit-slider-thumb {
  464. -webkit-appearance: none;
  465. width: 12px; height: 12px;
  466. background: #fff; border-radius: 50%;
  467. }
  468. /* Portrait phones/tablets drive playback volume with the hardware keys, so the
  469. in-page slider only eats toolbar width. Users who want it back can force it
  470. on from the player settings popup ("Volume bar → Always show"). */
  471. @media (max-width: 899px) and (orientation: portrait) {
  472. #volume-slider { display: none; }
  473. }
  474. body.always-show-volume #volume-slider { display: block; }
  475. /* ─── Centre play/pause flash indicator ──────────────────────────────────────── */
  476. #play-flash {
  477. position: absolute;
  478. top: 50%; left: 50%;
  479. width: 88px; height: 88px;
  480. margin: -44px 0 0 -44px;
  481. border-radius: 50%;
  482. background: rgba(0,0,0,0.55);
  483. backdrop-filter: blur(4px);
  484. -webkit-backdrop-filter: blur(4px);
  485. display: flex; align-items: center; justify-content: center;
  486. pointer-events: none;
  487. opacity: 0;
  488. z-index: 18;
  489. }
  490. #play-flash img { width: 40px; height: 40px; display: block; }
  491. #play-flash.flash { animation: playFlash 0.62s ease-out; }
  492. @keyframes playFlash {
  493. 0% { opacity: 0; transform: scale(0.68); }
  494. 18% { opacity: 0.95; transform: scale(0.92); }
  495. 100% { opacity: 0; transform: scale(1.32); }
  496. }
  497. /* ─── ASS subtitle overlay ───────────────────────────────────────────────────── */
  498. /* Sized in JS to the video's displayed rect so script coordinates land correctly
  499. regardless of letterboxing. Children are absolutely positioned by the renderer. */
  500. #ass-overlay {
  501. display: none;
  502. position: absolute;
  503. left: 0; top: 0; width: 0; height: 0;
  504. pointer-events: none;
  505. overflow: hidden;
  506. /* No z-index on purpose: subtitles sit directly after <video> in the DOM,
  507. so they paint above the (unpositioned) video but below every later
  508. positioned sibling — scrub preview, controls, menus and modals all stay
  509. on top of the text instead of being covered by it. */
  510. /* ...but that only holds if the cues stay *inside* this box. The renderer
  511. gives each cue an inline z-index so simultaneous lines stack in event
  512. order (see ass.js boxCss), and a positioned element with z-index:auto is
  513. not a stacking context — so those cues would otherwise be promoted into
  514. the player's stacking context and outrank the controls, which are
  515. themselves z-index:auto. Isolating creates the stacking context that keeps
  516. cue ordering internal, without giving this layer a z-index of its own. */
  517. isolation: isolate;
  518. }
  519. #ass-overlay.active { display: block; }
  520. /* ─── Scrub-bar hover preview ────────────────────────────────────────────────── */
  521. #scrub-preview {
  522. display: none;
  523. position: absolute;
  524. bottom: 100%;
  525. margin-bottom: 12px;
  526. transform: translateX(-50%);
  527. pointer-events: none;
  528. /* Above the centre play/pause flash, so scrubbing right after a click
  529. does not put the thumbnail behind it. (ASS cues no longer need
  530. outranking here — #ass-overlay isolates them.) */
  531. z-index: 20;
  532. flex-direction: column;
  533. align-items: center;
  534. gap: 6px;
  535. }
  536. #scrub-preview.active { display: flex; }
  537. #scrub-preview-thumb {
  538. display: none;
  539. border-radius: 8px;
  540. background-color: #000;
  541. background-repeat: no-repeat;
  542. box-shadow: 0 4px 18px rgba(0,0,0,0.8), 0 0 0 2px rgba(255,255,255,0.14);
  543. }
  544. #scrub-preview-thumb.ready { display: block; }
  545. #scrub-preview-time {
  546. background: rgba(0,0,0,0.82);
  547. border-radius: 6px;
  548. padding: 3px 9px;
  549. font-size: 12px;
  550. font-weight: 600;
  551. color: #fff;
  552. white-space: nowrap;
  553. font-variant-numeric: tabular-nums;
  554. }
  555. /* ─── Transcode-seek freeze frame ────────────────────────────────────────────── */
  556. /* Deliberately no z-index: both sit immediately after <video> in the DOM, so they
  557. paint above the (unpositioned) video but below every later positioned sibling
  558. — controls, top bar and menus all stay on top and clickable. */
  559. #seek-freeze {
  560. display: none;
  561. position: absolute; inset: 0;
  562. width: 100%; height: 100%;
  563. object-fit: contain;
  564. background: #000;
  565. pointer-events: none;
  566. }
  567. #seek-spinner {
  568. display: none;
  569. position: absolute; inset: 0;
  570. align-items: center; justify-content: center;
  571. pointer-events: none;
  572. }
  573. #seek-spinner.active { display: flex; }
  574. .seek-spinner-box {
  575. display: flex; flex-direction: column;
  576. align-items: center; gap: 10px;
  577. background: rgba(0,0,0,0.55);
  578. backdrop-filter: blur(4px);
  579. -webkit-backdrop-filter: blur(4px);
  580. border-radius: 14px;
  581. padding: 18px 24px;
  582. font-size: 12px; color: var(--text);
  583. }
  584. #time-display { font-size: 13px; color: rgba(255,255,255,0.8); margin-left: 6px; }
  585. #now-playing-title {
  586. font-size: 15px; font-weight: 600;
  587. flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  588. margin-left: 10px;
  589. }
  590. /* ─── Playlist sidebar ───────────────────────────────────────────────────────── */
  591. #playlist-sidebar {
  592. width: 300px;
  593. flex-shrink: 0;
  594. background: rgba(20,20,20,0.95);
  595. backdrop-filter: blur(12px);
  596. display: flex;
  597. flex-direction: column;
  598. border-left: 1px solid rgba(255,255,255,0.08);
  599. transform: translateX(0);
  600. transition: transform var(--transition), width var(--transition);
  601. }
  602. #playlist-sidebar.collapsed { width: 0; overflow: hidden; }
  603. #sidebar-header {
  604. padding: 14px 16px 10px;
  605. font-size: 15px; font-weight: 600;
  606. border-bottom: 1px solid rgba(255,255,255,0.08);
  607. display: flex; align-items: center; gap: 8px;
  608. }
  609. #sidebar-close {
  610. margin-left: auto;
  611. background: none; border: none; cursor: pointer;
  612. color: var(--text-sub); font-size: 18px; padding: 2px;
  613. outline: none;
  614. }
  615. #sidebar-close:hover { color: var(--text); }
  616. #sidebar-list { flex: 1; overflow-y: auto; padding: 8px; }
  617. #sidebar-list::-webkit-scrollbar { width: 3px; }
  618. #sidebar-list::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 3px; }
  619. .sidebar-ep {
  620. display: flex; align-items: center; gap: 10px;
  621. padding: 8px;
  622. border-radius: 8px; cursor: pointer;
  623. transition: background var(--transition);
  624. font-size: 13px; color: var(--text);
  625. outline: none;
  626. }
  627. .sidebar-ep:hover, .sidebar-ep.focused { background: var(--surface2); }
  628. .sidebar-ep.playing { background: rgba(10,132,255,0.2); color: var(--accent); }
  629. .sidebar-ep-num { flex-shrink: 0; width: 24px; text-align: center; color: var(--text-sub); font-size: 12px; }
  630. .sidebar-ep-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  631. /* ─── Player top bar (back btn + small-screen extras) ────────────────────────── */
  632. #player-topbar {
  633. position: absolute;
  634. top: 0; left: 0; right: 0;
  635. z-index: 10;
  636. display: flex;
  637. align-items: center;
  638. padding: 8px 10px;
  639. gap: 8px;
  640. /* transparent on large screens — only back button visible */
  641. }
  642. #player-back {
  643. flex-shrink: 0;
  644. background: rgba(0,0,0,0.55);
  645. backdrop-filter: blur(8px);
  646. border: none; cursor: pointer;
  647. border-radius: 20px;
  648. color: #fff;
  649. font-size: 13px; font-weight: 500;
  650. padding: 7px 16px;
  651. transition: background var(--transition);
  652. outline: none;
  653. }
  654. #player-back:hover { background: var(--accent); }
  655. /* Title + list + cast buttons shown only in topbar on small screens */
  656. #topbar-title {
  657. display: none;
  658. flex: 1;
  659. font-size: 13px; font-weight: 600;
  660. overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  661. color: #fff;
  662. margin: 0 2px;
  663. }
  664. #ctrl-cast-top, #ctrl-list-top { display: none; }
  665. @media (max-width: 600px) {
  666. #player-topbar {
  667. background: rgba(0,0,0,0.88);
  668. backdrop-filter: blur(10px);
  669. }
  670. #topbar-title, #ctrl-cast-top, #ctrl-list-top { display: flex; align-items: center; }
  671. #topbar-title { display: block; }
  672. /* Hide these from the bottom controls bar */
  673. #now-playing-title, #ctrl-list, #ctrl-cast { display: none !important; }
  674. /* Push the settings + fullscreen pair right now that the title spacer is gone */
  675. #ctrl-settings { margin-left: auto; }
  676. /* Shrink volume slider to save space */
  677. #volume-slider { width: 56px; }
  678. #time-display { font-size: 11px; }
  679. }
  680. /* Fullscreen: hide entire topbar */
  681. #view-player:fullscreen #player-topbar,
  682. #view-player:-webkit-full-screen #player-topbar,
  683. #view-player:-moz-full-screen #player-topbar { display: none !important; }
  684. /* ─── Toast notification ─────────────────────────────────────────────────────── */
  685. #toast {
  686. position: fixed;
  687. bottom: 30px; left: 50%;
  688. transform: translateX(-50%) translateY(20px);
  689. background: rgba(30,30,30,0.95);
  690. backdrop-filter: blur(8px);
  691. color: var(--text);
  692. padding: 10px 20px;
  693. border-radius: 20px;
  694. font-size: 13px;
  695. opacity: 0;
  696. transition: opacity 0.3s, transform 0.3s;
  697. pointer-events: none;
  698. z-index: 1000;
  699. max-width: min(90vw, 30em);
  700. text-align: center; line-height: 1.45;
  701. }
  702. #toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
  703. /* ─── Responsive ─────────────────────────────────────────────────────────────── */
  704. @media (max-width: 600px) {
  705. :root { --card-w: 130px; }
  706. #library-scroll { padding: 8px 12px 40px; }
  707. #detail-hero { height: 44vw; min-height: 160px; }
  708. #detail-poster { width: 80px; }
  709. #detail-title { font-size: 18px; }
  710. #playlist-sidebar { width: 100%; position: absolute; right: 0; top: 0; bottom: 0; z-index: 5; }
  711. #playlist-sidebar.collapsed { width: 0; }
  712. #episode-scroll { padding: 10px 12px 40px; }
  713. .ep-thumb { width: 72px; }
  714. }
  715. /* ─── Phone: wrap topbar so the search bar never overflows ───────────────────── */
  716. @media (max-width: 540px) {
  717. #topbar {
  718. flex-wrap: wrap;
  719. height: auto;
  720. min-height: var(--header-h);
  721. padding: 6px 14px;
  722. row-gap: 4px;
  723. align-items: center;
  724. }
  725. #topbar h1 { font-size: 18px; flex-shrink: 0; }
  726. #mode-tabs { flex-shrink: 0; }
  727. /* Force search onto its own row, full width */
  728. #search-wrap {
  729. flex-basis: 100%;
  730. margin-left: 0;
  731. order: 10;
  732. }
  733. #search-input { width: 100%; max-width: none; }
  734. #search-input:focus { width: 100%; }
  735. }
  736. @media (max-width: 400px) {
  737. :root { --card-w: 110px; }
  738. .mode-tab { padding: 5px 8px; font-size: 12px; }
  739. }
  740. /* TV / large screen layout */
  741. @media (min-width: 1400px) {
  742. :root { --card-w: 200px; }
  743. }
  744. @media (min-width: 1800px) {
  745. :root { --card-w: 240px; }
  746. }
  747. /* ─── Mode tabs ──────────────────────────────────────────────────────────────── */
  748. #mode-tabs { display: flex; gap: 2px; }
  749. .mode-tab {
  750. background: none; border: none; cursor: pointer;
  751. border-radius: 6px; color: var(--text-sub);
  752. font-size: 13px; font-weight: 500; padding: 5px 12px;
  753. transition: background var(--transition), color var(--transition);
  754. outline: none;
  755. }
  756. .mode-tab.active { background: var(--surface2); color: var(--text); }
  757. .mode-tab:hover { color: var(--text); }
  758. /* ─── Folder view ────────────────────────────────────────────────────────────── */
  759. #folder-nav-bar {
  760. flex-shrink: 0;
  761. padding: 6px 20px;
  762. display: flex;
  763. align-items: center;
  764. overflow-x: auto;
  765. scrollbar-width: none;
  766. border-bottom: 1px solid rgba(255,255,255,0.06);
  767. min-height: 40px;
  768. }
  769. #folder-nav-bar::-webkit-scrollbar { display: none; }
  770. #folder-breadcrumb { display: flex; align-items: center; gap: 2px; }
  771. .crumb-btn {
  772. background: none; border: none; cursor: pointer;
  773. color: var(--text-sub); font-size: 13px;
  774. padding: 3px 7px; border-radius: 5px;
  775. transition: color var(--transition), background var(--transition);
  776. outline: none; white-space: nowrap;
  777. }
  778. .crumb-btn:hover { color: var(--text); background: var(--surface2); }
  779. .crumb-btn.crumb-current { color: var(--text); font-weight: 600; pointer-events: none; }
  780. .crumb-sep { color: var(--text-sub); font-size: 12px; opacity: 0.4; padding: 0 2px; }
  781. #folder-scroll {
  782. flex: 1; overflow-y: auto; overflow-x: hidden;
  783. padding: 8px 20px 40px; scroll-behavior: smooth;
  784. }
  785. #folder-scroll::-webkit-scrollbar { width: 4px; }
  786. #folder-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
  787. #folder-loading {
  788. display: none; flex-direction: column; align-items: center;
  789. justify-content: center; padding: 60px 0; gap: 12px; color: var(--text-sub);
  790. }
  791. #folder-loading.active { display: flex; }
  792. #folder-empty { display: none; color: var(--text-sub); padding: 60px 0; text-align: center; }
  793. .folder-thumb {
  794. width: 100%; aspect-ratio: 16/9;
  795. background: linear-gradient(135deg, #1c2640 0%, #2a3d6e 100%);
  796. display: flex; align-items: center; justify-content: center;
  797. font-size: 32px; user-select: none;
  798. }
  799. /* ─── Settings view ──────────────────────────────────────────────────────────── */
  800. #settings-scroll {
  801. flex: 1; overflow-y: auto; overflow-x: hidden;
  802. padding: 14px 20px 48px; scroll-behavior: smooth;
  803. }
  804. #settings-scroll::-webkit-scrollbar { width: 4px; }
  805. #settings-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
  806. .settings-card {
  807. background: var(--surface);
  808. border-radius: var(--radius);
  809. padding: 4px 18px 6px;
  810. margin-bottom: 14px;
  811. }
  812. .settings-card-title {
  813. font-size: 12px; font-weight: 700; letter-spacing: 0.4px;
  814. text-transform: uppercase; color: var(--text-sub);
  815. padding: 14px 0 10px;
  816. }
  817. .settings-row {
  818. display: flex; align-items: center; gap: 16px;
  819. padding: 12px 0;
  820. border-top: 1px solid rgba(255,255,255,0.06);
  821. }
  822. .settings-row-text { flex: 1; min-width: 0; }
  823. .settings-row-label { font-size: 14px; font-weight: 600; margin-bottom: 3px; }
  824. .settings-row-desc { font-size: 12px; color: var(--text-sub); line-height: 1.45; }
  825. .settings-row-desc code {
  826. background: var(--surface2); border-radius: 4px;
  827. padding: 1px 6px; font-size: 11px;
  828. overflow-wrap: anywhere;
  829. }
  830. .settings-btn { flex-shrink: 0; padding: 8px 18px; font-size: 13px; }
  831. .settings-btn-danger:hover { background: rgba(255,69,58,0.22); color: #ff453a; }
  832. .settings-btn[disabled] { opacity: 0.4; cursor: default; transform: none; }
  833. /* Toggle switch */
  834. .settings-switch { flex-shrink: 0; cursor: pointer; display: block; }
  835. .settings-switch input { display: none; }
  836. .settings-switch-track {
  837. display: block; width: 42px; height: 24px;
  838. background: var(--surface2); border-radius: 12px;
  839. position: relative; transition: background 0.2s;
  840. }
  841. .settings-switch input:checked + .settings-switch-track { background: var(--accent2); }
  842. .settings-switch-track::after {
  843. content: '';
  844. position: absolute; top: 3px; left: 3px;
  845. width: 18px; height: 18px;
  846. background: #fff; border-radius: 50%;
  847. transition: transform 0.2s;
  848. }
  849. .settings-switch input:checked + .settings-switch-track::after { transform: translateX(18px); }
  850. /* Stats */
  851. .stats-grid {
  852. display: grid;
  853. grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  854. gap: 10px;
  855. padding: 4px 0 12px;
  856. }
  857. .stat-box {
  858. background: var(--surface2);
  859. border-radius: calc(var(--radius) - 4px);
  860. padding: 12px 14px;
  861. }
  862. .stat-value { font-size: 20px; font-weight: 700; line-height: 1.2; overflow-wrap: anywhere; }
  863. .stat-label { font-size: 11px; color: var(--text-sub); margin-top: 3px; }
  864. .settings-breakdown {
  865. display: flex; flex-wrap: wrap; gap: 6px;
  866. padding-bottom: 10px;
  867. }
  868. .breakdown-chip {
  869. background: var(--surface2); border-radius: 20px;
  870. font-size: 11px; color: var(--text-sub);
  871. padding: 4px 11px;
  872. }
  873. .breakdown-chip b { color: var(--text); font-weight: 600; }
  874. .settings-meta {
  875. font-size: 11px; color: var(--text-sub);
  876. border-top: 1px solid rgba(255,255,255,0.06);
  877. padding: 10px 0 12px;
  878. }
  879. .settings-progress {
  880. display: none; align-items: center; gap: 8px;
  881. font-size: 12px; color: var(--text-sub);
  882. border-top: 1px solid rgba(255,255,255,0.06);
  883. padding: 12px 0;
  884. }
  885. .settings-progress.active { display: flex; }
  886. @media (max-width: 600px) {
  887. #settings-scroll { padding: 12px 12px 48px; }
  888. .settings-card { padding: 4px 14px 6px; }
  889. .settings-row { flex-wrap: wrap; gap: 10px; }
  890. .settings-btn { width: 100%; }
  891. }
  892. /* ─── Movie info panel ───────────────────────────────────────────────────────── */
  893. #view-movie-info { position: relative; }
  894. #movie-info-backdrop {
  895. position: absolute; inset: 0;
  896. background-size: cover; background-position: center 20%;
  897. filter: blur(4px) brightness(0.38);
  898. transform: scale(1.12); z-index: 0;
  899. }
  900. #movie-info-back {
  901. position: absolute; top: 14px; left: 16px; z-index: 10;
  902. background: rgba(0,0,0,0.5); backdrop-filter: blur(8px);
  903. border: none; cursor: pointer; border-radius: 20px;
  904. color: var(--text); font-size: 13px; font-weight: 500;
  905. padding: 6px 16px; transition: background var(--transition); outline: none;
  906. }
  907. #movie-info-back:hover { background: var(--accent); }
  908. #movie-info-scroll {
  909. flex: 1; overflow-y: auto; overflow-x: hidden;
  910. scroll-behavior: smooth; position: relative; z-index: 1;
  911. }
  912. #movie-info-scroll::-webkit-scrollbar { width: 4px; }
  913. #movie-info-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
  914. #movie-info-hero {
  915. min-height: 280px; display: flex; align-items: flex-end; gap: 24px;
  916. padding: 70px 32px 28px;
  917. }
  918. #movie-info-poster-wrap {
  919. width: 130px; flex-shrink: 0; border-radius: 10px; overflow: hidden;
  920. box-shadow: 0 12px 32px rgba(0,0,0,0.7);
  921. aspect-ratio: 2/3; background: var(--surface2);
  922. }
  923. #movie-info-poster-wrap img { width: 100%; height: 100%; object-fit: cover; display: block; }
  924. #movie-info-meta { flex: 1; min-width: 0; }
  925. #movie-info-title { font-size: 26px; font-weight: 700; line-height: 1.15; margin-bottom: 2px; overflow-wrap: anywhere; }
  926. #movie-info-filename {
  927. font-size: 11px; color: var(--text-sub); opacity: 0.6;
  928. font-style: italic; margin-bottom: 6px;
  929. overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  930. display: none; /* shown only after IMDB title replaces the album name */
  931. }
  932. #movie-info-year { font-size: 14px; color: var(--text-sub); margin-bottom: 8px; }
  933. #movie-info-cast { font-size: 13px; color: var(--text-sub); line-height: 1.5; margin-bottom: 14px; }
  934. #movie-info-actions { display: flex; gap: 10px; flex-wrap: wrap; }
  935. .yt-badge {
  936. display: inline-flex; align-items: center;
  937. background: #ff0000; color: #fff;
  938. border-radius: 5px; font-size: 12px; font-weight: 800;
  939. padding: 5px 9px; cursor: pointer; border: none; outline: none;
  940. transition: opacity var(--transition);
  941. }
  942. .yt-badge:hover { opacity: 0.8; }
  943. .imdb-badge {
  944. display: inline-flex; align-items: center;
  945. background: #f5c518; color: #000;
  946. border-radius: 5px; font-size: 12px; font-weight: 800;
  947. padding: 5px 9px; cursor: pointer; border: none; outline: none;
  948. transition: opacity var(--transition);
  949. }
  950. .imdb-badge:hover { opacity: 0.8; }
  951. #movie-info-loading {
  952. display: none; flex-direction: column; align-items: center;
  953. justify-content: center; padding: 28px 0; gap: 10px; color: var(--text-sub);
  954. }
  955. #movie-info-loading.active { display: flex; }
  956. #movie-info-files { padding: 0 20px 48px; }
  957. #movie-info-wrong-wrap {
  958. display: none;
  959. padding: 10px 32px 0;
  960. }
  961. .reset-info-btn {
  962. background: none;
  963. border: 1px solid rgba(255,255,255,0.12);
  964. color: var(--text-sub);
  965. font-size: 11px; font-weight: 500;
  966. padding: 4px 12px;
  967. border-radius: 6px;
  968. cursor: pointer; outline: none;
  969. transition: border-color var(--transition), color var(--transition);
  970. }
  971. .reset-info-btn:hover { border-color: rgba(255,69,58,0.55); color: #ff453a; }
  972. @media (max-width: 600px) {
  973. #movie-info-hero { flex-direction: column; align-items: flex-start; padding: 56px 16px 20px; }
  974. #movie-info-poster-wrap { width: 90px; }
  975. #movie-info-title { font-size: 20px; }
  976. #movie-info-files { padding: 0 12px 48px; }
  977. }
  978. /* ─── Resume popup ───────────────────────────────────────────────────────────── */
  979. #resume-popup {
  980. display: none;
  981. position: absolute; bottom: 90px; right: 20px; z-index: 25;
  982. background: rgba(22,22,24,0.97); backdrop-filter: blur(16px);
  983. border-radius: 12px; padding: 16px 18px; min-width: 240px;
  984. box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.1);
  985. animation: slideUpPopup 0.2s ease;
  986. }
  987. #resume-popup.active { display: block; }
  988. @keyframes slideUpPopup {
  989. from { opacity: 0; transform: translateY(10px); }
  990. to { opacity: 1; transform: translateY(0); }
  991. }
  992. #resume-popup-title { font-size: 13px; font-weight: 600; margin-bottom: 4px; }
  993. #resume-popup-sub { font-size: 12px; color: var(--text-sub); margin-bottom: 12px; }
  994. #resume-popup-btns { display: flex; gap: 8px; }
  995. .resume-btn {
  996. flex: 1; padding: 8px; border: none; cursor: pointer;
  997. border-radius: 7px; font-size: 12px; font-weight: 600;
  998. outline: none; transition: opacity var(--transition);
  999. }
  1000. .resume-btn:hover { opacity: 0.8; }
  1001. #resume-btn-continue { background: var(--accent); color: #fff; }
  1002. #resume-btn-restart { background: var(--surface2); color: var(--text); }
  1003. /* Focus ring for TV remote navigation */
  1004. .tv-focused {
  1005. outline: 3px solid var(--accent) !important;
  1006. outline-offset: 2px !important;
  1007. }
  1008. /* ─── Load More button ───────────────────────────────────────────────────────── */
  1009. .load-more-wrap { text-align: center; padding: 16px 0 24px; }
  1010. .load-more-btn {
  1011. background: var(--surface2);
  1012. border: 1px solid rgba(255,255,255,0.08); cursor: pointer;
  1013. border-radius: 8px; color: var(--text);
  1014. font-size: 13px; font-weight: 500; padding: 9px 28px;
  1015. outline: none; transition: background var(--transition), box-shadow var(--transition);
  1016. }
  1017. .load-more-btn:hover { background: rgba(255,255,255,0.08); box-shadow: 0 0 0 1px var(--accent); }
  1018. /* ─── Autoplay toggle (sidebar) ─────────────────────────────────────────────── */
  1019. .autoplay-label {
  1020. display: flex; align-items: center; gap: 5px;
  1021. font-size: 11px; color: var(--text-sub);
  1022. cursor: pointer; user-select: none;
  1023. font-weight: 500;
  1024. }
  1025. .autoplay-label input[type="checkbox"] { display: none; }
  1026. .autoplay-track {
  1027. width: 30px; height: 17px;
  1028. background: var(--surface2); border-radius: 9px;
  1029. position: relative; flex-shrink: 0;
  1030. transition: background 0.2s;
  1031. }
  1032. .autoplay-label input:checked + .autoplay-track { background: var(--accent2); }
  1033. .autoplay-track::after {
  1034. content: '';
  1035. position: absolute; top: 2px; left: 2px;
  1036. width: 13px; height: 13px;
  1037. background: #fff; border-radius: 50%;
  1038. transition: transform 0.2s;
  1039. }
  1040. .autoplay-label input:checked + .autoplay-track::after { transform: translateX(13px); }
  1041. /* ─── Next-episode countdown ────────────────────────────────────────────────── */
  1042. #next-countdown {
  1043. display: none;
  1044. position: absolute; bottom: 80px; right: 20px;
  1045. background: rgba(20,20,20,0.92);
  1046. backdrop-filter: blur(8px);
  1047. border-radius: 10px; padding: 12px 16px;
  1048. min-width: 210px; z-index: 20;
  1049. }
  1050. #next-countdown-text { font-size: 13px; color: var(--text-sub); margin-bottom: 8px; }
  1051. #next-countdown-track {
  1052. height: 4px; background: var(--surface2);
  1053. border-radius: 4px; margin-bottom: 8px; overflow: hidden;
  1054. }
  1055. #next-countdown-bar { height: 100%; background: var(--accent); border-radius: 4px; transition: width 1s linear; }
  1056. #next-countdown-cancel {
  1057. display: block; width: 100%; background: var(--surface2);
  1058. border: none; cursor: pointer; border-radius: 6px;
  1059. color: var(--text); font-size: 12px; padding: 5px; outline: none;
  1060. transition: background var(--transition);
  1061. }
  1062. #next-countdown-cancel:hover { background: rgba(255,59,48,0.28); }
  1063. /* ─── Playback settings popup (gear button) ──────────────────────────────────── */
  1064. #settings-popup {
  1065. display: none;
  1066. position: absolute;
  1067. right: 20px; bottom: 62px;
  1068. z-index: 35;
  1069. background: rgba(28,28,30,0.97);
  1070. backdrop-filter: blur(16px);
  1071. -webkit-backdrop-filter: blur(16px);
  1072. border-radius: 10px;
  1073. padding: 6px 0;
  1074. width: 236px;
  1075. box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
  1076. color: var(--text);
  1077. user-select: none;
  1078. overflow-y: auto;
  1079. max-height: 320px;
  1080. }
  1081. #settings-popup.active { display: block; }
  1082. #settings-popup::-webkit-scrollbar,
  1083. #subtitle-popup::-webkit-scrollbar { width: 8px; }
  1084. #settings-popup::-webkit-scrollbar-track,
  1085. #subtitle-popup::-webkit-scrollbar-track { background: transparent; }
  1086. #settings-popup::-webkit-scrollbar-thumb,
  1087. #subtitle-popup::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.18); border-radius: 4px; }
  1088. #settings-popup::-webkit-scrollbar-thumb:hover,
  1089. #subtitle-popup::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.3); }
  1090. /* ─── Subtitle popup (dedicated CC button) ───────────────────────────────────── */
  1091. #subtitle-popup {
  1092. display: none;
  1093. position: absolute;
  1094. right: 20px; bottom: 62px;
  1095. z-index: 35;
  1096. background: rgba(28,28,30,0.97);
  1097. backdrop-filter: blur(16px);
  1098. -webkit-backdrop-filter: blur(16px);
  1099. border-radius: 10px;
  1100. padding: 4px 0;
  1101. min-width: 220px;
  1102. box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
  1103. color: var(--text);
  1104. user-select: none;
  1105. overflow-y: auto;
  1106. max-height: 320px;
  1107. }
  1108. #subtitle-popup.active { display: block; }
  1109. .set-section { padding: 6px 14px 8px; }
  1110. .set-section + .set-section { border-top: 1px solid rgba(255,255,255,0.08); }
  1111. .set-head {
  1112. display: flex; align-items: center; gap: 8px;
  1113. font-size: 11px; font-weight: 600; letter-spacing: 0.3px;
  1114. text-transform: uppercase; color: var(--text-sub);
  1115. margin-bottom: 7px;
  1116. }
  1117. .set-head img { width: 14px; height: 14px; opacity: 0.7; display: block; }
  1118. .set-seg {
  1119. display: flex; background: var(--surface2);
  1120. border-radius: 7px; padding: 2px; gap: 2px;
  1121. }
  1122. .set-seg-btn {
  1123. flex: 1; padding: 5px 0; font-size: 12px; font-family: inherit;
  1124. border: none; border-radius: 5px; cursor: pointer;
  1125. background: transparent; color: var(--text-sub);
  1126. transition: background 0.15s, color 0.15s; outline: none;
  1127. }
  1128. .set-seg-btn:hover { color: var(--text); }
  1129. .set-seg-btn.active { background: var(--surface); color: var(--text); }
  1130. .speed-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; }
  1131. .speed-btn {
  1132. padding: 5px 0; font-size: 12px; font-family: inherit;
  1133. border: none; border-radius: 5px; cursor: pointer;
  1134. background: var(--surface2); color: var(--text-sub);
  1135. transition: background 0.15s, color 0.15s; outline: none;
  1136. }
  1137. .speed-btn:hover { color: var(--text); }
  1138. .speed-btn.active { background: var(--accent); color: #fff; font-weight: 600; }
  1139. .quality-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
  1140. .set-head-note { margin-left: auto; text-transform: none; letter-spacing: 0; font-weight: 500; }
  1141. .set-link {
  1142. display: flex; align-items: center; gap: 9px;
  1143. padding: 8px 14px; font-size: 13px; cursor: pointer;
  1144. color: var(--text); transition: background var(--transition);
  1145. }
  1146. .set-link:hover { background: rgba(255,255,255,0.08); }
  1147. .set-link img { width: 15px; height: 15px; opacity: 0.8; display: block; }
  1148. /* ─── Player context menu ────────────────────────────────────────────────────── */
  1149. #player-ctx {
  1150. display: none;
  1151. position: absolute;
  1152. z-index: 30;
  1153. background: rgba(28,28,30,0.97);
  1154. backdrop-filter: blur(16px);
  1155. -webkit-backdrop-filter: blur(16px);
  1156. border-radius: 10px;
  1157. padding: 4px 0;
  1158. min-width: 192px;
  1159. box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
  1160. user-select: none;
  1161. }
  1162. .ctx-item {
  1163. padding: 9px 14px;
  1164. font-size: 13px;
  1165. cursor: pointer;
  1166. display: flex;
  1167. align-items: center;
  1168. gap: 10px;
  1169. color: var(--text);
  1170. transition: background var(--transition);
  1171. }
  1172. .ctx-item:hover { background: rgba(255,255,255,0.08); }
  1173. .ctx-item.ctx-active { color: var(--accent); }
  1174. .ctx-item.ctx-disabled { opacity: 0.3; pointer-events: none; }
  1175. .ctx-icon { width: 16px; text-align: center; flex-shrink: 0; font-style: normal; }
  1176. img.ctx-icon { height: 16px; opacity: 0.85; display: block; }
  1177. .ctx-divider { height: 1px; background: rgba(255,255,255,0.08); margin: 3px 0; }
  1178. .ctx-has-sub { justify-content: space-between; position: relative; }
  1179. .ctx-sub-arrow { font-style: normal; opacity: 0.55; font-size: 15px; }
  1180. /* Subtitle submenu — positioned relative to the parent .ctx-has-sub item */
  1181. #ctx-subtitle-sub {
  1182. display: none;
  1183. position: absolute;
  1184. top: 0;
  1185. left: 100%;
  1186. margin-left: 0;
  1187. background: rgba(28,28,30,0.97);
  1188. backdrop-filter: blur(16px);
  1189. -webkit-backdrop-filter: blur(16px);
  1190. border-radius: 10px;
  1191. padding: 4px 0;
  1192. min-width: 200px;
  1193. box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
  1194. z-index: 32;
  1195. overflow-y: auto;
  1196. max-height: 320px;
  1197. }
  1198. #ctx-subtitle-sub::-webkit-scrollbar { width: 8px; }
  1199. #ctx-subtitle-sub::-webkit-scrollbar-track { background: transparent; }
  1200. #ctx-subtitle-sub::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.18); border-radius: 4px; }
  1201. #ctx-subtitle-sub::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.3); }
  1202. /* Subtitle overlay */
  1203. #subtitle-display {
  1204. display: none;
  1205. position: absolute;
  1206. bottom: 72px;
  1207. left: 50%;
  1208. transform: translateX(-50%);
  1209. width: 90%;
  1210. text-align: center;
  1211. pointer-events: none; /* z-index deliberately unset, see #ass-overlay */
  1212. color: #fff;
  1213. font-size: 22px;
  1214. font-weight: 500;
  1215. line-height: 1.45;
  1216. text-shadow:
  1217. -1px -1px 0 #000, 1px -1px 0 #000,
  1218. -1px 1px 0 #000, 1px 1px 0 #000,
  1219. 0 2px 6px rgba(0,0,0,0.85);
  1220. }
  1221. /* ─── Subtitle settings modal ───────────────────────────────────────────────── */
  1222. #subtitle-settings-modal {
  1223. display: none;
  1224. position: absolute;
  1225. top: 50%; left: 50%;
  1226. transform: translate(-50%, -50%);
  1227. z-index: 40;
  1228. background: rgba(18,18,20,0.97);
  1229. backdrop-filter: blur(20px);
  1230. -webkit-backdrop-filter: blur(20px);
  1231. border-radius: 14px;
  1232. padding: 20px 22px 18px;
  1233. width: 340px;
  1234. box-shadow: 0 8px 40px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.1);
  1235. color: var(--text);
  1236. }
  1237. #subtitle-settings-modal h3 {
  1238. font-size: 14px; font-weight: 600;
  1239. margin-bottom: 14px;
  1240. display: flex; align-items: center; justify-content: space-between;
  1241. }
  1242. #sset-close {
  1243. background: none; border: none; cursor: pointer;
  1244. color: var(--text-sub); font-size: 17px; line-height: 1; padding: 0; outline: none;
  1245. }
  1246. #sset-close img { width: 14px; height: 14px; display: block; opacity: 0.55; transition: opacity var(--transition); }
  1247. #sset-close:hover img { opacity: 1; }
  1248. .sset-row {
  1249. display: flex; align-items: center; gap: 10px;
  1250. padding: 8px 0;
  1251. border-bottom: 1px solid rgba(255,255,255,0.05);
  1252. font-size: 12px;
  1253. }
  1254. .sset-row:last-child { border-bottom: none; }
  1255. .sset-label { color: var(--text-sub); flex-shrink: 0; width: 56px; }
  1256. .sset-seg {
  1257. display: flex; background: var(--surface2);
  1258. border-radius: 7px; padding: 2px; gap: 2px; flex: 1;
  1259. }
  1260. .sset-seg-btn {
  1261. flex: 1; padding: 4px 0; font-size: 12px; font-family: inherit;
  1262. border: none; border-radius: 5px; cursor: pointer;
  1263. background: transparent; color: var(--text-sub);
  1264. transition: background 0.15s, color 0.15s;
  1265. }
  1266. .sset-seg-btn.active { background: var(--surface); color: var(--text); }
  1267. #sset-size { flex: 1; accent-color: var(--accent); cursor: pointer; }
  1268. #sset-size-val { color: var(--text-sub); font-size: 11px; min-width: 32px; text-align: right; }
  1269. #sset-font {
  1270. flex: 1; background: var(--surface2); color: var(--text);
  1271. border: 1px solid rgba(255,255,255,0.08); border-radius: 7px;
  1272. padding: 5px 8px; font-size: 12px; cursor: pointer; outline: none;
  1273. appearance: auto;
  1274. width: 100%;
  1275. }
  1276. .sset-colors { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; flex: 1; }
  1277. .sset-color {
  1278. width: 22px; height: 22px; border-radius: 50%;
  1279. border: 2px solid transparent; outline: 2px solid transparent;
  1280. cursor: pointer; padding: 0; flex-shrink: 0;
  1281. transition: outline-color 0.15s, transform 0.1s;
  1282. }
  1283. .sset-color:hover { transform: scale(1.12); }
  1284. .sset-color.active { outline-color: var(--text); transform: scale(1.15); }
  1285. #sset-color-custom {
  1286. width: 22px; height: 22px; border-radius: 50%;
  1287. border: 2px solid rgba(255,255,255,0.2); padding: 0;
  1288. cursor: pointer; background: transparent; flex-shrink: 0;
  1289. }
  1290. #sset-color-custom.active { border-color: var(--text); transform: scale(1.15); }
  1291. #sset-preview {
  1292. margin-top: 14px;
  1293. background: rgba(0,0,0,0.65);
  1294. border-radius: 8px;
  1295. padding: 14px 12px;
  1296. text-align: center;
  1297. line-height: 1.4;
  1298. }
  1299. /* ─── Video info modal ───────────────────────────────────────────────────────── */
  1300. #video-info-modal, #adv-settings-modal {
  1301. display: none;
  1302. position: absolute;
  1303. top: 50%; left: 50%;
  1304. transform: translate(-50%, -50%);
  1305. z-index: 40;
  1306. background: rgba(18,18,20,0.97);
  1307. backdrop-filter: blur(20px);
  1308. -webkit-backdrop-filter: blur(20px);
  1309. border-radius: 14px;
  1310. padding: 20px 22px 16px;
  1311. width: 340px;
  1312. box-shadow: 0 8px 40px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.1);
  1313. }
  1314. #video-info-modal h3, #adv-settings-modal h3 {
  1315. font-size: 14px; font-weight: 600;
  1316. margin-bottom: 12px;
  1317. display: flex; align-items: center; justify-content: space-between;
  1318. }
  1319. #video-info-close, #adv-settings-close {
  1320. background: none; border: none; cursor: pointer;
  1321. color: var(--text-sub); font-size: 17px; line-height: 1; padding: 0; outline: none;
  1322. }
  1323. #video-info-close img, #adv-settings-close img { width: 14px; height: 14px; display: block; opacity: 0.55; transition: opacity var(--transition); }
  1324. #video-info-close:hover img, #adv-settings-close:hover img { opacity: 1; }
  1325. /* Advanced settings modal rows — same switch as the Settings tab, tighter */
  1326. #adv-settings-modal { width: 380px; max-height: 70%; overflow-y: auto; }
  1327. .adv-row {
  1328. display: flex; align-items: center; gap: 14px;
  1329. padding: 10px 0;
  1330. border-top: 1px solid rgba(255,255,255,0.06);
  1331. }
  1332. .adv-row:first-child { border-top: none; }
  1333. .adv-row-text { flex: 1; min-width: 0; }
  1334. .adv-row-label { font-size: 13px; font-weight: 600; margin-bottom: 3px; }
  1335. .adv-row-desc { font-size: 11px; color: var(--text-sub); line-height: 1.45; }
  1336. #video-info-tabs {
  1337. display: flex; gap: 3px;
  1338. background: var(--surface2);
  1339. border-radius: 8px;
  1340. padding: 3px;
  1341. margin-bottom: 12px;
  1342. }
  1343. .info-tab {
  1344. flex: 1; text-align: center; padding: 5px 0;
  1345. font-size: 12px; font-weight: 500;
  1346. border-radius: 6px; cursor: pointer;
  1347. color: var(--text-sub);
  1348. transition: background var(--transition), color var(--transition);
  1349. }
  1350. .info-tab.active { background: var(--surface); color: var(--text); }
  1351. .info-row {
  1352. display: flex; gap: 8px;
  1353. padding: 5px 0;
  1354. border-bottom: 1px solid rgba(255,255,255,0.05);
  1355. font-size: 12px;
  1356. line-height: 1.4;
  1357. }
  1358. .info-row:last-child { border-bottom: none; }
  1359. .info-label { color: var(--text-sub); flex-shrink: 0; width: 110px; }
  1360. .info-value { color: var(--text); word-break: break-all; }
  1361. /* ─── Arozcast cast ──────────────────────────────────────────────────────────── */
  1362. #ctrl-cast img, #ctrl-cast-top img { opacity: 0.8; }
  1363. #ctrl-cast.casting img, #ctrl-cast-top.casting img { filter: none; opacity: 1; }
  1364. #ctrl-cast.casting, #ctrl-cast-top.casting { background: rgba(231,76,60,0.25); }
  1365. #cast-modal {
  1366. display: none;
  1367. position: fixed; inset: 0; z-index: 9999;
  1368. background: rgba(0,0,0,0.65);
  1369. align-items: center; justify-content: center;
  1370. }
  1371. #cast-modal.active { display: flex; }
  1372. .cast-dialog {
  1373. background: var(--surface);
  1374. border-radius: var(--radius);
  1375. padding: 1.4em 1.8em;
  1376. min-width: 260px;
  1377. color: var(--text);
  1378. font-family: inherit;
  1379. box-shadow: 0 8px 32px rgba(0,0,0,0.6);
  1380. }
  1381. .cast-dialog h4 { margin: 0 0 0.9em; font-size: 1em; font-weight: 600; }
  1382. .cast-dialog input[type=text] {
  1383. width: 100%; padding: 0.45em 0.7em;
  1384. border-radius: 8px; border: 1px solid rgba(255,255,255,0.12);
  1385. background: var(--surface2); color: var(--text);
  1386. font-size: 1.5em; letter-spacing: 0.35em; text-align: center;
  1387. box-sizing: border-box; margin-bottom: 0.7em; outline: none;
  1388. }
  1389. .cast-dialog input[type=text]:focus { border-color: var(--accent); }
  1390. .cast-err { color: #e74c3c; font-size: 0.82em; min-height: 1.2em; margin-bottom: 0.5em; }
  1391. .cast-status-line { font-size: 0.85em; color: var(--text-sub); margin-bottom: 0.7em; }
  1392. .cast-actions { display: flex; gap: 0.5em; justify-content: flex-end; }
  1393. .cast-actions button {
  1394. padding: 0.4em 1em; border-radius: 8px; border: none;
  1395. cursor: pointer; font-size: 0.88em; font-family: inherit;
  1396. }
  1397. .btn-cast-connect { background: var(--accent); color: #fff; }
  1398. .btn-cast-cancel { background: var(--surface2); color: var(--text-sub); }
  1399. .btn-cast-disc { background: #444; color: var(--text); }
  1400. </style>
  1401. </head>
  1402. <body>
  1403. <div id="app">
  1404. <!-- ─ Loading overlay ─────────────────────────────────────────────────── -->
  1405. <div id="loading-overlay">
  1406. <div class="spinner"></div>
  1407. <span>Loading library…</span>
  1408. </div>
  1409. <!-- ─ Top bar ─────────────────────────────────────────────────────────── -->
  1410. <div id="topbar">
  1411. <h1><img src="img/module_icon.png" width="22" height="22" alt="" style="vertical-align:middle;margin-right:6px;margin-top:-4px;"><span>Movie</span></h1>
  1412. <div id="mode-tabs">
  1413. <button class="mode-tab active" id="tab-library" onclick="switchTab('library')">Library</button>
  1414. <button class="mode-tab" id="tab-folder" onclick="switchTab('folder')">Browse</button>
  1415. <button class="mode-tab" id="tab-settings" onclick="switchTab('settings')">Settings</button>
  1416. </div>
  1417. <div id="search-wrap">
  1418. <input id="search-input" type="text" placeholder="Search…" autocomplete="off">
  1419. </div>
  1420. </div>
  1421. <!-- ═══════════════ LIBRARY VIEW ═══════════════════════════════════════ -->
  1422. <div id="view-library" class="view active">
  1423. <div id="library-status-bar">
  1424. <div class="spinner-sm" id="library-spinner"></div>
  1425. <span id="library-status-text"></span>
  1426. <button id="library-refresh-btn" onclick="refreshLibrary()" style="display:none">Refresh</button>
  1427. </div>
  1428. <div id="library-scroll">
  1429. <div id="no-content">
  1430. <div class="icon"><img src="img/icons/movie_white.svg" alt=""></div>
  1431. <div>No videos found. Place your videos in a <strong>Video/</strong> folder on any storage.</div>
  1432. </div>
  1433. <div id="movies-section" style="display:none">
  1434. <div class="section-title">Movies</div>
  1435. <div id="movies-grid" class="album-grid"></div>
  1436. <div class="load-more-wrap"><button class="load-more-btn" id="movies-load-more" style="display:none" onclick="loadMoreSection('movies')">Load more</button></div>
  1437. </div>
  1438. <div id="collections-section" style="display:none">
  1439. <div class="section-title">Collections</div>
  1440. <div id="collections-grid" class="album-grid"></div>
  1441. <div class="load-more-wrap"><button class="load-more-btn" id="collections-load-more" style="display:none" onclick="loadMoreSection('collections')">Load more</button></div>
  1442. </div>
  1443. <div id="series-section" style="display:none">
  1444. <div class="section-title">TV / Shows</div>
  1445. <div id="series-grid" class="album-grid"></div>
  1446. <div class="load-more-wrap"><button class="load-more-btn" id="shows-load-more" style="display:none" onclick="loadMoreSection('shows')">Load more</button></div>
  1447. </div>
  1448. <div id="anime-section" style="display:none">
  1449. <div class="section-title">Anime</div>
  1450. <div id="anime-grid" class="album-grid"></div>
  1451. <div class="load-more-wrap"><button class="load-more-btn" id="anime-load-more" style="display:none" onclick="loadMoreSection('anime')">Load more</button></div>
  1452. </div>
  1453. <div id="shorts-section" style="display:none">
  1454. <div class="section-title">Shorts</div>
  1455. <div id="shorts-grid" class="album-grid"></div>
  1456. <div class="load-more-wrap"><button class="load-more-btn" id="shorts-load-more" style="display:none" onclick="loadMoreSection('shorts')">Load more</button></div>
  1457. </div>
  1458. </div>
  1459. </div>
  1460. <!-- ═══════════════ DETAIL VIEW ════════════════════════════════════════ -->
  1461. <div id="view-detail" class="view">
  1462. <div id="detail-hero">
  1463. <div id="detail-hero-bg"></div>
  1464. <div id="detail-hero-content">
  1465. <div id="detail-poster"><div class="poster-placeholder"><img src="img/icons/movie_white.svg" alt=""></div></div>
  1466. <div id="detail-meta">
  1467. <div id="detail-title">Album Title</div>
  1468. <div id="detail-subtitle">0 episodes</div>
  1469. <div id="detail-actions">
  1470. <button class="btn btn-primary" id="btn-play-first"><img src="img/icons/play_black.svg" width="15" height="15" alt="" style="vertical-align:middle;margin-right:5px;">Play</button>
  1471. <button class="btn btn-secondary" id="btn-shuffle"><img src="img/icons/shuffle_white.svg" width="15" height="15" alt="" style="vertical-align:middle;margin-right:5px;">Shuffle</button>
  1472. </div>
  1473. </div>
  1474. </div>
  1475. </div>
  1476. <button id="detail-back" onclick="showLibrary()"><img src="img/icons/back_arrow_white.svg" width="14" height="14" alt="" style="vertical-align:middle;margin-right:4px;">Back</button>
  1477. <div id="season-tabs"></div>
  1478. <div id="episode-scroll">
  1479. <div id="episode-list"></div>
  1480. </div>
  1481. </div>
  1482. <!-- ═══════════════ MOVIE INFO VIEW ══════════════════════════════════════ -->
  1483. <div id="view-movie-info" class="view">
  1484. <div id="movie-info-backdrop"></div>
  1485. <button id="movie-info-back" onclick="closeMovieInfo()"><img src="img/icons/back_arrow_white.svg" width="14" height="14" alt="" style="vertical-align:middle;margin-right:4px;">Back</button>
  1486. <div id="movie-info-scroll">
  1487. <div id="movie-info-hero">
  1488. <div id="movie-info-poster-wrap">
  1489. <img id="movie-info-poster-img" src="img/thumbnail.png" alt="">
  1490. </div>
  1491. <div id="movie-info-meta">
  1492. <div id="movie-info-title"></div>
  1493. <div id="movie-info-filename"></div>
  1494. <div id="movie-info-year"></div>
  1495. <div id="movie-info-cast"></div>
  1496. <div id="movie-info-actions">
  1497. <button class="btn btn-primary" id="movie-info-play-btn"><img src="img/icons/play_black.svg" width="15" height="15" alt="" style="vertical-align:middle;margin-right:5px;">Play</button>
  1498. <button class="btn btn-secondary" id="movie-info-fm-btn">Open in Files</button>
  1499. <button class="yt-badge" id="movie-info-yt-btn"><svg viewBox="0 0 12 12" width="10" height="10" fill="currentColor" style="margin-right:5px;"><path d="M2.5 1.2 10 6l-7.5 4.8V1.2Z"/></svg>YouTube</button>
  1500. <button class="imdb-badge" id="movie-info-imdb-btn" style="display:none">IMDb</button>
  1501. </div>
  1502. </div>
  1503. </div>
  1504. <div id="movie-info-wrong-wrap">
  1505. <button class="reset-info-btn" id="movie-info-reset-btn"><svg viewBox="0 0 12 12" width="9" height="9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="margin-right:5px;"><path d="M2.5 2.5 9.5 9.5M9.5 2.5 2.5 9.5"/></svg>Wrong movie? Disable IMDB info</button>
  1506. </div>
  1507. <div id="movie-info-loading"><div class="spinner"></div><span>Loading info…</span></div>
  1508. <div id="movie-info-files" style="display:none">
  1509. <div class="section-title" style="font-size:16px;margin:16px 20px 10px;">Files</div>
  1510. <div id="movie-info-episode-list"></div>
  1511. </div>
  1512. </div>
  1513. </div>
  1514. <!-- ═══════════════ FOLDER VIEW ════════════════════════════════════════ -->
  1515. <div id="view-folder" class="view">
  1516. <div id="folder-nav-bar">
  1517. <div id="folder-breadcrumb"></div>
  1518. </div>
  1519. <div id="folder-scroll">
  1520. <div id="folder-loading"><div class="spinner"></div><span>Loading…</span></div>
  1521. <div id="folder-empty"></div>
  1522. <div id="folder-section-dirs" style="display:none">
  1523. <div class="section-title">Folders</div>
  1524. <div id="folder-dirs-grid" class="album-grid"></div>
  1525. </div>
  1526. <div id="folder-section-vids" style="display:none">
  1527. <div class="section-title">Videos</div>
  1528. <div id="folder-vids-grid" class="album-grid"></div>
  1529. </div>
  1530. </div>
  1531. </div>
  1532. <!-- ═══════════════ SETTINGS VIEW ══════════════════════════════════════ -->
  1533. <div id="view-settings" class="view">
  1534. <div id="settings-scroll">
  1535. <div class="settings-card">
  1536. <div class="settings-card-title">Indexing</div>
  1537. <div class="settings-row">
  1538. <div class="settings-row-text">
  1539. <div class="settings-row-label">Auto indexing</div>
  1540. <div class="settings-row-desc">
  1541. Scan your storage for new videos automatically when the app opens.
  1542. Turn this off if scanning is slow on large libraries — you can still
  1543. scan on demand below.
  1544. </div>
  1545. </div>
  1546. <label class="settings-switch" title="Toggle auto indexing">
  1547. <input type="checkbox" id="setting-auto-index">
  1548. <span class="settings-switch-track"></span>
  1549. </label>
  1550. </div>
  1551. <div class="settings-row">
  1552. <div class="settings-row-text">
  1553. <div class="settings-row-label">Index location</div>
  1554. <div class="settings-row-desc"><code>user:/.appdata/Movie/library_cache.json</code></div>
  1555. </div>
  1556. </div>
  1557. </div>
  1558. <div class="settings-card">
  1559. <div class="settings-card-title">Index status</div>
  1560. <div id="settings-stats-grid" class="stats-grid">
  1561. <div class="stat-box"><div class="stat-value" id="stat-size">–</div><div class="stat-label">Index file size</div></div>
  1562. <div class="stat-box"><div class="stat-value" id="stat-albums">–</div><div class="stat-label">Titles indexed</div></div>
  1563. <div class="stat-box"><div class="stat-value" id="stat-videos">–</div><div class="stat-label">Video files indexed</div></div>
  1564. <div class="stat-box"><div class="stat-value" id="stat-roots">–</div><div class="stat-label">Storage roots scanned</div></div>
  1565. </div>
  1566. <div id="settings-breakdown" class="settings-breakdown"></div>
  1567. <div class="settings-meta" id="settings-last-scan">Last scan: never</div>
  1568. </div>
  1569. <div class="settings-card">
  1570. <div class="settings-card-title">Maintenance</div>
  1571. <div class="settings-row">
  1572. <div class="settings-row-text">
  1573. <div class="settings-row-label">Rescan library</div>
  1574. <div class="settings-row-desc">Walk every storage root again and rebuild the index from scratch.</div>
  1575. </div>
  1576. <button class="btn btn-primary settings-btn" id="settings-scan-btn">Scan now</button>
  1577. </div>
  1578. <div class="settings-row">
  1579. <div class="settings-row-text">
  1580. <div class="settings-row-label">Clear index</div>
  1581. <div class="settings-row-desc">
  1582. Delete the cached scan result. Your video files are never touched —
  1583. only the index is removed.
  1584. </div>
  1585. </div>
  1586. <button class="btn btn-secondary settings-btn settings-btn-danger" id="settings-clear-btn">Clear index</button>
  1587. </div>
  1588. <div id="settings-progress" class="settings-progress">
  1589. <div class="spinner-sm"></div><span id="settings-progress-text">Scanning…</span>
  1590. </div>
  1591. </div>
  1592. </div>
  1593. </div>
  1594. <!-- ═══════════════ PLAYER VIEW ════════════════════════════════════════ -->
  1595. <div id="view-player" class="view">
  1596. <div id="video-container">
  1597. <div id="player-topbar">
  1598. <button id="player-back" onclick="closePlayer()"><img src="img/icons/back_arrow_white.svg" width="14" height="14" alt="" style="vertical-align:middle;margin-right:4px;">Back</button>
  1599. <span id="topbar-title"></span>
  1600. <button class="ctrl-btn" id="ctrl-list-top" onclick="toggleSidebar()" title="Episode list"><img src="img/icons/menu_white.svg" alt="" width="18" height="18"></button>
  1601. <button class="ctrl-btn" id="ctrl-cast-top" title="Cast to Arozcast" onclick="openCastDialog()"><img src="img/icons/cast_white.svg" alt="" width="18" height="18"></button>
  1602. </div>
  1603. <video id="main-video" preload="metadata"></video>
  1604. <!-- Frozen last frame + spinner, shown while a transcode seek re-buffers.
  1605. Must stay directly after <video> — stacking relies on DOM order. -->
  1606. <canvas id="seek-freeze"></canvas>
  1607. <div id="seek-spinner">
  1608. <div class="seek-spinner-box">
  1609. <div class="spinner"></div>
  1610. <span>Buffering…</span>
  1611. </div>
  1612. </div>
  1613. <!-- Styled ASS/SSA subtitles are drawn here, sized to the video's
  1614. displayed rectangle. The plain #subtitle-display below is used
  1615. for SubRip tracks. -->
  1616. <div id="ass-overlay"></div>
  1617. <div id="subtitle-display"></div>
  1618. <!-- Centre play/pause flash indicator -->
  1619. <div id="play-flash"><img id="play-flash-icon" src="img/icons/play_white.svg" alt=""></div>
  1620. <!-- Resume-from-last-position popup -->
  1621. <div id="resume-popup">
  1622. <div id="resume-popup-title">Resume playback?</div>
  1623. <div id="resume-popup-sub"></div>
  1624. <div id="resume-popup-btns">
  1625. <button class="resume-btn" id="resume-btn-continue">Resume</button>
  1626. <button class="resume-btn" id="resume-btn-restart">Start over</button>
  1627. </div>
  1628. </div>
  1629. <!-- Auto-play countdown -->
  1630. <div id="next-countdown">
  1631. <div id="next-countdown-text">Next episode in <span id="countdown-num">5</span>s&hellip;</div>
  1632. <div id="next-countdown-track"><div id="next-countdown-bar" style="width:100%"></div></div>
  1633. <button id="next-countdown-cancel" onclick="cancelCountdown()">Cancel</button>
  1634. </div>
  1635. <!-- Player context menu -->
  1636. <div id="player-ctx">
  1637. <div class="ctx-item" id="ctx-play"><img class="ctx-icon" src="img/icons/play_white.svg" alt="">Play</div>
  1638. <div class="ctx-item" id="ctx-pause"><img class="ctx-icon" src="img/icons/pause_white.svg" alt="">Pause</div>
  1639. <div class="ctx-divider"></div>
  1640. <div class="ctx-item" id="ctx-prev"><img class="ctx-icon" src="img/icons/skip_previous_white.svg" alt="">Previous</div>
  1641. <div class="ctx-item" id="ctx-next"><img class="ctx-icon" src="img/icons/skip_next_white.svg" alt="">Next</div>
  1642. <div class="ctx-divider"></div>
  1643. <div class="ctx-item" id="ctx-repeat"><img class="ctx-icon" src="img/icons/repeat_white.svg" alt="">Repeat: Off</div>
  1644. <div class="ctx-divider"></div>
  1645. <div class="ctx-item ctx-has-sub" id="ctx-subtitle-parent">
  1646. <span><i class="ctx-icon" style="display:inline-block">CC</i>Subtitles</span>
  1647. <i class="ctx-sub-arrow">›</i>
  1648. <!-- Subtitle submenu — child of parent item for easy relative positioning -->
  1649. <div id="ctx-subtitle-sub">
  1650. <div class="ctx-item ctx-active" id="ctx-sub-disable"><i class="ctx-icon">✓</i>Disable</div>
  1651. <div class="ctx-divider"></div>
  1652. <div class="ctx-item" id="ctx-sub-load"><i class="ctx-icon">+</i>Load SRT file…</div>
  1653. </div>
  1654. </div>
  1655. <div class="ctx-divider"></div>
  1656. <div class="ctx-item" id="ctx-subtitle-settings"><img class="ctx-icon" src="img/icons/settings_white.svg" alt="">Subtitle Settings</div>
  1657. <div class="ctx-item" id="ctx-props">Video Properties</div>
  1658. </div>
  1659. <!-- Playback / subtitle settings modal -->
  1660. <div id="subtitle-settings-modal">
  1661. <h3>Subtitle Settings<button id="sset-close" title="Close"><img src="img/icons/close_white.svg" alt=""></button></h3>
  1662. <div class="sset-row">
  1663. <span class="sset-label">Position</span>
  1664. <div class="sset-seg">
  1665. <button class="sset-seg-btn active" data-val="bottom">Bottom</button>
  1666. <button class="sset-seg-btn" data-val="top">Top</button>
  1667. </div>
  1668. </div>
  1669. <div class="sset-row">
  1670. <span class="sset-label">Size</span>
  1671. <input type="range" id="sset-size" min="14" max="52" step="1" value="22">
  1672. <span id="sset-size-val">22px</span>
  1673. </div>
  1674. <div class="sset-row">
  1675. <span class="sset-label">Font</span>
  1676. <select id="sset-font">
  1677. <option value="system-ui, sans-serif">System Default</option>
  1678. <option value="Arial, sans-serif">Arial</option>
  1679. <option value="'Helvetica Neue', Helvetica, sans-serif">Helvetica</option>
  1680. <option value="Georgia, serif">Georgia</option>
  1681. <option value="'Times New Roman', Times, serif">Times New Roman</option>
  1682. <option value="'Courier New', Courier, monospace">Courier New</option>
  1683. <option value="Verdana, sans-serif">Verdana</option>
  1684. <option value="'Trebuchet MS', sans-serif">Trebuchet MS</option>
  1685. <option value="Impact, fantasy">Impact</option>
  1686. </select>
  1687. </div>
  1688. <div class="sset-row">
  1689. <span class="sset-label">Color</span>
  1690. <div class="sset-colors">
  1691. <button class="sset-color active" data-color="#ffffff" style="background:#ffffff" title="White"></button>
  1692. <button class="sset-color" data-color="#ffff00" style="background:#ffff00" title="Yellow"></button>
  1693. <button class="sset-color" data-color="#00ffff" style="background:#00ffff" title="Cyan"></button>
  1694. <button class="sset-color" data-color="#00ff88" style="background:#00ff88" title="Green"></button>
  1695. <button class="sset-color" data-color="#ff8800" style="background:#ff8800" title="Orange"></button>
  1696. <input type="color" id="sset-color-custom" value="#ffffff" title="Custom color">
  1697. </div>
  1698. </div>
  1699. <div id="sset-preview">Sample subtitle text</div>
  1700. </div>
  1701. <!-- Video info / stats modal -->
  1702. <div id="video-info-modal">
  1703. <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>
  1704. <div id="video-info-tabs">
  1705. <div class="info-tab active" onclick="showInfoTab('props')">Properties</div>
  1706. <div class="info-tab" onclick="showInfoTab('stats')">Stats</div>
  1707. </div>
  1708. <div id="video-info-body"></div>
  1709. </div>
  1710. <!-- Advanced settings modal -->
  1711. <div id="adv-settings-modal">
  1712. <h3><span>Advanced Settings</span><button id="adv-settings-close" title="Close" onclick="closeAdvancedSettings()"><img src="img/icons/close_white.svg" alt=""></button></h3>
  1713. <div id="adv-settings-body">
  1714. <div class="adv-row">
  1715. <div class="adv-row-text">
  1716. <div class="adv-row-label">Disable playlist show when change episode</div>
  1717. <div class="adv-row-desc">
  1718. Keep the playlist hidden when you skip to another episode. When this is
  1719. off, a hidden playlist peeks open for 2 seconds and closes again.
  1720. </div>
  1721. </div>
  1722. <label class="settings-switch" title="Disable playlist show when change episode">
  1723. <input type="checkbox" id="adv-no-playlist-peek">
  1724. <span class="settings-switch-track"></span>
  1725. </label>
  1726. </div>
  1727. </div>
  1728. </div>
  1729. <!-- Playback settings popup -->
  1730. <div id="settings-popup">
  1731. <div class="set-section">
  1732. <div class="set-head"><img src="img/icons/repeat_white.svg" alt="">Repeat</div>
  1733. <div class="set-seg" id="set-repeat-seg">
  1734. <button class="set-seg-btn active" data-repeat="off">Off</button>
  1735. <button class="set-seg-btn" data-repeat="one">Repeat one</button>
  1736. </div>
  1737. </div>
  1738. <div class="set-section">
  1739. <div class="set-head"><img src="img/icons/play_white.svg" alt="">Playback speed</div>
  1740. <div class="speed-grid" id="set-speed-grid">
  1741. <button class="speed-btn" data-speed="0.5">0.5&times;</button>
  1742. <button class="speed-btn active" data-speed="1">1&times;</button>
  1743. <button class="speed-btn" data-speed="1.2">1.2&times;</button>
  1744. <button class="speed-btn" data-speed="1.5">1.5&times;</button>
  1745. <button class="speed-btn" data-speed="2">2&times;</button>
  1746. </div>
  1747. </div>
  1748. <div class="set-section">
  1749. <div class="set-head"><img src="img/icons/volume_white.svg" alt="">Volume bar</div>
  1750. <div class="set-seg" id="set-volbar-seg">
  1751. <button class="set-seg-btn active" data-volbar="auto">Auto</button>
  1752. <button class="set-seg-btn" data-volbar="always">Always show</button>
  1753. </div>
  1754. </div>
  1755. <div class="set-section">
  1756. <div class="set-head"><img src="img/icons/movie_white.svg" alt="">Streaming mode</div>
  1757. <div class="set-seg" id="set-stream-seg">
  1758. <button class="set-seg-btn active" data-stream="auto">Auto</button>
  1759. <button class="set-seg-btn" data-stream="mp4">MP4</button>
  1760. <button class="set-seg-btn" data-stream="hls">HLS</button>
  1761. </div>
  1762. </div>
  1763. <div class="set-section">
  1764. <div class="set-head"><img src="img/icons/quality_white.svg" alt="">Quality<span class="set-head-note" id="set-quality-note"></span></div>
  1765. <div class="quality-grid" id="set-quality-grid">
  1766. <button class="speed-btn" data-quality="auto">Auto</button>
  1767. <button class="speed-btn active" data-quality="original">Original</button>
  1768. <button class="speed-btn" data-quality="1080p">1080p</button>
  1769. <button class="speed-btn" data-quality="720p">720p</button>
  1770. <button class="speed-btn" data-quality="480p">480p</button>
  1771. <button class="speed-btn" data-quality="360p">360p</button>
  1772. </div>
  1773. </div>
  1774. <div class="set-section" style="padding-left:0;padding-right:0;padding-bottom:2px;">
  1775. <div class="set-link" id="set-video-props">
  1776. <img src="img/icons/menu_white.svg" alt="">Video properties
  1777. </div>
  1778. <div class="set-link" id="set-advanced">
  1779. <img src="img/icons/settings_white.svg" alt="">Advanced settings
  1780. </div>
  1781. </div>
  1782. </div>
  1783. <!-- Subtitle popup (dedicated CC button) -->
  1784. <div id="subtitle-popup">
  1785. <div class="ctx-item ctx-active" id="sub-pop-disable"><i class="ctx-icon">✓</i>Disable</div>
  1786. <div class="ctx-divider"></div>
  1787. <div class="ctx-item" id="sub-pop-load"><i class="ctx-icon">+</i>Load SRT file…</div>
  1788. <div class="ctx-divider"></div>
  1789. <div class="set-link" id="sub-pop-settings">
  1790. <img src="img/icons/settings_white.svg" alt="">Subtitle settings
  1791. </div>
  1792. </div>
  1793. <!-- Custom controls -->
  1794. <div id="video-controls">
  1795. <div id="progress-wrap">
  1796. <div id="progress-bar" style="width:0%"></div>
  1797. <div id="progress-thumb" style="left:0%"></div>
  1798. <div id="scrub-preview">
  1799. <div id="scrub-preview-thumb"></div>
  1800. <div id="scrub-preview-time">0:00</div>
  1801. </div>
  1802. </div>
  1803. <div id="controls-row">
  1804. <button class="ctrl-btn" id="ctrl-prev" title="Previous (←)"><img src="img/icons/skip_previous_white.svg" alt=""></button>
  1805. <button class="ctrl-btn" id="ctrl-play" title="Play/Pause (Space)"><img id="play-icon" src="img/icons/play_white.svg" alt=""></button>
  1806. <button class="ctrl-btn" id="ctrl-next" title="Next (→)"><img src="img/icons/skip_next_white.svg" alt=""></button>
  1807. <div id="volume-wrap">
  1808. <button class="ctrl-btn" id="ctrl-mute" title="Mute (M)"><img id="mute-icon" src="img/icons/volume_white.svg" alt=""></button>
  1809. <input id="volume-slider" type="range" min="0" max="1" step="0.05" value="1">
  1810. </div>
  1811. <span id="time-display">0:00 / 0:00</span>
  1812. <span id="now-playing-title"></span>
  1813. <button class="ctrl-btn" id="ctrl-list" title="Episode list (L)"><img src="img/icons/menu_white.svg" alt=""></button>
  1814. <button class="ctrl-btn" id="ctrl-cast" title="Cast to Arozcast" onclick="openCastDialog()"><img src="img/icons/cast_white.svg" alt="" width="18" height="18"></button>
  1815. <button class="ctrl-btn" id="ctrl-subtitle" title="Subtitles"><span class="ctrl-cc-icon">CC</span></button>
  1816. <button class="ctrl-btn" id="ctrl-settings" title="Playback settings (S)"><img src="img/icons/settings_white.svg" alt=""></button>
  1817. <button class="ctrl-btn" id="ctrl-fs" title="Fullscreen (F)"><img src="img/icons/fullscreen_white.svg" alt=""></button>
  1818. </div>
  1819. </div>
  1820. </div>
  1821. <!-- Sidebar playlist -->
  1822. <div id="playlist-sidebar">
  1823. <div id="sidebar-header">
  1824. <span>Playlist</span>
  1825. <label class="autoplay-label" title="Auto-play next episode">
  1826. <input type="checkbox" id="autoplay-check">
  1827. <span class="autoplay-track"></span>
  1828. <span>Auto</span>
  1829. </label>
  1830. <button id="sidebar-close" onclick="toggleSidebar()"><img style="width: 16px;" src="img/icons/close_white.svg" alt=""></button>
  1831. </div>
  1832. <div id="sidebar-list"></div>
  1833. </div>
  1834. </div>
  1835. </div>
  1836. <!-- Toast -->
  1837. <div id="toast"></div>
  1838. <!-- Arozcast cast modal -->
  1839. <div id="cast-modal">
  1840. <div class="cast-dialog">
  1841. <h4>Cast to Arozcast</h4>
  1842. <div id="cast-status-line" class="cast-status-line" style="display:none;"></div>
  1843. <input type="text" id="cast-code-input" maxlength="4" placeholder="1234"
  1844. oninput="this.value=this.value.replace(/\D/g,'')"
  1845. onkeydown="if(event.key==='Enter') connectCast()">
  1846. <div id="cast-err" class="cast-err"></div>
  1847. <div class="cast-actions">
  1848. <button class="btn-cast-cancel" onclick="closeCastDialog()">Cancel</button>
  1849. <button class="btn-cast-disc" id="cast-disc-btn" style="display:none;" onclick="disconnectCast()">Disconnect</button>
  1850. <button class="btn-cast-connect" id="cast-conn-btn" onclick="connectCast()">Connect</button>
  1851. </div>
  1852. </div>
  1853. </div>
  1854. <!-- ═══════════════ JAVASCRIPT ════════════════════════════════════════════════ -->
  1855. <script>
  1856. // ─── All configurable paths come from backend/common.js ──────────────────────
  1857. // (SCRIPT_GET_LIBRARY, SCRIPT_GET_EPISODES, SCRIPT_GET_THUMBNAIL, MEDIA_API)
  1858. // ─── Library cache ────────────────────────────────────────────────────────────
  1859. // Cache is stored server-side (user:/.appdata/Movie/library_cache.json)
  1860. // so it is shared across devices for the same user account.
  1861. var libraryNeedsRedraw = false; // set when bg-refresh finishes outside the library view
  1862. // ─── App state ────────────────────────────────────────────────────────────────
  1863. var library = []; // full album array from server
  1864. var currentAlbum = null; // album object currently shown in detail view
  1865. var currentSeason = null; // season object currently active
  1866. var currentEpisodes = []; // flat episode array for current season/album
  1867. var playingIndex = -1; // index in currentEpisodes being played
  1868. // TV-remote focus management
  1869. var focusMode = false; // set to true when arrow-key pressed
  1870. var focusedEl = null;
  1871. // Controls auto-hide timer
  1872. var controlsTimer = null;
  1873. // Library pagination
  1874. var PAGE_SIZE = 24;
  1875. var moviesData = [];
  1876. var collectionsData = [];
  1877. var showsData = [];
  1878. var shortsData = [];
  1879. var animeData = [];
  1880. var moviesShown = 0;
  1881. var collectionsShown = 0;
  1882. var showsShown = 0;
  1883. var shortsShown = 0;
  1884. var animeShown = 0;
  1885. // Auto-play between episodes
  1886. var autoplayEnabled = localStorage.getItem('movie_autoplay') !== '0'; // on by default
  1887. var countdownTimer = null;
  1888. // Single-repeat
  1889. var repeatSingle = (localStorage.getItem('movie_repeat_one') === '1');
  1890. // Playback speed (persisted, reapplied whenever a new source loads)
  1891. // Snapped to the nearest preset on load: an earlier build let this be dragged
  1892. // to any value, and the popup highlights presets only.
  1893. // The preset rates offered in the settings popup. Declared here rather than
  1894. // beside setPlaybackSpeed because the initialiser below runs on load, and a
  1895. // `var` further down the file would still be undefined at that point.
  1896. var PLAYBACK_SPEEDS = [0.5, 1, 1.2, 1.5, 2];
  1897. var playbackSpeed = nearestPlaybackSpeed(localStorage.getItem('movie_playback_speed') || '1');
  1898. // Force the volume slider visible even on portrait phones (see the media query)
  1899. var alwaysShowVolumeBar = (localStorage.getItem('movie_always_volume_bar') === '1');
  1900. // Indexing (Settings tab). Auto indexing governs the automatic scan on app open;
  1901. // manual scans from the Settings tab always work regardless.
  1902. var autoIndexEnabled = (localStorage.getItem('movie_auto_index') !== '0'); // on by default
  1903. var libraryCacheTs = 0; // timestamp of the index currently in memory
  1904. // Set once the user manually opens/closes the playlist, so orientation changes
  1905. // stop auto-managing it until the next playback starts.
  1906. var playlistUserToggled = false;
  1907. // Skipping between episodes must not reshuffle the layout. A playlist that is
  1908. // already open stays open; a closed one only peeks open for this long before
  1909. // tucking itself away again (unless the user disabled the peek entirely).
  1910. var PLAYLIST_PEEK_MS = 2000;
  1911. var playlistPeekTimer = null;
  1912. var disablePlaylistPeek = (localStorage.getItem('movie_no_playlist_peek') === '1');
  1913. // ─── Arozcast cast state ──────────────────────────────────────────────────────
  1914. var castWs = null;
  1915. var castCode = null;
  1916. var castMode = false;
  1917. var castPingTimer = null;
  1918. var castWatchTimer = null;
  1919. var castLastSeen = 0;
  1920. var castCurrentTime = 0;
  1921. var castDuration = 0;
  1922. var castIsPlaying = false;
  1923. var castReconnectTimer = null; // setTimeout handle for next reconnect attempt
  1924. var castReconnectCount = 0; // number of attempts made so far
  1925. var castPendingCode = null; // room code kept alive during reconnect
  1926. function _castConnected() {
  1927. return castWs !== null && castWs.readyState === WebSocket.OPEN;
  1928. }
  1929. function _castSend(topic, payload) {
  1930. if (!_castConnected()) { return; }
  1931. castWs.send(JSON.stringify({ topic: topic, payload: payload || {} }));
  1932. }
  1933. function openCastDialog() {
  1934. var $inp = $('#cast-code-input');
  1935. var $stat = $('#cast-status-line');
  1936. var $err = $('#cast-err');
  1937. $('#cast-err').text('');
  1938. if (_castConnected()) {
  1939. $inp.hide();
  1940. $stat.show().text('Casting to room ' + castCode);
  1941. $('#cast-conn-btn').hide();
  1942. $('#cast-disc-btn').show();
  1943. } else {
  1944. $inp.show().val('');
  1945. $stat.hide();
  1946. $('#cast-conn-btn').show();
  1947. $('#cast-disc-btn').hide();
  1948. }
  1949. $('#cast-modal').addClass('active');
  1950. if ($inp.is(':visible')) { setTimeout(function(){ $inp.focus(); }, 50); }
  1951. }
  1952. function closeCastDialog() { $('#cast-modal').removeClass('active'); }
  1953. function connectCast() {
  1954. var code = $('#cast-code-input').val().trim();
  1955. if (code.length !== 4) { $('#cast-err').text('Enter a 4-digit room code.'); return; }
  1956. $('#cast-err').text('');
  1957. fetch(ao_root + 'api/arozcast/ping?code=' + code)
  1958. .then(function(r) { return r.json(); })
  1959. .then(function(data) {
  1960. if (!data.exists) { $('#cast-err').text('Room not found. Is Arozcast running?'); return; }
  1961. if (castWs) { castWs.onclose = null; castWs.close(); castWs = null; }
  1962. clearInterval(castPingTimer); clearInterval(castWatchTimer);
  1963. // Cancel any pending auto-reconnect to the old room — user is opening a new session
  1964. clearTimeout(castReconnectTimer); castReconnectTimer = null;
  1965. castReconnectCount = 0; castPendingCode = null;
  1966. // Signal other apps (Musicify, Photo) to yield the cast room
  1967. try { new BroadcastChannel('arozcast').postMessage({ type: 'arozcast.takeover' }); } catch(e) {}
  1968. castCode = code;
  1969. var wsUrl = new URL(ao_root + 'api/arozcast/ws?code=' + code, window.location.href);
  1970. wsUrl.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
  1971. castWs = new WebSocket(wsUrl.toString());
  1972. castWs.onopen = function() {
  1973. castLastSeen = Date.now();
  1974. castMode = true;
  1975. castWs.send(JSON.stringify({ topic: 'peer.hello', payload: {} }));
  1976. var vid = document.getElementById('main-video');
  1977. // Load current episode on Arozcast; stop local playback
  1978. if (playingIndex >= 0 && currentEpisodes[playingIndex]) {
  1979. var ep = currentEpisodes[playingIndex];
  1980. var ext = ep.ext ? ep.ext.toLowerCase().replace(/^\./, '') : '';
  1981. // Always hand the receiver the MP4 stream: it is a separate
  1982. // client whose HLS support we cannot probe from here, and
  1983. // this browser's streaming-mode preference says nothing
  1984. // about it.
  1985. var src = isWebPlayable(ext)
  1986. ? MEDIA_API + '?file=' + encodeURIComponent(ep.filepath)
  1987. : TRANSCODE_API + '?file=' + encodeURIComponent(ep.filepath);
  1988. _castSend('media.load', {
  1989. filepath: ep.filepath, name: ep.name, type: 'video',
  1990. src: src, startTime: (isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime) || 0
  1991. });
  1992. // Volume after load, before play — ensures it overrides any default
  1993. // the Arozcast side might apply during media initialisation.
  1994. _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted });
  1995. _castSend(vid.paused ? 'media.pause' : 'media.play', {});
  1996. // Stop local video to avoid dual transcoding
  1997. vid.pause();
  1998. vid.removeAttribute('src');
  1999. }
  2000. castPingTimer = setInterval(function() { _castSend('peer.heartbeat', {}); }, 5000);
  2001. castWatchTimer = setInterval(function() {
  2002. if (Date.now() - castLastSeen > 12000 && castWs) { castWs.close(); }
  2003. }, 4000);
  2004. $('#ctrl-cast, #ctrl-cast-top').addClass('casting');
  2005. closeCastDialog();
  2006. showToast('Casting to room ' + code);
  2007. };
  2008. castWs.onmessage = function(evt) {
  2009. castLastSeen = Date.now();
  2010. try { _handleCastMessage(JSON.parse(evt.data)); } catch(e) {}
  2011. };
  2012. castWs.onclose = function() {
  2013. clearInterval(castPingTimer); clearInterval(castWatchTimer);
  2014. castPingTimer = castWatchTimer = null;
  2015. var wasActive = castMode;
  2016. var savedCode = castCode;
  2017. castMode = false; castCode = null; castWs = null;
  2018. $('#ctrl-cast, #ctrl-cast-top').removeClass('casting');
  2019. if (wasActive) { _startCastReconnect(savedCode); }
  2020. };
  2021. castWs.onerror = function() {
  2022. $('#cast-err').text('Connection error.');
  2023. openCastDialog();
  2024. };
  2025. })
  2026. .catch(function() { $('#cast-err').text('Network error.'); });
  2027. }
  2028. function disconnectCast() {
  2029. // Cancel any pending auto-reconnect before tearing down
  2030. clearTimeout(castReconnectTimer); castReconnectTimer = null;
  2031. castReconnectCount = 0; castPendingCode = null;
  2032. if (_castConnected()) { _castSend('media.stop', {}); }
  2033. if (castWs) { castWs.onclose = null; castWs.close(); castWs = null; }
  2034. clearInterval(castPingTimer); clearInterval(castWatchTimer);
  2035. castPingTimer = castWatchTimer = null;
  2036. castMode = false; castCode = null;
  2037. $('#ctrl-cast, #ctrl-cast-top').removeClass('casting');
  2038. closeCastDialog();
  2039. _castResumeLocally();
  2040. }
  2041. function _castResumeLocally() {
  2042. if (playingIndex < 0 || !currentEpisodes || !currentEpisodes[playingIndex]) { return; }
  2043. var ep = currentEpisodes[playingIndex];
  2044. var pos = castCurrentTime;
  2045. var vid = document.getElementById('main-video');
  2046. if (isTranscodedVideo && pos > 0) {
  2047. // Restart the transcode at the cast position, on whichever transport
  2048. // this browser is using
  2049. transcodeSeekOffset = pos;
  2050. attachTranscodeStream(vid, transcodeStreamURL(ep.filepath, pos));
  2051. } else {
  2052. var ext = ep.ext ? ep.ext.toLowerCase().replace(/^\./, '') : '';
  2053. if (isWebPlayable(ext)) {
  2054. vid.src = MEDIA_API + '?file=' + encodeURIComponent(ep.filepath);
  2055. } else {
  2056. attachTranscodeStream(vid, transcodeStreamURL(ep.filepath, 0));
  2057. }
  2058. if (pos > 0) {
  2059. $(vid).one('loadedmetadata.castresume', function() { vid.currentTime = pos; });
  2060. }
  2061. }
  2062. vid.load();
  2063. $('#play-icon').attr('src', 'img/icons/play_white.svg');
  2064. showToast('Arozcast disconnected — click play to resume');
  2065. }
  2066. // ── Arozcast auto-reconnect ───────────────────────────────────────────────────
  2067. var _CAST_RECONNECT_DELAYS = [2000, 5000, 12000];
  2068. function _startCastReconnect(code) {
  2069. if (!code || castReconnectCount >= _CAST_RECONNECT_DELAYS.length) {
  2070. if (castReconnectCount > 0) { _castResumeLocally(); }
  2071. castReconnectCount = 0; castPendingCode = null;
  2072. return;
  2073. }
  2074. castPendingCode = code;
  2075. var delay = _CAST_RECONNECT_DELAYS[castReconnectCount++];
  2076. clearTimeout(castReconnectTimer);
  2077. castReconnectTimer = setTimeout(function() {
  2078. castReconnectTimer = null;
  2079. _attemptCastReconnect();
  2080. }, delay);
  2081. showToast('Arozcast disconnected — reconnecting…');
  2082. }
  2083. function _attemptCastReconnect() {
  2084. if (!castPendingCode) return;
  2085. var code = castPendingCode;
  2086. var wsUrl = new URL(ao_root + 'api/arozcast/ws?code=' + code, window.location.href);
  2087. wsUrl.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
  2088. var ws = new WebSocket(wsUrl.toString());
  2089. // If the socket doesn't open within 8 s, count as a failed attempt
  2090. var openTimer = setTimeout(function() {
  2091. ws.onopen = ws.onclose = ws.onerror = null; ws.close();
  2092. _startCastReconnect(code);
  2093. }, 8000);
  2094. ws.onopen = function() { clearTimeout(openTimer); castPendingCode = null; _castDidReconnect(ws, code); };
  2095. ws.onerror = function() {}; // let onclose handle it
  2096. ws.onclose = function() { clearTimeout(openTimer); _startCastReconnect(code); };
  2097. }
  2098. function _castDidReconnect(ws, code) {
  2099. castWs = ws; castCode = code; castMode = true; castLastSeen = Date.now();
  2100. ws.onmessage = function(evt) {
  2101. castLastSeen = Date.now();
  2102. try { _handleCastMessage(JSON.parse(evt.data)); } catch(e) {}
  2103. };
  2104. ws.onclose = function() {
  2105. clearInterval(castPingTimer); clearInterval(castWatchTimer);
  2106. castPingTimer = castWatchTimer = null;
  2107. var wasActive = castMode;
  2108. var savedCode = castCode;
  2109. castMode = false; castCode = null; castWs = null;
  2110. $('#ctrl-cast, #ctrl-cast-top').removeClass('casting');
  2111. if (wasActive) { _startCastReconnect(savedCode); }
  2112. };
  2113. // Re-announce presence and sync volume only — do NOT resend media.load.
  2114. // Arozcast kept playing while the phone was asleep; its next status.update
  2115. // will immediately sync castCurrentTime to the live remote position.
  2116. _castSend('peer.hello', {});
  2117. var vid = document.getElementById('main-video');
  2118. _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted });
  2119. castPingTimer = setInterval(function() { _castSend('peer.heartbeat', {}); }, 5000);
  2120. castWatchTimer = setInterval(function() {
  2121. if (Date.now() - castLastSeen > 12000 && castWs) { castWs.close(); }
  2122. }, 4000);
  2123. $('#ctrl-cast, #ctrl-cast-top').addClass('casting');
  2124. showToast('Arozcast reconnected');
  2125. }
  2126. function _handleCastMessage(msg) {
  2127. if (msg.topic === 'status.update') {
  2128. castReconnectCount = 0; // receiver confirmed alive — reset retry counter
  2129. castCurrentTime = msg.payload.currentTime || 0;
  2130. castDuration = msg.payload.duration || 0;
  2131. castIsPlaying = msg.payload.isPlaying || false;
  2132. if (castDuration > 0) {
  2133. var pct = (castCurrentTime / castDuration) * 100;
  2134. $('#progress-bar').css('width', pct + '%');
  2135. $('#progress-thumb').css('left', 'calc(' + pct + '% - 7px)');
  2136. $('#time-display').text(formatTime(castCurrentTime) + ' / ' + formatTime(castDuration));
  2137. }
  2138. $('#play-icon').attr('src', castIsPlaying
  2139. ? 'img/icons/pause_white.svg' : 'img/icons/play_white.svg');
  2140. } else if (msg.topic === 'media.ended') {
  2141. cancelCountdown();
  2142. if (repeatSingle) {
  2143. _castSend('media.seek', { time: 0 });
  2144. _castSend('media.play', {});
  2145. } else if (playingIndex < currentEpisodes.length - 1 && autoplayEnabled) {
  2146. startNextCountdown();
  2147. } else {
  2148. castIsPlaying = false;
  2149. $('#play-icon').attr('src', 'img/icons/play_white.svg');
  2150. }
  2151. }
  2152. }
  2153. // Movie info panel
  2154. var currentMovieAlbum = null;
  2155. var movieInfoEpisodes = [];
  2156. var currentMovieImdbTitle = null; // IMDB title once fetched; null until then
  2157. // Player return-destination and watch-position tracking
  2158. var playerReturnView = 'library';
  2159. var pendingResumePos = 0;
  2160. var watchSaveInterval = null;
  2161. // Transcode seek state (seek-by-reload for non-web-playable formats)
  2162. var transcodeSeekOffset = 0; // seconds already consumed before current chunk start
  2163. var isTranscodedVideo = false; // true when current video plays via transcode endpoint
  2164. var transcodeDuration = 0; // duration pre-fetched via /media/duration/ (seconds)
  2165. // Folder browse state
  2166. var folderViewPath = '/';
  2167. var folderViewVideos = [];
  2168. // ─── Movie info panel ─────────────────────────────────────────────────────────
  2169. function openMovieInfo(album) {
  2170. currentMovieAlbum = album;
  2171. currentAlbum = album;
  2172. movieInfoEpisodes = [];
  2173. currentMovieImdbTitle = null;
  2174. // Seed with local data immediately
  2175. $('#movie-info-title').text(album.name);
  2176. $('#movie-info-filename').hide().text('');
  2177. $('#movie-info-year').text('');
  2178. $('#movie-info-cast').text('');
  2179. $('#movie-info-imdb-btn').hide();
  2180. $('#movie-info-wrong-wrap').hide();
  2181. $('#movie-info-files').hide();
  2182. $('#movie-info-loading').addClass('active');
  2183. var localThumb = album.thumbnail
  2184. ? 'data:image/jpeg;base64,' + album.thumbnail
  2185. : 'img/thumbnail.png';
  2186. $('#movie-info-poster-img').attr('src', localThumb);
  2187. $('#movie-info-backdrop').css('background-image', 'url(' + localThumb + ')');
  2188. // Bind Play button
  2189. $('#movie-info-play-btn').off('click').on('click', function () {
  2190. if (movieInfoEpisodes.length > 0) {
  2191. currentAlbum = album; currentSeason = null;
  2192. currentEpisodes = movieInfoEpisodes;
  2193. startPlayback(0);
  2194. }
  2195. });
  2196. // Bind Open in Files — opens file manager at the movie's location
  2197. $('#movie-info-fm-btn').off('click').on('click', function () {
  2198. if (!currentMovieAlbum) { return; }
  2199. if (currentMovieAlbum._singleFile) {
  2200. var fp = currentMovieAlbum._singleFile;
  2201. var dir = fp.substring(0, fp.lastIndexOf('/'));
  2202. var fname = fp.split('/').pop();
  2203. ao_module_openPath(dir, fname);
  2204. } else {
  2205. ao_module_openPath(currentMovieAlbum.folderpath);
  2206. }
  2207. });
  2208. // Bind YouTube search — uses IMDB title once available, raw name otherwise
  2209. $('#movie-info-yt-btn').off('click').on('click', function () {
  2210. var term = currentMovieImdbTitle || (currentMovieAlbum ? currentMovieAlbum.name : '');
  2211. window.open('https://www.youtube.com/results?search_query=' + encodeURIComponent(term + ' trailer'), '_blank');
  2212. });
  2213. showView('movie-info');
  2214. // Fetch IMDB metadata
  2215. ao_module_agirun(SCRIPT_GET_MOVIE_INFO, { movie: album.name }, function (data) {
  2216. $('#movie-info-loading').removeClass('active');
  2217. if (data && !data.error) { applyMovieInfo(data); }
  2218. }, function () {
  2219. $('#movie-info-loading').removeClass('active');
  2220. });
  2221. // Build file list
  2222. if (album._singleFile) {
  2223. var ext = '.' + album._singleFile.split('.').pop().toLowerCase();
  2224. movieInfoEpisodes = [{ name: album.name, filepath: album._singleFile, ext: ext, index: 0 }];
  2225. // Single file — file list not needed (Play button is enough)
  2226. } else {
  2227. ao_module_agirun(SCRIPT_GET_EPISODES, { folder: album.folderpath }, function (data) {
  2228. if (data && !data.error && data.length > 0) {
  2229. movieInfoEpisodes = data;
  2230. if (data.length > 1) { renderMovieFileList(data); }
  2231. }
  2232. });
  2233. }
  2234. }
  2235. function applyMovieInfo(info) {
  2236. var imdbTitle = info['#TITLE'] || '';
  2237. var year = info['#YEAR'] ? String(info['#YEAR']) : '';
  2238. var actors = info['#ACTORS'] || '';
  2239. var imdbUrl = info['#IMDB_URL'] || '';
  2240. var poster = info['#IMG_POSTER'] || '';
  2241. // Replace the displayed title with the canonical IMDB title and show the
  2242. // original filename as a small italic subtitle underneath.
  2243. if (imdbTitle) {
  2244. currentMovieImdbTitle = imdbTitle;
  2245. $('#movie-info-title').text(imdbTitle);
  2246. if (currentMovieAlbum && currentMovieAlbum.name !== imdbTitle) {
  2247. $('#movie-info-filename').text(currentMovieAlbum.name).show();
  2248. }
  2249. }
  2250. if (year) { $('#movie-info-year').text(year); }
  2251. if (actors) {
  2252. $('#movie-info-cast').html(
  2253. '<span style="color:var(--text-sub);font-weight:600">Cast</span> ' + escapeHtml(actors)
  2254. );
  2255. }
  2256. if (poster) {
  2257. var img = document.getElementById('movie-info-poster-img');
  2258. img.onerror = function () {
  2259. img.src = (currentMovieAlbum && currentMovieAlbum.thumbnail)
  2260. ? 'data:image/jpeg;base64,' + currentMovieAlbum.thumbnail
  2261. : 'img/thumbnail.png';
  2262. img.onerror = null;
  2263. };
  2264. img.onload = function () {
  2265. $('#movie-info-backdrop').css('background-image', 'url(' + poster + ')');
  2266. img.onload = null;
  2267. };
  2268. img.src = poster;
  2269. }
  2270. if (imdbUrl) {
  2271. $('#movie-info-imdb-btn').show().off('click').on('click', function () {
  2272. window.open(imdbUrl, '_blank');
  2273. });
  2274. }
  2275. // Show the "wrong movie" reset button now that IMDB data is displayed
  2276. $('#movie-info-wrong-wrap').show();
  2277. $('#movie-info-reset-btn').off('click').on('click', function () {
  2278. if (!currentMovieAlbum) { return; }
  2279. ao_module_agirun(SCRIPT_DISABLE_MOVIE_INFO, { movie: currentMovieAlbum.name },
  2280. function () { resetMovieInfo(); },
  2281. function () { resetMovieInfo(); } // reset UI even if backend call fails
  2282. );
  2283. });
  2284. }
  2285. // Reset the movie info panel to local-only state (used after disabling IMDB info)
  2286. function resetMovieInfo() {
  2287. if (!currentMovieAlbum) { return; }
  2288. currentMovieImdbTitle = null;
  2289. var album = currentMovieAlbum;
  2290. $('#movie-info-title').text(album.name);
  2291. $('#movie-info-filename').hide().text('');
  2292. $('#movie-info-year').text('');
  2293. $('#movie-info-cast').text('');
  2294. $('#movie-info-imdb-btn').hide();
  2295. $('#movie-info-wrong-wrap').hide();
  2296. // Restore local thumbnail as poster and backdrop
  2297. var localThumb = album.thumbnail
  2298. ? 'data:image/jpeg;base64,' + album.thumbnail
  2299. : 'img/thumbnail.png';
  2300. document.getElementById('movie-info-poster-img').src = localThumb;
  2301. $('#movie-info-backdrop').css('background-image', 'url(' + localThumb + ')');
  2302. }
  2303. function renderMovieFileList(episodes) {
  2304. var $list = $('#movie-info-episode-list').empty();
  2305. episodes.forEach(function (ep, i) {
  2306. var row = $('<div class="episode-item" tabindex="0" role="button">'
  2307. + '<div class="ep-thumb"><div class="ep-thumb-placeholder"><img src="img/icons/play_white.svg" alt=""></div></div>'
  2308. + '<div class="ep-info">'
  2309. + '<div class="ep-name">' + escapeHtml(ep.name) + '</div>'
  2310. + '<div class="ep-path">' + escapeHtml((ep.ext || '').replace('.', '').toUpperCase()) + '</div>'
  2311. + '</div>'
  2312. + '<div class="ep-play-icon"><img src="img/icons/play_white.svg" alt=""></div>'
  2313. + '</div>');
  2314. row.data('idx', i);
  2315. row.on('click', function () {
  2316. currentAlbum = currentMovieAlbum; currentSeason = null;
  2317. currentEpisodes = movieInfoEpisodes;
  2318. startPlayback($(this).data('idx'));
  2319. });
  2320. row.on('keydown', function (e) {
  2321. if (e.key === 'Enter' || e.key === ' ') {
  2322. e.preventDefault();
  2323. currentAlbum = currentMovieAlbum; currentSeason = null;
  2324. currentEpisodes = movieInfoEpisodes;
  2325. startPlayback($(this).data('idx'));
  2326. }
  2327. });
  2328. $list.append(row);
  2329. // Lazy thumbnail
  2330. (function (epObj, rowEl) {
  2331. ao_module_agirun(SCRIPT_GET_THUMBNAIL, { file: epObj.filepath }, function (data) {
  2332. if (data && !data.error && data.length > 20) {
  2333. rowEl.find('.ep-thumb-placeholder')
  2334. .replaceWith('<img src="data:image/jpeg;base64,' + data + '" alt="">');
  2335. }
  2336. });
  2337. })(ep, row);
  2338. });
  2339. $('#movie-info-files').show();
  2340. }
  2341. function closeMovieInfo() {
  2342. currentMovieAlbum = null;
  2343. movieInfoEpisodes = [];
  2344. showView('library');
  2345. }
  2346. // ─── Scrub-bar hover preview (storyboard) ─────────────────────────────────────
  2347. // The server renders one sprite sheet per file holding a downscaled frame every
  2348. // few seconds; we fetch it once and keep it in memory, so hovering the timeline
  2349. // costs nothing. Asking ffmpeg for a frame per hover would be hopeless on a
  2350. // software-decoded H.265 source, which is exactly where previews matter most.
  2351. var storyboard = null; // layout from the server + the loaded sheet URL
  2352. var storyboardToken = 0; // invalidates in-flight loads when the file changes
  2353. var storyboardTimer = null;
  2354. function resetStoryboard() {
  2355. storyboardToken++;
  2356. storyboard = null;
  2357. clearTimeout(storyboardTimer);
  2358. storyboardTimer = null;
  2359. $('#scrub-preview-thumb').removeClass('ready');
  2360. hideScrubPreview();
  2361. }
  2362. // Building the sheet runs ffmpeg, so hold off briefly and let playback (and any
  2363. // transcode) get established before adding more load.
  2364. function scheduleStoryboardLoad(filepath) {
  2365. resetStoryboard();
  2366. if (!filepath) { return; }
  2367. var token = storyboardToken;
  2368. storyboardTimer = setTimeout(function () { loadStoryboard(filepath, token); }, 3000);
  2369. }
  2370. function loadStoryboard(filepath, token) {
  2371. var base = STORYBOARD_API + '?file=' + encodeURIComponent(filepath);
  2372. fetch(base)
  2373. .then(function (r) { return r.json(); })
  2374. .then(function (meta) {
  2375. if (token !== storyboardToken) { return; } // switched file while loading
  2376. if (!meta || meta.error || !meta.interval || !meta.tileWidth) { return; }
  2377. var img = new Image();
  2378. img.onload = function () {
  2379. if (token !== storyboardToken) { return; }
  2380. meta.url = img.src;
  2381. storyboard = meta;
  2382. };
  2383. img.src = base + '&image=1';
  2384. })
  2385. .catch(function () {}); // previews are optional — stay silent on failure
  2386. }
  2387. // Whole-file duration, whichever playback mode is active
  2388. function scrubTotalDuration() {
  2389. if (castMode && castDuration > 0) { return castDuration; }
  2390. if (isTranscodedVideo) { return transcodeDuration; }
  2391. return document.getElementById('main-video').duration || 0;
  2392. }
  2393. function initScrubPreview() {
  2394. var $wrap = $('#progress-wrap');
  2395. $wrap.on('mousemove', function (e) {
  2396. var total = scrubTotalDuration();
  2397. var rect = this.getBoundingClientRect();
  2398. if (!total || !isFinite(total) || rect.width <= 0) { hideScrubPreview(); return; }
  2399. var ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
  2400. showScrubPreview(ratio * total, ratio, rect.width);
  2401. });
  2402. $wrap.on('mouseleave', hideScrubPreview);
  2403. }
  2404. function showScrubPreview(time, ratio, barWidth) {
  2405. $('#scrub-preview-time').text(formatTime(time));
  2406. var $thumb = $('#scrub-preview-thumb');
  2407. var halfWidth;
  2408. if (storyboard && storyboard.url) {
  2409. var idx = Math.max(0, Math.min(storyboard.count - 1,
  2410. Math.floor(time / storyboard.interval)));
  2411. var col = idx % storyboard.cols;
  2412. var row = Math.floor(idx / storyboard.cols);
  2413. $thumb.addClass('ready').css({
  2414. 'width': storyboard.tileWidth + 'px',
  2415. 'height': storyboard.tileHeight + 'px',
  2416. 'background-image': 'url("' + storyboard.url + '")',
  2417. 'background-position': (-col * storyboard.tileWidth) + 'px '
  2418. + (-row * storyboard.tileHeight) + 'px'
  2419. });
  2420. halfWidth = storyboard.tileWidth / 2;
  2421. } else {
  2422. // Sheet not ready (or unavailable) — the timestamp alone is still useful
  2423. $thumb.removeClass('ready');
  2424. halfWidth = 28;
  2425. }
  2426. // Keep the popup within the bar rather than letting it hang off an edge
  2427. var x = Math.max(halfWidth, Math.min(barWidth - halfWidth, ratio * barWidth));
  2428. $('#scrub-preview').css('left', x + 'px').addClass('active');
  2429. }
  2430. function hideScrubPreview() { $('#scrub-preview').removeClass('active'); }
  2431. // ─── Transcode seek (seek-by-reload) ──────────────────────────────────────────
  2432. // Formats the browser can't decode are streamed through ffmpeg, so "seeking"
  2433. // means restarting the transcode at a new offset. Replacing .src blanks the
  2434. // <video> to black until the first frame of the new segment arrives, which can
  2435. // take seconds. Freeze the last painted frame under a spinner instead, and only
  2436. // reveal the live element once it is genuinely playing again.
  2437. var seekFreezeTimer = null;
  2438. function showSeekFreeze() {
  2439. var vid = document.getElementById('main-video');
  2440. var canvas = document.getElementById('seek-freeze');
  2441. if (canvas && vid.videoWidth > 0 && vid.videoHeight > 0) {
  2442. canvas.width = vid.videoWidth;
  2443. canvas.height = vid.videoHeight;
  2444. try {
  2445. canvas.getContext('2d').drawImage(vid, 0, 0, canvas.width, canvas.height);
  2446. $(canvas).show();
  2447. } catch (e) {
  2448. // No decodable frame right now (e.g. seeking again mid-buffer) —
  2449. // leave whatever is already frozen on screen rather than flashing black.
  2450. }
  2451. }
  2452. $('#seek-spinner').addClass('active');
  2453. clearTimeout(seekFreezeTimer);
  2454. // Safety net: a stalled transcode must never leave the overlay stuck on
  2455. seekFreezeTimer = setTimeout(hideSeekFreeze, 30000);
  2456. }
  2457. function hideSeekFreeze() {
  2458. clearTimeout(seekFreezeTimer);
  2459. seekFreezeTimer = null;
  2460. $('#seek-freeze').hide();
  2461. $('#seek-spinner').removeClass('active');
  2462. }
  2463. // Seek to `seconds` (absolute, whole-file time), clamped to the known duration.
  2464. //
  2465. // An HLS stream keeps every segment produced so far in its playlist, so a seek
  2466. // landing inside the transcoded window is an ordinary <video> seek — no reload,
  2467. // no re-transcode, no black frame. Only a seek past that window (or an MP4
  2468. // stream, which has no seekable history at all) has to restart the transcode at
  2469. // the new offset.
  2470. // Restarting the transcode this close to the end of the file would leave ffmpeg
  2471. // with nothing to encode, and the request comes back with no playable stream at
  2472. // all — so a scrub to the very end lands just short of it instead.
  2473. var TRANSCODE_SEEK_TAIL = 5;
  2474. function transcodeSeekTo(seconds) {
  2475. if (playingIndex < 0 || !currentEpisodes[playingIndex]) { return; }
  2476. var vid = document.getElementById('main-video');
  2477. var pos = Math.max(0, seconds);
  2478. if (transcodeDuration > 0) {
  2479. pos = Math.min(Math.max(0, transcodeDuration - TRANSCODE_SEEK_TAIL), pos);
  2480. }
  2481. if (usingHLS() && seekWithinTranscodedWindow(vid, pos)) {
  2482. setSubtitleSeekFloor(pos);
  2483. vid.currentTime = pos - transcodeSeekOffset;
  2484. playVideo(vid);
  2485. return;
  2486. }
  2487. showSeekFreeze();
  2488. setSubtitleSeekFloor(pos);
  2489. transcodeSeekOffset = pos;
  2490. // The freeze frame stays up until the new stream is bound: attaching a
  2491. // playlist waits on the server to start the transcode, so playback resumes
  2492. // from the onReady callback rather than immediately.
  2493. if (!attachTranscodeStream(vid, transcodeStreamURL(currentEpisodes[playingIndex].filepath, pos),
  2494. function (reason) { hideSeekFreeze(); showToast(reason); },
  2495. function () { playVideo(vid); })) {
  2496. hideSeekFreeze();
  2497. showToast('This browser cannot play the HLS stream. Switch streaming mode to MP4 in settings.');
  2498. }
  2499. }
  2500. // Whether `pos` (absolute time) falls inside what the current stream has
  2501. // already produced and can therefore be reached without reloading. seekable
  2502. // spans every segment the playlist lists, for native HLS and for the Media
  2503. // Source player alike (it publishes the playlist's length as the duration).
  2504. function seekWithinTranscodedWindow(vid, pos) {
  2505. var relative = pos - transcodeSeekOffset;
  2506. if (relative < 0) { return false; }
  2507. if (!vid.seekable || vid.seekable.length === 0) { return false; }
  2508. var available = vid.seekable.end(vid.seekable.length - 1);
  2509. // Stay a segment clear of the live edge; seeking right onto it stalls until
  2510. // the next segment lands.
  2511. return relative <= available - 4;
  2512. }
  2513. // ─── HLS stream recovery ──────────────────────────────────────────────────────
  2514. // An HLS transcode lives on the server, and it can disappear from under the
  2515. // player: reaped after a long pause, retired when the same player asked for a
  2516. // different offset, or lost with a restart. The next segment then 404s and the
  2517. // element reports a decode error, which leaves a black frame and no way back.
  2518. // Re-open the stream where it stopped instead. The Media Source player reports
  2519. // the same failures as STREAM_LOST_EVENT rather than an element error.
  2520. //
  2521. // Returns whether a recovery was started, so a caller holding a reason for the
  2522. // failure can show it once recovery has given up.
  2523. var streamRecoveryAttempts = 0;
  2524. var STREAM_RECOVERY_LIMIT = 3; // consecutive tries before giving up
  2525. function recoverTranscodeStream() {
  2526. if (!isTranscodedVideo || !usingHLS()) { return false; }
  2527. if (playingIndex < 0 || !currentEpisodes[playingIndex]) { return false; }
  2528. // A file that genuinely cannot be transcoded fails every time; retrying it
  2529. // forever would replace one dead player with a flickering one.
  2530. if (streamRecoveryAttempts >= STREAM_RECOVERY_LIMIT) { return false; }
  2531. streamRecoveryAttempts++;
  2532. var vid = document.getElementById('main-video');
  2533. var resumeAt = effectivePlaybackTime();
  2534. showSeekFreeze();
  2535. transcodeSeekOffset = resumeAt;
  2536. attachTranscodeStream(vid, transcodeStreamURL(currentEpisodes[playingIndex].filepath, resumeAt),
  2537. function (reason) { hideSeekFreeze(); showToast(reason); },
  2538. function () { playVideo(vid); });
  2539. return true;
  2540. }
  2541. // Current playback position in whole-file terms (transcode streams restart at 0)
  2542. function effectivePlaybackTime() {
  2543. var vid = document.getElementById('main-video');
  2544. return isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
  2545. }
  2546. // ─── Watch position (resume) ──────────────────────────────────────────────────
  2547. function saveWatchPosition() {
  2548. var vid = document.getElementById('main-video');
  2549. var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
  2550. if (playingIndex < 0 || !currentEpisodes || !effectiveDuration || effectiveDuration < 3600) { return; }
  2551. var ep = currentEpisodes[playingIndex];
  2552. var effectiveTime = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
  2553. if (!ep || effectiveTime < 10) { return; }
  2554. ao_module_agirun(SCRIPT_SET_WATCHTIME, {
  2555. filepath: ep.filepath,
  2556. position: Math.floor(effectiveTime),
  2557. duration: Math.floor(effectiveDuration)
  2558. }, function () {}, function () {});
  2559. }
  2560. function clearWatchPosition() {
  2561. if (playingIndex < 0 || !currentEpisodes) { return; }
  2562. var ep = currentEpisodes[playingIndex];
  2563. if (!ep) { return; }
  2564. ao_module_agirun(SCRIPT_SET_WATCHTIME, { filepath: ep.filepath, position: 0, duration: 0 },
  2565. function () {}, function () {});
  2566. }
  2567. function showResumePopup(savedPos, duration) {
  2568. var vid = document.getElementById('main-video');
  2569. vid.pause();
  2570. pendingResumePos = savedPos;
  2571. $('#resume-popup-sub').text(
  2572. 'Last position: ' + formatTime(savedPos) + ' of ' + formatTime(duration)
  2573. );
  2574. $('#resume-popup').addClass('active');
  2575. showControls();
  2576. $('#resume-btn-continue').off('click').on('click', function () {
  2577. if (isTranscodedVideo && playingIndex >= 0 && currentEpisodes[playingIndex]) {
  2578. transcodeSeekTo(pendingResumePos);
  2579. } else {
  2580. vid.currentTime = pendingResumePos;
  2581. playVideo(vid);
  2582. }
  2583. $('#resume-popup').removeClass('active');
  2584. });
  2585. $('#resume-btn-restart').off('click').on('click', function () {
  2586. playVideo(vid);
  2587. $('#resume-popup').removeClass('active');
  2588. });
  2589. }
  2590. // ─── Tab switching ────────────────────────────────────────────────────────────
  2591. function switchTab(tab) {
  2592. if (tab === 'folder') {
  2593. var wasAlreadyFolder = $('#view-folder').hasClass('active');
  2594. showView('folder');
  2595. if (!wasAlreadyFolder) { navigateFolder(folderViewPath); }
  2596. } else if (tab === 'settings') {
  2597. showView('settings');
  2598. refreshIndexStats();
  2599. } else {
  2600. showView('library');
  2601. }
  2602. }
  2603. // ─── Folder navigation ────────────────────────────────────────────────────────
  2604. function buildBreadcrumbs(path) {
  2605. var crumbs = [{ name: 'Home', path: '/' }];
  2606. if (!path || path === '/') { return crumbs; }
  2607. var colonIdx = path.indexOf(':/');
  2608. if (colonIdx < 0) { return crumbs; }
  2609. var root = path.substring(0, colonIdx + 2);
  2610. crumbs.push({ name: root, path: root });
  2611. var rest = path.substring(colonIdx + 2);
  2612. if (!rest) { return crumbs; }
  2613. var parts = rest.split('/').filter(function (s) { return s.length > 0; });
  2614. var cumPath = root;
  2615. for (var i = 0; i < parts.length; i++) {
  2616. cumPath += parts[i] + '/';
  2617. crumbs.push({ name: parts[i], path: cumPath });
  2618. }
  2619. return crumbs;
  2620. }
  2621. function renderBreadcrumb(path) {
  2622. var crumbs = buildBreadcrumbs(path);
  2623. var $bc = $('#folder-breadcrumb').empty();
  2624. for (var i = 0; i < crumbs.length; i++) {
  2625. var crumb = crumbs[i];
  2626. var isLast = (i === crumbs.length - 1);
  2627. if (i > 0) { $bc.append('<span class="crumb-sep">›</span>'); }
  2628. var btn = $('<button class="crumb-btn' + (isLast ? ' crumb-current' : '') + '">'
  2629. + escapeHtml(crumb.name) + '</button>');
  2630. if (!isLast) {
  2631. (function (p) { btn.on('click', function () { navigateFolder(p); }); })(crumb.path);
  2632. }
  2633. $bc.append(btn);
  2634. }
  2635. }
  2636. function navigateFolder(path) {
  2637. folderViewPath = path || '/';
  2638. renderBreadcrumb(folderViewPath);
  2639. loadFolderContents(folderViewPath);
  2640. }
  2641. function loadFolderContents(path) {
  2642. $('#folder-loading').addClass('active');
  2643. $('#folder-empty').hide();
  2644. $('#folder-section-dirs').hide();
  2645. $('#folder-section-vids').hide();
  2646. var params = (path && path !== '/') ? { folder: path } : { folder: '' };
  2647. ao_module_agirun(SCRIPT_LIST_FOLDER, params, function (data) {
  2648. $('#folder-loading').removeClass('active');
  2649. if (!data || data.error) {
  2650. $('#folder-empty').text(data && data.error ? data.error : 'Failed to load folder.').show();
  2651. return;
  2652. }
  2653. renderFolderContents(data);
  2654. }, function () {
  2655. $('#folder-loading').removeClass('active');
  2656. $('#folder-empty').text('Error loading folder.').show();
  2657. });
  2658. }
  2659. function renderFolderContents(data) {
  2660. folderViewVideos = data.videos || [];
  2661. var hasDirs = data.folders && data.folders.length > 0;
  2662. var hasVids = data.videos && data.videos.length > 0;
  2663. if (!hasDirs && !hasVids) {
  2664. $('#folder-empty').text('This folder is empty.').show();
  2665. return;
  2666. }
  2667. if (hasDirs) {
  2668. var $dirs = $('#folder-dirs-grid').empty();
  2669. $('#folder-section-dirs').show();
  2670. data.folders.forEach(function (f) {
  2671. var thumbHtml;
  2672. if (f.isRoot) {
  2673. thumbHtml = '<div class="poster-placeholder"><img src="img/root_placeholder.png" alt=""></div>';
  2674. } else if (f.hasVideos && f.thumbnail && f.thumbnail.length > 20) {
  2675. thumbHtml = '<img class="poster" src="data:image/jpeg;base64,' + f.thumbnail + '" alt="">';
  2676. } else if (f.hasVideos) {
  2677. thumbHtml = '<div class="poster-placeholder"><img src="img/playlist_placeholder.png" alt=""></div>';
  2678. } else {
  2679. thumbHtml = '<div class="poster-placeholder"><img src="img/folder_placeholder.png" alt=""></div>';
  2680. }
  2681. var meta = f.isRoot ? 'Storage root' : (f.hasVideos ? 'Playlist' : 'Folder');
  2682. var card = $('<div class="album-card" tabindex="0" role="button" aria-label="' + escapeAttr(f.name) + '">'
  2683. + thumbHtml
  2684. + '<div class="card-info">'
  2685. + '<div class="card-title">' + escapeHtml(f.name) + '</div>'
  2686. + '<div class="card-meta">' + escapeHtml(meta) + '</div>'
  2687. + '</div>'
  2688. + '</div>');
  2689. card.on('click', function () { navigateFolder(f.path); });
  2690. card.on('keydown', function (e) {
  2691. if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); navigateFolder(f.path); }
  2692. });
  2693. $dirs.append(card);
  2694. });
  2695. }
  2696. if (hasVids) {
  2697. var $vids = $('#folder-vids-grid').empty();
  2698. $('#folder-section-vids').show();
  2699. data.videos.forEach(function (v, i) {
  2700. var card = $('<div class="album-card" tabindex="0" role="button" aria-label="' + escapeAttr(v.name) + '">'
  2701. + '<div class="poster-placeholder"><img src="img/thumbnail.png" alt=""></div>'
  2702. + '<div class="card-info">'
  2703. + '<div class="card-title">' + escapeHtml(v.name) + '</div>'
  2704. + '<div class="card-meta">' + escapeHtml((v.ext || '').replace('.', '').toUpperCase()) + '</div>'
  2705. + '</div>'
  2706. + '</div>');
  2707. card.data('vidIdx', i);
  2708. card.data('vidInfo', v);
  2709. card.on('click', function () { playFolderVideos(folderViewVideos, $(this).data('vidIdx')); });
  2710. card.on('keydown', function (e) {
  2711. if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); playFolderVideos(folderViewVideos, $(this).data('vidIdx')); }
  2712. });
  2713. $vids.append(card);
  2714. });
  2715. // Lazy-load video thumbnails
  2716. $('#folder-vids-grid .album-card').each(function () {
  2717. var $card = $(this);
  2718. var v = $card.data('vidInfo');
  2719. if (!v) { return; }
  2720. ao_module_agirun(SCRIPT_GET_THUMBNAIL, { file: v.filepath }, function (data) {
  2721. if (data && !data.error && data.length > 20) {
  2722. $card.find('.poster-placeholder')
  2723. .replaceWith('<img class="poster" src="data:image/jpeg;base64,' + data + '" alt="">');
  2724. }
  2725. });
  2726. });
  2727. }
  2728. }
  2729. function playFolderVideos(videos, startIndex) {
  2730. if (!videos || videos.length === 0) { return; }
  2731. var segments = folderViewPath.split('/').filter(function (s) { return s.length > 0; });
  2732. var folderName = segments.length > 0 ? segments[segments.length - 1] : 'Videos';
  2733. currentAlbum = { name: folderName, type: 'folder', folderpath: folderViewPath };
  2734. currentSeason = null;
  2735. currentEpisodes = videos.map(function (v, i) {
  2736. return { name: v.name, filepath: v.filepath, ext: v.ext, index: i };
  2737. });
  2738. startPlayback(startIndex);
  2739. }
  2740. // ─── Init ─────────────────────────────────────────────────────────────────────
  2741. $(document).ready(function () {
  2742. initSettings(); // must run before loadLibrary — it reads autoIndexEnabled
  2743. loadLibrary();
  2744. initVideoControls();
  2745. initKeyboard();
  2746. initSearch();
  2747. initContextMenu();
  2748. initSettingsPopup();
  2749. initSubtitlePopup();
  2750. initScrubPreview();
  2751. initAssRenderer();
  2752. initSubtitleMenu();
  2753. initSubtitleSettings();
  2754. // Rotating a phone/tablet into landscape should reveal the playlist again
  2755. // (and back into portrait should tuck it away) — unless the user has taken
  2756. // manual control of it for this playback.
  2757. $(window).on('resize orientationchange', function () {
  2758. if (!playlistUserToggled && $('#view-player').hasClass('active')) {
  2759. applyPlaylistVisibility();
  2760. }
  2761. });
  2762. // Autoplay toggle
  2763. $('#autoplay-check').prop('checked', autoplayEnabled);
  2764. $('#autoplay-check').on('change', function () {
  2765. autoplayEnabled = $(this).is(':checked');
  2766. localStorage.setItem('movie_autoplay', autoplayEnabled ? '1' : '0');
  2767. });
  2768. // Yield cast session to other apps (Photo, Musicify) if they take over
  2769. try {
  2770. var _acCh = new BroadcastChannel('arozcast');
  2771. _acCh.onmessage = function(evt) {
  2772. if (evt.data && evt.data.type === 'arozcast.takeover' && castMode) {
  2773. disconnectCast();
  2774. }
  2775. };
  2776. } catch(e) {}
  2777. // When the user returns to this tab after the phone was asleep, reconnect immediately
  2778. document.addEventListener('visibilitychange', function() {
  2779. if (document.visibilityState === 'visible' && castPendingCode) {
  2780. clearTimeout(castReconnectTimer);
  2781. castReconnectTimer = null;
  2782. _attemptCastReconnect();
  2783. }
  2784. });
  2785. // Close WS cleanly on page unload — do NOT send media.stop so Arozcast keeps playing.
  2786. // Only an explicit disconnectCast() call should stop remote playback.
  2787. window.addEventListener('beforeunload', function() {
  2788. if (castWs) { castWs.onclose = null; castWs.close(); }
  2789. });
  2790. });
  2791. // ─── Library status bar helpers ────────────────────────────────────────────────
  2792. // spinning=true shows the spinner and hides the Refresh button, and vice-versa.
  2793. function setLibraryStatus(text, spinning) {
  2794. $('#library-status-text').text(text);
  2795. $('#library-spinner').toggle(spinning);
  2796. $('#library-refresh-btn').toggle(!spinning);
  2797. }
  2798. function timeAgo(ts) {
  2799. var d = Math.floor((Date.now() - ts) / 1000);
  2800. if (d < 60) { return 'just now'; }
  2801. if (d < 3600) { return Math.floor(d / 60) + 'm ago'; }
  2802. if (d < 86400) { return Math.floor(d / 3600) + 'h ago'; }
  2803. return Math.floor(d / 86400) + 'd ago';
  2804. }
  2805. // Re-render the library grid, preserving an active search filter if present.
  2806. function renderCurrentLibrary() {
  2807. var q = $('#search-input').val().trim().toLowerCase();
  2808. renderLibrary(q ? library.filter(function (a) { return a.name.toLowerCase().indexOf(q) > -1; }) : library);
  2809. }
  2810. // Run a background full scan. getLibrary.js writes the cache file server-side
  2811. // before it sends its response, so the cache is updated even if the tab closes
  2812. // partway through — the browser just won't receive the response in that case.
  2813. function backgroundScanLibrary() {
  2814. ao_module_agirun(SCRIPT_GET_LIBRARY, {}, function (data) {
  2815. if (!data || data.error) {
  2816. setLibraryStatus('Refresh failed · showing cached data', false);
  2817. return;
  2818. }
  2819. library = data;
  2820. libraryCacheTs = Date.now();
  2821. if ($('#view-library').hasClass('active')) {
  2822. renderCurrentLibrary();
  2823. libraryNeedsRedraw = false;
  2824. } else {
  2825. libraryNeedsRedraw = true;
  2826. }
  2827. var n = library.length;
  2828. setLibraryStatus(n + ' item' + (n !== 1 ? 's' : ''), false);
  2829. }, function () {
  2830. setLibraryStatus('Refresh failed · showing cached data', false);
  2831. });
  2832. }
  2833. // ─── Load library (server-side cache-first) ────────────────────────────────────
  2834. // 1. Ask getLibraryCache.js for the last saved scan result (milliseconds, no scan).
  2835. // 2a. Cache hit → render immediately, kick off backgroundScanLibrary().
  2836. // 2b. Cache miss → show loading overlay, run full scan, render when done.
  2837. function loadLibrary() {
  2838. ao_module_agirun(SCRIPT_GET_LIBRARY_CACHE, {}, function (cached) {
  2839. if (cached && !cached.error && Array.isArray(cached.data)) {
  2840. // Fast path: paint the UI from cache right away
  2841. $('#loading-overlay').hide();
  2842. library = cached.data;
  2843. libraryCacheTs = cached.ts || 0;
  2844. renderLibrary(library);
  2845. if (autoIndexEnabled) {
  2846. setLibraryStatus('Cached · ' + timeAgo(cached.ts) + ' · refreshing…', true);
  2847. backgroundScanLibrary();
  2848. } else {
  2849. // Auto indexing is off — serve the cache as-is and say so, so an
  2850. // out-of-date library never looks like a bug.
  2851. var n = library.length;
  2852. setLibraryStatus(n + ' item' + (n !== 1 ? 's' : '')
  2853. + ' · indexed ' + timeAgo(cached.ts) + ' · auto indexing off', false);
  2854. }
  2855. } else {
  2856. coldStartLibrary();
  2857. }
  2858. }, function () {
  2859. // getLibraryCache.js itself failed — treat as cold start
  2860. coldStartLibrary();
  2861. });
  2862. }
  2863. // No usable index yet. Scan if auto indexing is on; otherwise leave the library
  2864. // empty and point the user at the manual scan rather than walking every root.
  2865. function coldStartLibrary() {
  2866. if (!autoIndexEnabled) {
  2867. $('#loading-overlay').fadeOut(300);
  2868. library = [];
  2869. renderLibrary(library);
  2870. setLibraryStatus('No index yet · auto indexing off', false);
  2871. return;
  2872. }
  2873. setLibraryStatus('Loading…', true);
  2874. ao_module_agirun(SCRIPT_GET_LIBRARY, {}, function (data) {
  2875. $('#loading-overlay').fadeOut(300);
  2876. if (!data || data.error) {
  2877. showToast('Failed to load library');
  2878. setLibraryStatus('Failed to load library', false);
  2879. return;
  2880. }
  2881. library = data;
  2882. libraryCacheTs = Date.now();
  2883. renderLibrary(library);
  2884. var n = library.length;
  2885. setLibraryStatus(n + ' item' + (n !== 1 ? 's' : ''), false);
  2886. }, function () {
  2887. $('#loading-overlay').fadeOut(300);
  2888. showToast('Error loading library');
  2889. setLibraryStatus('Error loading library', false);
  2890. });
  2891. }
  2892. // ─── Manual refresh (Refresh button) ──────────────────────────────────────────
  2893. // Passes forceRefresh=1 to bypass the 8-hour staleness guard in getLibrary.js.
  2894. function refreshLibrary() {
  2895. $('#library-refresh-btn').prop('disabled', true);
  2896. setLibraryStatus('Refreshing…', true);
  2897. ao_module_agirun(SCRIPT_GET_LIBRARY, { forceRefresh: '1' }, function (data) {
  2898. $('#library-refresh-btn').prop('disabled', false);
  2899. if (!data || data.error) {
  2900. showToast('Failed to refresh library');
  2901. setLibraryStatus('Refresh failed', false);
  2902. return;
  2903. }
  2904. library = data;
  2905. libraryCacheTs = Date.now();
  2906. renderCurrentLibrary();
  2907. libraryNeedsRedraw = false;
  2908. var n = library.length;
  2909. setLibraryStatus(n + ' item' + (n !== 1 ? 's' : '') + ' · just refreshed', false);
  2910. }, function () {
  2911. $('#library-refresh-btn').prop('disabled', false);
  2912. showToast('Error refreshing library');
  2913. setLibraryStatus('Refresh failed', false);
  2914. });
  2915. }
  2916. // ═══════════════ SETTINGS TAB ═══════════════════════════════════════════════
  2917. // Indexing controls: toggle the automatic scan, rescan on demand, drop the
  2918. // index, and report what the index currently costs on disk.
  2919. function formatBytes(n) {
  2920. if (!n || n < 0) { return '0 B'; }
  2921. var units = ['B', 'KB', 'MB', 'GB'];
  2922. var i = 0;
  2923. while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; }
  2924. return (i === 0 ? n : n.toFixed(n < 10 ? 1 : 0)) + ' ' + units[i];
  2925. }
  2926. function setAutoIndexEnabled(on) {
  2927. autoIndexEnabled = !!on;
  2928. localStorage.setItem('movie_auto_index', autoIndexEnabled ? '1' : '0');
  2929. $('#setting-auto-index').prop('checked', autoIndexEnabled);
  2930. }
  2931. function setSettingsBusy(busy, text) {
  2932. $('#settings-progress').toggleClass('active', !!busy);
  2933. if (text) { $('#settings-progress-text').text(text); }
  2934. $('#settings-scan-btn, #settings-clear-btn').prop('disabled', !!busy);
  2935. }
  2936. // Album/video totals come from the in-memory library (already loaded from the
  2937. // same cache file), so this never re-parses the multi-MB index server-side.
  2938. function renderIndexStats(stats) {
  2939. var albums = library ? library.length : 0;
  2940. var videos = 0;
  2941. var byType = {};
  2942. if (library) {
  2943. for (var i = 0; i < library.length; i++) {
  2944. var a = library[i];
  2945. videos += (a.episodeCount || 0);
  2946. byType[a.type] = (byType[a.type] || 0) + 1;
  2947. }
  2948. }
  2949. $('#stat-size').text(stats && stats.exists ? formatBytes(stats.sizeBytes) : '—');
  2950. $('#stat-albums').text(albums.toLocaleString());
  2951. $('#stat-videos').text(videos.toLocaleString());
  2952. $('#stat-roots').text(stats ? String(stats.roots) : '—');
  2953. var labels = {
  2954. movie: ['Movie', 'Movies'],
  2955. collection: ['Collection', 'Collections'],
  2956. series: ['TV show', 'TV shows'],
  2957. anime: ['Anime', 'Anime'],
  2958. short: ['Short', 'Shorts']
  2959. };
  2960. var $bd = $('#settings-breakdown').empty();
  2961. ['movie', 'collection', 'series', 'anime', 'short'].forEach(function (t) {
  2962. var n = byType[t];
  2963. if (!n) { return; }
  2964. var label = labels[t] ? labels[t][n === 1 ? 0 : 1] : t;
  2965. $bd.append('<span class="breakdown-chip"><b>' + n + '</b> ' + escapeHtml(label) + '</span>');
  2966. });
  2967. if (stats && stats.skippedRoots > 0) {
  2968. $bd.append('<span class="breakdown-chip"><b>' + stats.skippedRoots
  2969. + '</b> root' + (stats.skippedRoots !== 1 ? 's' : '') + ' skipped</span>');
  2970. }
  2971. var when = (stats && stats.exists && libraryCacheTs)
  2972. ? 'Last scan: ' + timeAgo(libraryCacheTs) + ' (' + new Date(libraryCacheTs).toLocaleString() + ')'
  2973. : (stats && stats.exists ? 'Last scan: unknown' : 'No index on disk — run a scan to build one.');
  2974. $('#settings-last-scan').text(when);
  2975. }
  2976. function refreshIndexStats() {
  2977. renderIndexStats(null); // paint client-side counts immediately
  2978. ao_module_agirun(SCRIPT_GET_INDEX_STATS, {}, function (stats) {
  2979. if (stats && !stats.error) { renderIndexStats(stats); }
  2980. }, function () {});
  2981. }
  2982. function settingsScanNow() {
  2983. setSettingsBusy(true, 'Scanning every storage root — this can take a while…');
  2984. setLibraryStatus('Rescanning…', true);
  2985. ao_module_agirun(SCRIPT_GET_LIBRARY, { forceRefresh: '1' }, function (data) {
  2986. setSettingsBusy(false);
  2987. if (!data || data.error) {
  2988. showToast('Scan failed');
  2989. setLibraryStatus('Scan failed', false);
  2990. return;
  2991. }
  2992. library = data;
  2993. libraryCacheTs = Date.now();
  2994. renderCurrentLibrary();
  2995. libraryNeedsRedraw = false;
  2996. var n = library.length;
  2997. setLibraryStatus(n + ' item' + (n !== 1 ? 's' : '') + ' · just refreshed', false);
  2998. refreshIndexStats();
  2999. showToast('Scan complete — ' + n + ' title' + (n !== 1 ? 's' : '') + ' indexed');
  3000. }, function () {
  3001. setSettingsBusy(false);
  3002. showToast('Error while scanning');
  3003. setLibraryStatus('Scan failed', false);
  3004. });
  3005. }
  3006. function settingsClearIndex() {
  3007. if (!confirm('Clear the library index?\n\nOnly the cached scan result is deleted — your video files are not touched.')) {
  3008. return;
  3009. }
  3010. setSettingsBusy(true, 'Clearing index…');
  3011. ao_module_agirun(SCRIPT_CLEAR_INDEX, {}, function (res) {
  3012. setSettingsBusy(false);
  3013. if (!res || res.error) { showToast('Could not clear the index'); return; }
  3014. library = [];
  3015. libraryCacheTs = 0;
  3016. renderLibrary(library);
  3017. libraryNeedsRedraw = false;
  3018. setLibraryStatus('No index yet' + (autoIndexEnabled ? '' : ' · auto indexing off'), false);
  3019. refreshIndexStats();
  3020. showToast(res.removed ? 'Index cleared' : 'No index to clear');
  3021. }, function () {
  3022. setSettingsBusy(false);
  3023. showToast('Could not clear the index');
  3024. });
  3025. }
  3026. function initSettings() {
  3027. $('#setting-auto-index').prop('checked', autoIndexEnabled).on('change', function () {
  3028. setAutoIndexEnabled($(this).is(':checked'));
  3029. showToast('Auto indexing ' + (autoIndexEnabled ? 'enabled' : 'disabled'));
  3030. });
  3031. $('#settings-scan-btn').on('click', settingsScanNow);
  3032. $('#settings-clear-btn').on('click', settingsClearIndex);
  3033. }
  3034. // ─── Render library grid ──────────────────────────────────────────────────────
  3035. function renderLibrary(albums) {
  3036. moviesData = albums.filter(function (a) { return a.type === 'movie'; });
  3037. collectionsData = albums.filter(function (a) { return a.type === 'collection'; });
  3038. showsData = albums.filter(function (a) { return a.type === 'series'; });
  3039. animeData = albums.filter(function (a) { return a.type === 'anime'; });
  3040. shortsData = albums.filter(function (a) { return a.type === 'short'; });
  3041. moviesShown = 0;
  3042. collectionsShown = 0;
  3043. showsShown = 0;
  3044. animeShown = 0;
  3045. shortsShown = 0;
  3046. $('#movies-grid').empty();
  3047. $('#collections-grid').empty();
  3048. $('#series-grid').empty();
  3049. $('#shorts-grid').empty();
  3050. $('#anime-grid').empty();
  3051. if (!moviesData.length && !collectionsData.length && !showsData.length && !animeData.length && !shortsData.length) {
  3052. $('#no-content').show();
  3053. return;
  3054. }
  3055. $('#no-content').hide();
  3056. if (moviesData.length > 0) { $('#movies-section').show(); loadMoreSection('movies'); }
  3057. else { $('#movies-section').hide(); }
  3058. if (collectionsData.length > 0) { $('#collections-section').show(); loadMoreSection('collections'); }
  3059. else { $('#collections-section').hide(); }
  3060. if (showsData.length > 0) { $('#series-section').show(); loadMoreSection('shows'); }
  3061. else { $('#series-section').hide(); }
  3062. if (animeData.length > 0) { $('#anime-section').show(); loadMoreSection('anime'); }
  3063. else { $('#anime-section').hide(); }
  3064. if (shortsData.length > 0) { $('#shorts-section').show(); loadMoreSection('shorts'); }
  3065. else { $('#shorts-section').hide(); }
  3066. }
  3067. function loadMoreSection(which) {
  3068. var data, $grid, $btn, start, end, i;
  3069. if (which === 'movies') {
  3070. data = moviesData;
  3071. $grid = $('#movies-grid');
  3072. $btn = $('#movies-load-more');
  3073. start = moviesShown;
  3074. end = Math.min(start + PAGE_SIZE, data.length);
  3075. for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
  3076. moviesShown = end;
  3077. $btn.toggle(moviesShown < data.length);
  3078. } else if (which === 'shows') {
  3079. data = showsData;
  3080. $grid = $('#series-grid');
  3081. $btn = $('#shows-load-more');
  3082. start = showsShown;
  3083. end = Math.min(start + PAGE_SIZE, data.length);
  3084. for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
  3085. showsShown = end;
  3086. $btn.toggle(showsShown < data.length);
  3087. } else if (which === 'collections') {
  3088. data = collectionsData;
  3089. $grid = $('#collections-grid');
  3090. $btn = $('#collections-load-more');
  3091. start = collectionsShown;
  3092. end = Math.min(start + PAGE_SIZE, data.length);
  3093. for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
  3094. collectionsShown = end;
  3095. $btn.toggle(collectionsShown < data.length);
  3096. } else if (which === 'anime') {
  3097. data = animeData;
  3098. $grid = $('#anime-grid');
  3099. $btn = $('#anime-load-more');
  3100. start = animeShown;
  3101. end = Math.min(start + PAGE_SIZE, data.length);
  3102. for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
  3103. animeShown = end;
  3104. $btn.toggle(animeShown < data.length);
  3105. } else {
  3106. data = shortsData;
  3107. $grid = $('#shorts-grid');
  3108. $btn = $('#shorts-load-more');
  3109. start = shortsShown;
  3110. end = Math.min(start + PAGE_SIZE, data.length);
  3111. for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
  3112. shortsShown = end;
  3113. $btn.toggle(shortsShown < data.length);
  3114. }
  3115. loadCardThumbnails();
  3116. }
  3117. function buildCard(album, idx) {
  3118. var thumb = album.thumbnail && album.thumbnail.length > 0
  3119. ? '<img class="poster" src="data:image/jpeg;base64,' + album.thumbnail + '" alt="">'
  3120. : '<div class="poster-placeholder"><img src="img/thumbnail.png" alt=""></div>';
  3121. var badge = album.type === 'series' ? '<span class="badge series">Series</span>'
  3122. : album.type === 'anime' ? '<span class="badge anime">Anime</span>'
  3123. : '';
  3124. var ext = album._singleFile ? album._singleFile.split('.').pop().toUpperCase() : '';
  3125. var meta = (album.type === 'series' || album.type === 'anime')
  3126. ? album.episodeCount + ' ep'
  3127. : album.type === 'short'
  3128. ? (ext || 'Short')
  3129. : album.type === 'collection'
  3130. ? album.episodeCount + (album.episodeCount > 1 ? ' videos' : ' video')
  3131. : album.episodeCount + (album.episodeCount > 1 ? ' parts' : ' movie');
  3132. var card = $('<div class="album-card" tabindex="0" role="button" aria-label="' + escapeAttr(album.name) + '">'
  3133. + thumb
  3134. + badge
  3135. + '<div class="card-info">'
  3136. + '<div class="card-title">' + escapeHtml(album.name) + '</div>'
  3137. + '<div class="card-meta">' + escapeHtml(meta) + '</div>'
  3138. + '</div>'
  3139. + '</div>');
  3140. card.data('album', album);
  3141. card.on('click', function () {
  3142. if (album.type === 'short' && album._singleFile) {
  3143. currentAlbum = album; currentSeason = null;
  3144. currentEpisodes = [{ name: album.name, filepath: album._singleFile,
  3145. ext: album._singleFile.split('.').pop().toLowerCase(), index: 0 }];
  3146. startPlayback(0);
  3147. } else if (album.type === 'movie') {
  3148. openMovieInfo(album);
  3149. } else { openDetail(album); }
  3150. });
  3151. card.on('keydown', function (e) {
  3152. if (e.key === 'Enter' || e.key === ' ') {
  3153. e.preventDefault();
  3154. if (album.type === 'short' && album._singleFile) {
  3155. currentAlbum = album; currentSeason = null;
  3156. currentEpisodes = [{ name: album.name, filepath: album._singleFile,
  3157. ext: album._singleFile.split('.').pop().toLowerCase(), index: 0 }];
  3158. startPlayback(0);
  3159. } else if (album.type === 'movie') {
  3160. openMovieInfo(album);
  3161. } else { openDetail(album); }
  3162. }
  3163. });
  3164. return card;
  3165. }
  3166. // Load thumbnails in background (for cards that don't have one embedded)
  3167. function loadCardThumbnails() {
  3168. $('.album-card').each(function () {
  3169. var $card = $(this);
  3170. var album = $card.data('album');
  3171. if (!album || album.thumbnail) { return; } // already has thumb
  3172. // For shorts use the actual video file; folder path would yield the generic folder thumbnail
  3173. var fileParam = (album.type === 'short' && album._singleFile) ? album._singleFile : album.folderpath;
  3174. ao_module_agirun(SCRIPT_GET_THUMBNAIL, { file: fileParam }, function (data) {
  3175. if (data && !data.error && data.length > 20) {
  3176. $card.find('.poster-placeholder')
  3177. .replaceWith('<img class="poster" src="data:image/jpeg;base64,' + data + '" alt="">');
  3178. }
  3179. });
  3180. });
  3181. }
  3182. // ─── Detail view ──────────────────────────────────────────────────────────────
  3183. function openDetail(album) {
  3184. currentAlbum = album;
  3185. // Hero background
  3186. var bg = album.thumbnail ? 'data:image/jpeg;base64,' + album.thumbnail : '';
  3187. $('#detail-hero-bg').css('background-image', bg ? 'url(' + bg + ')' : 'none');
  3188. // Poster
  3189. var posterHtml = album.thumbnail
  3190. ? '<img src="data:image/jpeg;base64,' + album.thumbnail + '" alt="" style="width:100%;aspect-ratio:2/3;object-fit:cover;">'
  3191. : '<div class="poster-placeholder"><img src="img/icons/movie_white.svg" alt=""></div>';
  3192. $('#detail-poster').html(posterHtml);
  3193. // Title & subtitle
  3194. $('#detail-title').text(album.name);
  3195. var sub = (album.type === 'series' || album.type === 'anime')
  3196. ? album.seasons.length + ' season' + (album.seasons.length !== 1 ? 's' : '') + ' · ' + album.episodeCount + ' episodes'
  3197. : album.type === 'collection'
  3198. ? album.episodeCount + (album.episodeCount > 1 ? ' videos' : ' video')
  3199. : album.episodeCount + (album.episodeCount > 1 ? ' parts' : ' movie');
  3200. $('#detail-subtitle').text(sub);
  3201. // Season tabs
  3202. var $tabs = $('#season-tabs').empty();
  3203. if ((album.type === 'series' || album.type === 'anime') && album.seasons.length > 0) {
  3204. album.seasons.forEach(function (s, i) {
  3205. var tab = $('<button class="season-tab" tabindex="0" title="' + escapeAttr(s.name) + '">'
  3206. + escapeHtml(s.name) + '</button>');
  3207. tab.data('season', s);
  3208. tab.on('click', function () { selectSeason($(this).data('season')); activateTab(this); });
  3209. $tabs.append(tab);
  3210. });
  3211. $tabs.show();
  3212. selectSeason(album.seasons[0]);
  3213. $tabs.find('.season-tab').first().addClass('active');
  3214. } else {
  3215. $tabs.hide();
  3216. // Load the folder directly as episodes
  3217. loadEpisodes(album.folderpath);
  3218. }
  3219. // Play / shuffle button bindings
  3220. $('#btn-play-first').off('click').on('click', function () {
  3221. if (currentEpisodes.length > 0) { startPlayback(0); }
  3222. });
  3223. $('#btn-shuffle').off('click').on('click', function () {
  3224. if (currentEpisodes.length === 0) { return; }
  3225. var idx = Math.floor(Math.random() * currentEpisodes.length);
  3226. startPlayback(idx);
  3227. });
  3228. showView('detail');
  3229. }
  3230. function selectSeason(season) {
  3231. currentSeason = season;
  3232. loadEpisodes(season.folderpath);
  3233. }
  3234. function activateTab(el) {
  3235. $('#season-tabs .season-tab').removeClass('active');
  3236. $(el).addClass('active');
  3237. }
  3238. function loadEpisodes(folderpath) {
  3239. $('#episode-list').html('<div style="color:var(--text-sub);padding:20px 0;">Loading…</div>');
  3240. ao_module_agirun(SCRIPT_GET_EPISODES, { folder: folderpath }, function (data) {
  3241. if (!data || data.error) {
  3242. $('#episode-list').html('<div style="color:var(--text-sub);padding:20px 0;">No episodes found.</div>');
  3243. currentEpisodes = [];
  3244. return;
  3245. }
  3246. currentEpisodes = data;
  3247. renderEpisodes(data);
  3248. }, function () {
  3249. $('#episode-list').html('<div style="color:var(--text-sub);padding:20px 0;">Error loading episodes.</div>');
  3250. });
  3251. }
  3252. function renderEpisodes(episodes) {
  3253. var $list = $('#episode-list').empty();
  3254. episodes.forEach(function (ep, i) {
  3255. var row = $('<div class="episode-item" tabindex="0" role="button">'
  3256. + '<div class="ep-thumb"><div class="ep-thumb-placeholder"><img src="img/icons/play_white.svg" alt=""></div></div>'
  3257. + '<div class="ep-info">'
  3258. + '<div class="ep-name">' + escapeHtml(ep.name) + '</div>'
  3259. + '<div class="ep-path">' + escapeHtml(ep.ext.replace('.', '').toUpperCase()) + '</div>'
  3260. + '</div>'
  3261. + '<div class="ep-play-icon"><img src="img/icons/play_white.svg" alt=""></div>'
  3262. + '</div>');
  3263. row.data('ep', ep);
  3264. row.data('idx', i);
  3265. row.on('click', function () { startPlayback($(this).data('idx')); });
  3266. row.on('keydown', function (e) {
  3267. if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); startPlayback($(this).data('idx')); }
  3268. });
  3269. $list.append(row);
  3270. // Lazy-load thumbnail
  3271. (function (epObj, rowEl) {
  3272. ao_module_agirun(SCRIPT_GET_THUMBNAIL, { file: epObj.filepath }, function (data) {
  3273. if (data && !data.error && data.length > 20) {
  3274. rowEl.find('.ep-thumb-placeholder')
  3275. .replaceWith('<img src="data:image/jpeg;base64,' + data + '" alt="">');
  3276. }
  3277. });
  3278. })(ep, row);
  3279. });
  3280. }
  3281. // ─── Player ───────────────────────────────────────────────────────────────────
  3282. function isWebPlayable(ext) {
  3283. return ['mp4', 'webm', 'ogg'].includes(ext);
  3284. }
  3285. function startPlayback(index) {
  3286. // Coming from inside the player means this is an episode change rather than
  3287. // a fresh playback, and the playlist is handled differently (see below).
  3288. var isEpisodeChange = $('#view-player').hasClass('active');
  3289. cancelCountdown();
  3290. hideSeekFreeze(); // never carry a frozen frame across to a different episode
  3291. resetSubtitleSeekFloor(); // a fresh episode starts unsuppressed
  3292. $('#resume-popup').removeClass('active');
  3293. if (!currentEpisodes || currentEpisodes.length === 0) { return; }
  3294. playingIndex = index;
  3295. var ep = currentEpisodes[index];
  3296. var ext = ep.ext ? ep.ext.toLowerCase().replace(/^\./, '') : '';
  3297. // Reset transcode seek state for the new episode
  3298. transcodeSeekOffset = 0;
  3299. transcodeDuration = 0;
  3300. var vid = document.getElementById('main-video');
  3301. // The extension only says the container might be playable; the codec inside
  3302. // decides. The cast receiver is a separate client but faces the same codecs,
  3303. // so it is routed through the same verdict.
  3304. resolveDirectPlay(ep.filepath, ext, function (directPlay) {
  3305. if (playingIndex !== index) { return; } // episode changed while probing
  3306. renderStreamQuality(); // the probe now knows which steps this file allows
  3307. if (castMode && _castConnected()) {
  3308. // Don't load locally — avoids transcoding the same file twice.
  3309. // The receiver always gets the MP4 stream rather than this browser's
  3310. // streaming-mode preference.
  3311. isTranscodedVideo = !directPlay;
  3312. vid.pause();
  3313. _castSend('media.load', {
  3314. filepath: ep.filepath, name: ep.name, type: 'video',
  3315. src: directPlay ? MEDIA_API + '?file=' + encodeURIComponent(ep.filepath)
  3316. : TRANSCODE_API + '?file=' + encodeURIComponent(ep.filepath)
  3317. + streamQualityParam(ep.filepath),
  3318. startTime: 0
  3319. });
  3320. // Volume after load, before play — guarantees device volume overrides
  3321. // whatever Arozcast was previously playing at.
  3322. _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted });
  3323. _castSend('media.play', {});
  3324. armResumePrompt(ep, index);
  3325. return;
  3326. }
  3327. beginEpisodeStream(ep, index, directPlay);
  3328. });
  3329. $('#now-playing-title, #topbar-title').text(ep.name);
  3330. ao_module_setWindowTitle('Movie – ' + ep.name);
  3331. scheduleStoryboardLoad(ep.filepath);
  3332. loadEmbeddedTrackList(ep.filepath);
  3333. renderSidebar(currentEpisodes, index);
  3334. if (isEpisodeChange) {
  3335. peekPlaylistForEpisodeChange();
  3336. } else {
  3337. // New playback — drop any manual show/hide the user applied to the last one
  3338. cancelPlaylistPeek();
  3339. playlistUserToggled = false;
  3340. applyPlaylistVisibility();
  3341. }
  3342. highlightPlayingEpisode(index);
  3343. // Remember where we came from so closePlayer() can return there
  3344. var curView = $('.view.active').attr('id');
  3345. if (curView && curView !== 'view-player') {
  3346. playerReturnView = curView.replace('view-', '');
  3347. }
  3348. showView('player');
  3349. showControls();
  3350. }
  3351. // Bind the video element to the right stream and arm the resume prompt.
  3352. //
  3353. // Split out of startPlayback because the direct-play decision depends on a
  3354. // codec probe and so arrives asynchronously; it is also the retry target when
  3355. // direct playback turns out to fail anyway.
  3356. function beginEpisodeStream(ep, index, directPlay) {
  3357. var vid = document.getElementById('main-video');
  3358. clearDirectPlaybackWatch(vid);
  3359. detachTranscodeStream(vid);
  3360. isTranscodedVideo = !directPlay;
  3361. transcodeSeekOffset = 0;
  3362. transcodeDuration = 0;
  3363. if (directPlay) {
  3364. vid.src = MEDIA_API + '?file=' + encodeURIComponent(ep.filepath);
  3365. // Last resort: a browser without the platform decoder the probe assumed
  3366. onDirectPlaybackFailure(vid, function () {
  3367. if (playingIndex !== index) { return; }
  3368. showToast('This browser cannot decode that file — switching to a transcode');
  3369. beginEpisodeStream(ep, index, false);
  3370. });
  3371. playVideo(vid);
  3372. } else if (!attachTranscodeStream(vid, transcodeStreamURL(ep.filepath, 0),
  3373. function (reason) { showToast(reason); },
  3374. function () { playVideo(vid); })) {
  3375. showToast('This browser cannot play the transcoded stream. Switch streaming mode to MP4 in settings.');
  3376. return;
  3377. }
  3378. armResumePrompt(ep, index);
  3379. }
  3380. // Offer to resume where the viewer left off. Direct playback learns its length
  3381. // from the element; a transcode has to ask the server for it.
  3382. function armResumePrompt(ep, index) {
  3383. var vid = document.getElementById('main-video');
  3384. if (!isTranscodedVideo) {
  3385. (function (epFilepath) {
  3386. $(vid).off('loadedmetadata.resume').one('loadedmetadata.resume', function () {
  3387. if (vid.duration > 3600) {
  3388. ao_module_agirun(SCRIPT_GET_WATCHTIME, { filepath: epFilepath }, function (data) {
  3389. if (data && !data.error && data.position > 30 && data.position < vid.duration * 0.95) {
  3390. showResumePopup(data.position, vid.duration);
  3391. }
  3392. });
  3393. }
  3394. });
  3395. })(ep.filepath);
  3396. } else {
  3397. $(vid).off('loadedmetadata.resume'); // clear any stale handler
  3398. (function (capturedEp, capturedIndex) {
  3399. fetch(ao_root + 'media/duration/?file=' + encodeURIComponent(capturedEp.filepath))
  3400. .then(function (r) { return r.json(); })
  3401. .then(function (data) {
  3402. if (data.duration > 0 && playingIndex === capturedIndex &&
  3403. currentEpisodes[capturedIndex] &&
  3404. currentEpisodes[capturedIndex].filepath === capturedEp.filepath) {
  3405. transcodeDuration = data.duration;
  3406. if (transcodeDuration > 3600) {
  3407. ao_module_agirun(SCRIPT_GET_WATCHTIME, { filepath: capturedEp.filepath }, function (wdata) {
  3408. if (wdata && !wdata.error && wdata.position > 30 && wdata.position < transcodeDuration * 0.95) {
  3409. showResumePopup(wdata.position, transcodeDuration);
  3410. }
  3411. });
  3412. }
  3413. }
  3414. }).catch(function () {});
  3415. })(ep, index);
  3416. }
  3417. }
  3418. function renderSidebar(episodes, playing) {
  3419. var $list = $('#sidebar-list').empty();
  3420. episodes.forEach(function (ep, i) {
  3421. var row = $('<div class="sidebar-ep' + (i === playing ? ' playing' : '') + '" tabindex="0" role="button">'
  3422. + '<span class="sidebar-ep-num">' + (i + 1) + '</span>'
  3423. + '<span class="sidebar-ep-name">' + escapeHtml(ep.name) + '</span>'
  3424. + '</div>');
  3425. row.data('idx', i);
  3426. row.on('click', function () {
  3427. cancelCountdown();
  3428. startPlayback($(this).data('idx'));
  3429. });
  3430. $list.append(row);
  3431. });
  3432. // Scroll to playing
  3433. var $playing = $list.find('.playing');
  3434. if ($playing.length) {
  3435. setTimeout(function () { $playing[0].scrollIntoView({ block: 'center' }); }, 50);
  3436. }
  3437. }
  3438. function highlightPlayingEpisode(idx) {
  3439. $('#episode-list .episode-item').removeClass('playing');
  3440. $('#episode-list .episode-item').eq(idx).addClass('playing');
  3441. }
  3442. function closePlayer() {
  3443. // Always cancel any pending auto-reconnect
  3444. clearTimeout(castReconnectTimer); castReconnectTimer = null;
  3445. castReconnectCount = 0; castPendingCode = null;
  3446. if (castMode) {
  3447. // Do NOT send media.stop — Arozcast will keep playing.
  3448. // Only disconnectCast() (explicit user action) stops remote playback.
  3449. if (castWs) { castWs.onclose = null; castWs.close(); castWs = null; }
  3450. clearInterval(castPingTimer); clearInterval(castWatchTimer);
  3451. castPingTimer = castWatchTimer = null;
  3452. castMode = false; castCode = null;
  3453. $('#ctrl-cast, #ctrl-cast-top').removeClass('casting');
  3454. }
  3455. saveWatchPosition();
  3456. cancelCountdown();
  3457. cancelPlaylistPeek();
  3458. hideSeekFreeze();
  3459. resetStoryboard();
  3460. resetEmbeddedTracks();
  3461. if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
  3462. var vid = document.getElementById('main-video');
  3463. vid.pause();
  3464. // Release the HLS attachment before clearing the source, or it keeps
  3465. // fetching segments into an element nobody is watching.
  3466. clearDirectPlaybackWatch(vid);
  3467. detachTranscodeStream(vid);
  3468. vid.removeAttribute('src');
  3469. $('#resume-popup').removeClass('active');
  3470. var returnTo = (currentAlbum && (currentAlbum.type === 'series' || currentAlbum.type === 'anime' || currentAlbum.type === 'collection'))
  3471. ? 'detail'
  3472. : playerReturnView;
  3473. showView(returnTo);
  3474. }
  3475. function showLibrary() {
  3476. showView('library');
  3477. currentAlbum = null;
  3478. // If a background refresh completed while the user was away, apply it now
  3479. if (libraryNeedsRedraw) {
  3480. libraryNeedsRedraw = false;
  3481. renderCurrentLibrary();
  3482. }
  3483. }
  3484. // ─── View switching ───────────────────────────────────────────────────────────
  3485. function showView(name) {
  3486. $('.view').removeClass('active');
  3487. $('#view-' + name).addClass('active');
  3488. if (name === 'library' || name === 'detail') {
  3489. $('.mode-tab').removeClass('active');
  3490. $('#tab-library').addClass('active');
  3491. $('#search-wrap').show();
  3492. } else if (name === 'folder') {
  3493. $('.mode-tab').removeClass('active');
  3494. $('#tab-folder').addClass('active');
  3495. $('#search-wrap').hide();
  3496. } else if (name === 'movie-info') {
  3497. $('.mode-tab').removeClass('active');
  3498. $('#tab-library').addClass('active');
  3499. $('#search-wrap').hide();
  3500. } else if (name === 'settings') {
  3501. $('.mode-tab').removeClass('active');
  3502. $('#tab-settings').addClass('active');
  3503. $('#search-wrap').hide();
  3504. }
  3505. // player view leaves tab state unchanged
  3506. }
  3507. // ─── Video controls ───────────────────────────────────────────────────────────
  3508. function initVideoControls() {
  3509. var vid = document.getElementById('main-video');
  3510. var $ctrl = $('#video-controls');
  3511. var $prog = $('#progress-bar');
  3512. var $thumb = $('#progress-thumb');
  3513. var $time = $('#time-display');
  3514. var $play = $('#ctrl-play');
  3515. var $mute = $('#ctrl-mute');
  3516. // Restore saved volume from last session
  3517. var savedVol = parseFloat(localStorage.getItem('movie_volume'));
  3518. if (!isNaN(savedVol) && savedVol >= 0 && savedVol <= 1) {
  3519. vid.volume = savedVol;
  3520. $('#volume-slider').val(savedVol);
  3521. }
  3522. if (localStorage.getItem('movie_muted') === '1') { vid.muted = true; }
  3523. // Play/Pause
  3524. $('#ctrl-play').on('click', function () { togglePlay(); });
  3525. $('#ctrl-mute').on('click', function () {
  3526. vid.muted = !vid.muted;
  3527. updateMuteIcon();
  3528. if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
  3529. });
  3530. $('#ctrl-prev').on('click', function () { playOffset(-1); });
  3531. $('#ctrl-next').on('click', function () { playOffset(1); });
  3532. $('#ctrl-fs').on('click', function () { toggleFullscreen(); });
  3533. $('#ctrl-list').on('click', function () { toggleSidebar(); });
  3534. $('#volume-slider').on('input', function () {
  3535. vid.volume = parseFloat($(this).val());
  3536. updateMuteIcon();
  3537. if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
  3538. });
  3539. // Progress bar click / drag
  3540. $('#progress-wrap').on('click', function (e) {
  3541. if (castMode && _castConnected()) {
  3542. if (castDuration > 0) {
  3543. var pct = e.offsetX / $(this).width();
  3544. var seekTo = pct * castDuration;
  3545. _castSend('media.seek', { time: seekTo });
  3546. // Optimistic update — reflect position immediately
  3547. castCurrentTime = seekTo;
  3548. _castUpdateProgressUI();
  3549. }
  3550. return;
  3551. }
  3552. if (isTranscodedVideo && transcodeDuration > 0 && playingIndex >= 0 && currentEpisodes[playingIndex]) {
  3553. transcodeSeekTo((e.offsetX / $(this).width()) * transcodeDuration);
  3554. return;
  3555. }
  3556. if (vid.duration) {
  3557. var pct = e.offsetX / $(this).width();
  3558. vid.currentTime = pct * vid.duration;
  3559. }
  3560. });
  3561. // Video events
  3562. $(vid).on('timeupdate', function () {
  3563. if (isTranscodedVideo) {
  3564. var displayTime = vid.currentTime + transcodeSeekOffset;
  3565. if (transcodeDuration > 0) {
  3566. var pct = (displayTime / transcodeDuration) * 100;
  3567. $prog.css('width', pct + '%');
  3568. $thumb.css('left', 'calc(' + pct + '% - 7px)');
  3569. $time.text(formatTime(displayTime) + ' / ' + formatTime(transcodeDuration));
  3570. } else {
  3571. $time.text(formatTime(displayTime) + ' / --:--');
  3572. }
  3573. return;
  3574. }
  3575. if (!vid.duration) { return; }
  3576. var pct = (vid.currentTime / vid.duration) * 100;
  3577. $prog.css('width', pct + '%');
  3578. $thumb.css('left', 'calc(' + pct + '% - 7px)');
  3579. $time.text(formatTime(vid.currentTime) + ' / ' + formatTime(vid.duration));
  3580. });
  3581. $(vid).on('play', function () {
  3582. $('#play-icon').attr('src', 'img/icons/pause_white.svg');
  3583. // Periodically save position for videos longer than 1 hr
  3584. if (watchSaveInterval) { clearInterval(watchSaveInterval); }
  3585. watchSaveInterval = setInterval(function () {
  3586. var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
  3587. if (!vid.paused && effectiveDuration > 3600) { saveWatchPosition(); }
  3588. }, 30000);
  3589. });
  3590. $(vid).on('pause', function () {
  3591. $('#play-icon').attr('src', 'img/icons/play_white.svg');
  3592. if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
  3593. var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
  3594. var effectiveTime = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
  3595. if (effectiveDuration > 3600 && effectiveTime > 30) { saveWatchPosition(); }
  3596. });
  3597. $(vid).on('ended', function () {
  3598. clearWatchPosition(); // video finished naturally — remove resume point
  3599. if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
  3600. cancelCountdown();
  3601. if (repeatSingle) {
  3602. vid.currentTime = 0;
  3603. playVideo(vid);
  3604. } else if (playingIndex < currentEpisodes.length - 1 && autoplayEnabled) {
  3605. startNextCountdown();
  3606. }
  3607. });
  3608. $(vid).on('volumechange', function () {
  3609. updateMuteIcon();
  3610. localStorage.setItem('movie_volume', vid.volume);
  3611. localStorage.setItem('movie_muted', vid.muted ? '1' : '0');
  3612. });
  3613. // Drop the transcode-seek freeze frame the moment the new segment is live.
  3614. // 'playing' is the accurate signal; 'loadeddata' covers a seek made while
  3615. // paused (where 'playing' never fires), and 'error' avoids a stuck overlay.
  3616. // Any seek — native or transcode reload — re-bases the subtitle floor
  3617. $(vid).on('seeking', function () { setSubtitleSeekFloor(effectivePlaybackTime()); });
  3618. $(vid).on('playing', function () {
  3619. hideSeekFreeze();
  3620. streamRecoveryAttempts = 0; // the stream is healthy again
  3621. });
  3622. $(vid).on('loadeddata', function () { if (vid.paused) { hideSeekFreeze(); } });
  3623. $(vid).on('error', function () {
  3624. hideSeekFreeze();
  3625. recoverTranscodeStream();
  3626. });
  3627. $(vid).on(STREAM_LOST_EVENT, function (e) {
  3628. hideSeekFreeze();
  3629. if (recoverTranscodeStream()) { return; }
  3630. var detail = (e.originalEvent && e.originalEvent.detail) || {};
  3631. showToast(detail.reason || 'The HLS stream stopped and could not be reopened.');
  3632. });
  3633. // Auto-hide controls
  3634. $('#video-container').on('mousemove touchstart', function () { showControls(); });
  3635. // Click on video = play/pause
  3636. $(vid).on('click', function () { togglePlay(); });
  3637. // Hide back button when in fullscreen (JS reinforcement)
  3638. document.addEventListener('fullscreenchange', function () {
  3639. $('#player-topbar').toggle(!document.fullscreenElement);
  3640. });
  3641. document.addEventListener('webkitfullscreenchange', function () {
  3642. $('#player-topbar').toggle(!document.webkitFullscreenElement);
  3643. });
  3644. function updateMuteIcon() {
  3645. var isMuted = vid.muted || vid.volume === 0;
  3646. $('#mute-icon').attr('src', isMuted ? 'img/icons/mute_white.svg' : 'img/icons/volume_white.svg');
  3647. $('#volume-slider').val(vid.muted ? 0 : vid.volume);
  3648. }
  3649. }
  3650. // Optimistic UI sync for cast mode — call immediately after sending a seek/play/pause command
  3651. // so the user sees instant feedback instead of waiting up to 3 s for status.update.
  3652. function _castUpdateProgressUI() {
  3653. if (!castDuration) return;
  3654. var pct = (castCurrentTime / castDuration) * 100;
  3655. $('#progress-bar').css('width', pct + '%');
  3656. $('#progress-thumb').css('left', 'calc(' + pct + '% - 7px)');
  3657. $('#time-display').text(formatTime(castCurrentTime) + ' / ' + formatTime(castDuration));
  3658. }
  3659. function togglePlay() {
  3660. $('#resume-popup').removeClass('active');
  3661. if (castMode && _castConnected()) {
  3662. if (castIsPlaying) {
  3663. _castSend('media.pause', {});
  3664. castIsPlaying = false;
  3665. $('#play-icon').attr('src', 'img/icons/play_white.svg');
  3666. } else {
  3667. _castSend('media.play', {});
  3668. castIsPlaying = true;
  3669. $('#play-icon').attr('src', 'img/icons/pause_white.svg');
  3670. }
  3671. flashPlayState(castIsPlaying);
  3672. return;
  3673. }
  3674. var vid = document.getElementById('main-video');
  3675. var willPlay = vid.paused;
  3676. if (willPlay) { playVideo(vid); } else { vid.pause(); }
  3677. flashPlayState(willPlay);
  3678. }
  3679. function playOffset(offset) {
  3680. var next = playingIndex + offset;
  3681. if (next < 0) { next = 0; }
  3682. if (next >= currentEpisodes.length) { next = currentEpisodes.length - 1; }
  3683. if (next !== playingIndex) { startPlayback(next); }
  3684. }
  3685. function showControls() {
  3686. $('#video-controls').removeClass('hidden');
  3687. clearTimeout(controlsTimer);
  3688. controlsTimer = setTimeout(function () {
  3689. var isPlaying = castMode ? castIsPlaying : !document.getElementById('main-video').paused;
  3690. // Keep the bar up while a popup is open — both are anchored to it
  3691. if (isPlaying && !$('#settings-popup').hasClass('active') && !$('#subtitle-popup').hasClass('active')) {
  3692. $('#video-controls').addClass('hidden');
  3693. }
  3694. }, 3000);
  3695. }
  3696. function toggleFullscreen() {
  3697. var el = document.getElementById('view-player');
  3698. if (!document.fullscreenElement) {
  3699. el.requestFullscreen && el.requestFullscreen();
  3700. } else {
  3701. document.exitFullscreen && document.exitFullscreen();
  3702. }
  3703. }
  3704. function toggleSidebar() {
  3705. cancelPlaylistPeek(); // a manual toggle outranks a pending auto-close
  3706. playlistUserToggled = true; // stop auto-management until the next playback
  3707. $('#playlist-sidebar').toggleClass('collapsed');
  3708. }
  3709. function cancelPlaylistPeek() {
  3710. if (playlistPeekTimer) { clearTimeout(playlistPeekTimer); playlistPeekTimer = null; }
  3711. }
  3712. // Skipping to another episode used to re-run applyPlaylistVisibility(), which
  3713. // popped the sidebar open and left it there. Instead: leave an open playlist
  3714. // alone, and let a closed one peek open just long enough to show what is playing
  3715. // now — or not at all, when disabled in Advanced settings.
  3716. function peekPlaylistForEpisodeChange() {
  3717. cancelPlaylistPeek();
  3718. var $sidebar = $('#playlist-sidebar');
  3719. if (!$sidebar.hasClass('collapsed')) { return; } // already open — nothing to do
  3720. if (disablePlaylistPeek) { return; }
  3721. if (!currentEpisodes || currentEpisodes.length <= 1) { return; }
  3722. $sidebar.removeClass('collapsed');
  3723. playlistPeekTimer = setTimeout(function () {
  3724. playlistPeekTimer = null;
  3725. $('#playlist-sidebar').addClass('collapsed');
  3726. // The peek is transient — keep a later resize from re-opening it
  3727. playlistUserToggled = true;
  3728. }, PLAYLIST_PEEK_MS);
  3729. }
  3730. // The playlist sidebar eats a lot of width, so it is only opened automatically
  3731. // where there is room for it: a wide (desktop/laptop) viewport, or any device
  3732. // held in landscape. A phone/tablet in portrait starts with it collapsed — the
  3733. // list button in the player top bar still opens it on demand.
  3734. function shouldAutoShowPlaylist() {
  3735. if (!window.matchMedia) { return true; }
  3736. return window.matchMedia('(min-width: 900px), (orientation: landscape)').matches;
  3737. }
  3738. function applyPlaylistVisibility() {
  3739. var hasPlaylist = currentEpisodes && currentEpisodes.length > 1;
  3740. $('#playlist-sidebar').toggleClass('collapsed', !(hasPlaylist && shouldAutoShowPlaylist()));
  3741. }
  3742. function startNextCountdown() {
  3743. var total = 5;
  3744. var remaining = total;
  3745. var $bar = $('#next-countdown-bar');
  3746. var $num = $('#countdown-num');
  3747. $bar.css('transition', 'none').css('width', '100%');
  3748. $num.text(remaining);
  3749. $('#next-countdown').show();
  3750. countdownTimer = setInterval(function () {
  3751. remaining--;
  3752. $num.text(remaining);
  3753. $bar.css('transition', 'width 1s linear').css('width', (remaining / total * 100) + '%');
  3754. if (remaining <= 0) { cancelCountdown(); playOffset(1); }
  3755. }, 1000);
  3756. }
  3757. function cancelCountdown() {
  3758. if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null; }
  3759. $('#next-countdown').hide();
  3760. }
  3761. // ─── Player context menu ──────────────────────────────────────────────────────
  3762. var infoRefreshTimer = null;
  3763. var currentInfoTab = 'props';
  3764. function initContextMenu() {
  3765. var vid = document.getElementById('main-video');
  3766. var $ctx = $('#player-ctx');
  3767. // Right-click on the video container
  3768. $('#video-container').on('contextmenu', function (e) {
  3769. e.preventDefault();
  3770. if (playingIndex < 0) { return; }
  3771. // Update item disabled / active states
  3772. var paused = castMode ? !castIsPlaying : vid.paused;
  3773. $('#ctx-play').toggleClass('ctx-disabled', !paused);
  3774. $('#ctx-pause').toggleClass('ctx-disabled', paused);
  3775. $('#ctx-prev').toggleClass('ctx-disabled', playingIndex <= 0);
  3776. $('#ctx-next').toggleClass('ctx-disabled', playingIndex >= currentEpisodes.length - 1);
  3777. $('#ctx-repeat').toggleClass('ctx-active', repeatSingle)
  3778. .html('<img class="ctx-icon" src="img/icons/'
  3779. + (repeatSingle ? 'repeat_one_white.svg' : 'repeat_white.svg')
  3780. + '" alt="">Repeat: ' + (repeatSingle ? 'On' : 'Off'));
  3781. // Always collapse subtitle submenu on fresh open
  3782. $('#ctx-subtitle-sub').hide();
  3783. closeSettingsPopup();
  3784. closeSubtitlePopup();
  3785. // Position menu, clamp inside container
  3786. var rect = this.getBoundingClientRect();
  3787. var x = e.clientX - rect.left;
  3788. var y = e.clientY - rect.top;
  3789. $ctx.css({ left: x, top: y, display: 'block' });
  3790. var mw = $ctx.outerWidth(), mh = $ctx.outerHeight();
  3791. if (x + mw > rect.width) { $ctx.css('left', Math.max(0, x - mw)); }
  3792. if (y + mh > rect.height) { $ctx.css('top', Math.max(0, y - mh)); }
  3793. showControls();
  3794. });
  3795. // Dismiss on any click outside the menu
  3796. $(document).on('mousedown.ctx', function (e) {
  3797. if (!$(e.target).closest('#player-ctx').length) { $ctx.hide(); }
  3798. });
  3799. // Dismiss on Escape
  3800. $(document).on('keydown.ctx', function (e) {
  3801. if (e.key === 'Escape') { $ctx.hide(); closeVideoInfo(); closeSubtitleSettings(); }
  3802. });
  3803. $('#ctx-play').on('click', function () {
  3804. if (castMode && _castConnected()) {
  3805. _castSend('media.play', {}); castIsPlaying = true;
  3806. $('#play-icon').attr('src', 'img/icons/pause_white.svg');
  3807. } else { playVideo(vid); }
  3808. flashPlayState(true);
  3809. $ctx.hide();
  3810. });
  3811. $('#ctx-pause').on('click', function () {
  3812. if (castMode && _castConnected()) {
  3813. _castSend('media.pause', {}); castIsPlaying = false;
  3814. $('#play-icon').attr('src', 'img/icons/play_white.svg');
  3815. } else { vid.pause(); }
  3816. flashPlayState(false);
  3817. $ctx.hide();
  3818. });
  3819. $('#ctx-prev').on('click', function () { cancelCountdown(); playOffset(-1); $ctx.hide(); });
  3820. $('#ctx-next').on('click', function () { cancelCountdown(); playOffset(1); $ctx.hide(); });
  3821. $('#ctx-repeat').on('click', function () { setRepeatSingle(!repeatSingle); $ctx.hide(); });
  3822. $('#ctx-subtitle-settings').on('click', function () { $ctx.hide(); openSubtitleSettings(); });
  3823. $('#ctx-props').on('click', function () { $ctx.hide(); openVideoInfo('props'); });
  3824. $('#ctx-stats').on('click', function () { $ctx.hide(); openVideoInfo('stats'); });
  3825. }
  3826. // Flash a large play/pause glyph in the centre of the video so the user gets
  3827. // immediate feedback that their click / key press registered.
  3828. function flashPlayState(isPlaying) {
  3829. var $f = $('#play-flash');
  3830. if (!$f.length) { return; }
  3831. $('#play-flash-icon').attr('src',
  3832. isPlaying ? 'img/icons/play_white.svg' : 'img/icons/pause_white.svg');
  3833. $f.removeClass('flash');
  3834. void $f[0].offsetWidth; // force reflow so the animation restarts
  3835. $f.addClass('flash');
  3836. }
  3837. // ─── Playback settings popup (gear button) ────────────────────────────────────
  3838. function setAlwaysShowVolumeBar(on) {
  3839. alwaysShowVolumeBar = !!on;
  3840. localStorage.setItem('movie_always_volume_bar', alwaysShowVolumeBar ? '1' : '0');
  3841. $('body').toggleClass('always-show-volume', alwaysShowVolumeBar);
  3842. $('#set-volbar-seg .set-seg-btn').removeClass('active')
  3843. .filter('[data-volbar="' + (alwaysShowVolumeBar ? 'always' : 'auto') + '"]').addClass('active');
  3844. }
  3845. function setRepeatSingle(on) {
  3846. repeatSingle = !!on;
  3847. localStorage.setItem('movie_repeat_one', repeatSingle ? '1' : '0');
  3848. $('#set-repeat-seg .set-seg-btn').removeClass('active')
  3849. .filter('[data-repeat="' + (repeatSingle ? 'one' : 'off') + '"]').addClass('active');
  3850. }
  3851. // Apply a streaming mode. Changing it mid-playback re-opens the current file on
  3852. // the other transport, resuming where the viewer was.
  3853. function applyStreamMode(mode, reloadCurrent) {
  3854. var previous = getStreamMode();
  3855. setStreamMode(mode);
  3856. $('#set-stream-seg .set-seg-btn').removeClass('active')
  3857. .filter('[data-stream="' + getStreamMode() + '"]').addClass('active');
  3858. if (!reloadCurrent || previous === getStreamMode()) { return; }
  3859. // Warn only when the viewer actively picks a mode this browser cannot play
  3860. warnIfStreamModeUnplayable();
  3861. if (!isTranscodedVideo || playingIndex < 0 || !currentEpisodes[playingIndex]) { return; }
  3862. // Restart the current file on the newly chosen transport, at the same spot.
  3863. // Opening it directly at that offset rather than at zero avoids starting a
  3864. // transcode from the beginning only to abandon it a moment later.
  3865. var resumeAt = effectivePlaybackTime();
  3866. var startAt = resumeAt > 1 ? resumeAt : 0;
  3867. var vid = document.getElementById('main-video');
  3868. var resume = !vid.paused;
  3869. transcodeSeekOffset = startAt;
  3870. if (!attachTranscodeStream(vid, transcodeStreamURL(currentEpisodes[playingIndex].filepath, startAt),
  3871. function (reason) { showToast(reason); },
  3872. function () { settlePlayState(vid, resume); })) {
  3873. showToast('This browser cannot play the HLS stream.');
  3874. }
  3875. }
  3876. function playerVideoElement() { return document.getElementById('main-video'); }
  3877. function currentPlayingFilepath() {
  3878. var ep = playingIndex >= 0 ? currentEpisodes[playingIndex] : null;
  3879. return ep ? ep.filepath : null;
  3880. }
  3881. // Show the quality steps the current file allows, with the one it plays at
  3882. // highlighted. That is the viewer's choice unless the file is smaller than it;
  3883. // under Auto the header says which step Auto is on.
  3884. function renderStreamQuality() {
  3885. var filepath = currentPlayingFilepath();
  3886. var info = filepath ? cachedMediaInfo(filepath) : null;
  3887. var chosen = getStreamQuality();
  3888. var active = (chosen === 'auto' || !filepath) ? chosen : effectiveStreamQuality(filepath);
  3889. $('#set-quality-grid .speed-btn').each(function () {
  3890. var id = String($(this).data('quality'));
  3891. $(this).toggle(streamQualityAvailable(id, info))
  3892. .toggleClass('active', id === active);
  3893. });
  3894. var note = (chosen === 'auto' && filepath) ? streamQualityStep(effectiveStreamQuality(filepath)) : null;
  3895. $('#set-quality-note').text(note ? note.label : '');
  3896. }
  3897. // Apply a quality step. Changing it mid-playback re-opens the current file at
  3898. // the new step, resuming where the viewer was.
  3899. function applyStreamQuality(quality, reloadCurrent) {
  3900. var filepath = currentPlayingFilepath();
  3901. var previous = filepath ? effectiveStreamQuality(filepath) : getStreamQuality();
  3902. // Auto starts from whatever is playing now rather than reloading straight away
  3903. if (quality === 'auto' && filepath) { setAutoQualityStep(filepath, previous); }
  3904. setStreamQuality(quality);
  3905. renderStreamQuality();
  3906. if (!reloadCurrent || !filepath || previous === effectiveStreamQuality(filepath)) { return; }
  3907. // The receiver picks the new step up with the next file it is sent
  3908. if (castMode && _castConnected()) { return; }
  3909. reopenCurrentStream(!document.getElementById('main-video').paused);
  3910. }
  3911. // Finish re-opening a stream in the state the viewer left it. The pause()
  3912. // matters even on a paused element: it stops a newly set source from starting
  3913. // by itself, which an autoplay attribute would otherwise do.
  3914. function settlePlayState(vid, resume) {
  3915. if (resume) { playVideo(vid); } else { vid.pause(); }
  3916. }
  3917. // Re-open the current file at the current position after a quality change,
  3918. // playing again only when `resume` says it was playing. Unlike a
  3919. // streaming-mode change this can cross between direct playback and a
  3920. // transcode: dropping below the source size always transcodes, and returning
  3921. // to Original plays the file as-is again when the browser can.
  3922. function reopenCurrentStream(resume) {
  3923. var index = playingIndex;
  3924. var ep = currentEpisodes[index];
  3925. var vid = document.getElementById('main-video');
  3926. var ext = ep.ext ? ep.ext.toLowerCase().replace(/^\./, '') : '';
  3927. var resumeAt = effectivePlaybackTime();
  3928. var startAt = resumeAt > 1 ? resumeAt : 0;
  3929. // A direct stream knows its own length; a transcode is told it separately
  3930. var knownDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
  3931. showSeekFreeze();
  3932. setSubtitleSeekFloor(startAt);
  3933. resolveDirectPlay(ep.filepath, ext, function (directPlay) {
  3934. if (playingIndex !== index) { return; } // episode changed meanwhile
  3935. clearDirectPlaybackWatch(vid);
  3936. detachTranscodeStream(vid);
  3937. $(vid).off('loadedmetadata.quality'); // from a switch made just before
  3938. isTranscodedVideo = !directPlay;
  3939. if (directPlay) {
  3940. transcodeSeekOffset = 0;
  3941. vid.src = MEDIA_API + '?file=' + encodeURIComponent(ep.filepath);
  3942. $(vid).one('loadedmetadata.quality', function () { vid.currentTime = startAt; });
  3943. onDirectPlaybackFailure(vid, function () {
  3944. if (playingIndex !== index) { return; }
  3945. showToast('This browser cannot decode that file — switching to a transcode');
  3946. beginEpisodeStream(ep, index, false);
  3947. });
  3948. settlePlayState(vid, resume);
  3949. return;
  3950. }
  3951. transcodeSeekOffset = startAt;
  3952. if (knownDuration > 0 && isFinite(knownDuration)) {
  3953. transcodeDuration = knownDuration;
  3954. } else {
  3955. fetch(ao_root + 'media/duration/?file=' + encodeURIComponent(ep.filepath))
  3956. .then(function (r) { return r.json(); })
  3957. .then(function (data) {
  3958. if (data.duration > 0 && playingIndex === index) { transcodeDuration = data.duration; }
  3959. }).catch(function () {});
  3960. }
  3961. if (!attachTranscodeStream(vid, transcodeStreamURL(ep.filepath, startAt),
  3962. function (reason) { hideSeekFreeze(); showToast(reason); },
  3963. function () { settlePlayState(vid, resume); })) {
  3964. hideSeekFreeze();
  3965. showToast('This browser cannot play the transcoded stream. Switch streaming mode to MP4 in settings.');
  3966. }
  3967. });
  3968. }
  3969. // Surface the two streaming modes that cannot work on a given browser. Anything
  3970. // that is simply working says nothing at all.
  3971. function warnIfStreamModeUnplayable() {
  3972. var mode = getStreamMode();
  3973. if (mode === 'mp4' && isWebKitClient()) {
  3974. showToast('This browser cannot play the MP4 stream. Use Auto or HLS.');
  3975. } else if (mode === 'hls' && !hlsPlaybackSupported(playerVideoElement())) {
  3976. showToast('This browser has no HLS support (needs Media Source Extensions).');
  3977. }
  3978. }
  3979. function setPlaybackSpeed(rate) {
  3980. playbackSpeed = parseFloat(rate) || 1;
  3981. document.getElementById('main-video').playbackRate = playbackSpeed;
  3982. localStorage.setItem('movie_playback_speed', String(playbackSpeed));
  3983. $('#set-speed-grid .speed-btn').removeClass('active')
  3984. .filter('[data-speed="' + playbackSpeed + '"]').addClass('active');
  3985. }
  3986. // Snap an arbitrary stored rate onto the nearest preset, so the popup always
  3987. // has exactly one button highlighted. Needed because an earlier build persisted
  3988. // free-form rates from a drag slider.
  3989. function nearestPlaybackSpeed(rate) {
  3990. var value = parseFloat(rate);
  3991. if (!value || value <= 0) { return 1; }
  3992. return PLAYBACK_SPEEDS.reduce(function (best, preset) {
  3993. return Math.abs(preset - value) < Math.abs(best - value) ? preset : best;
  3994. }, PLAYBACK_SPEEDS[0]);
  3995. }
  3996. // Cap a bottom-anchored popup's height so it never runs past the top edge of
  3997. // the player (it only ever opens upward) — the popup's own scrollbar takes
  3998. // over for whatever doesn't fit.
  3999. function clampBottomPopupHeight($popup) {
  4000. var container = document.getElementById('video-container');
  4001. if (!container) { return; }
  4002. var margin = 10;
  4003. var containerRect = container.getBoundingClientRect();
  4004. var popupRect = $popup[0].getBoundingClientRect();
  4005. var available = popupRect.bottom - containerRect.top - margin;
  4006. $popup.css('max-height', Math.max(120, available) + 'px');
  4007. }
  4008. function openSettingsPopup() {
  4009. setRepeatSingle(repeatSingle);
  4010. setPlaybackSpeed(playbackSpeed);
  4011. setAlwaysShowVolumeBar(alwaysShowVolumeBar);
  4012. applyStreamMode(getStreamMode(), false);
  4013. renderStreamQuality();
  4014. $('#player-ctx').hide();
  4015. closeSubtitlePopup();
  4016. $('#settings-popup').addClass('active');
  4017. clampBottomPopupHeight($('#settings-popup'));
  4018. showControls();
  4019. }
  4020. function closeSettingsPopup() { $('#settings-popup').removeClass('active'); }
  4021. function toggleSettingsPopup() {
  4022. if ($('#settings-popup').hasClass('active')) { closeSettingsPopup(); }
  4023. else { openSettingsPopup(); }
  4024. }
  4025. // ── Subtitle popup (dedicated CC button) ────────────────────────────────────
  4026. function openSubtitlePopup() {
  4027. updateSubtitleSubmenu();
  4028. $('#player-ctx').hide();
  4029. closeSettingsPopup();
  4030. $('#subtitle-popup').addClass('active');
  4031. clampBottomPopupHeight($('#subtitle-popup'));
  4032. showControls();
  4033. }
  4034. function closeSubtitlePopup() { $('#subtitle-popup').removeClass('active'); }
  4035. function toggleSubtitlePopup() {
  4036. if ($('#subtitle-popup').hasClass('active')) { closeSubtitlePopup(); }
  4037. else { openSubtitlePopup(); }
  4038. }
  4039. function initSubtitlePopup() {
  4040. $('#ctrl-subtitle').on('click', function (e) {
  4041. e.stopPropagation();
  4042. toggleSubtitlePopup();
  4043. });
  4044. $(document).on('mousedown.subpop', function (e) {
  4045. if (!$(e.target).closest('#subtitle-popup, #ctrl-subtitle').length) {
  4046. closeSubtitlePopup();
  4047. }
  4048. });
  4049. $('#sub-pop-disable').on('click', function () {
  4050. activeSubtitleIndex = -1;
  4051. stopAssTrack();
  4052. $('#subtitle-display').hide();
  4053. updateSubtitleSubmenu();
  4054. closeSubtitlePopup();
  4055. });
  4056. $('#sub-pop-load').on('click', function () { closeSubtitlePopup(); pickSubtitleFile(); });
  4057. $('#sub-pop-settings').on('click', function () { closeSubtitlePopup(); openSubtitleSettings(); });
  4058. }
  4059. function initSettingsPopup() {
  4060. $('#ctrl-settings').on('click', function (e) {
  4061. e.stopPropagation();
  4062. toggleSettingsPopup();
  4063. });
  4064. // Dismiss when clicking anywhere outside the popup or its button
  4065. $(document).on('mousedown.setpop', function (e) {
  4066. if (!$(e.target).closest('#settings-popup, #ctrl-settings').length) {
  4067. closeSettingsPopup();
  4068. }
  4069. });
  4070. $('#set-repeat-seg').on('click', '.set-seg-btn', function () {
  4071. setRepeatSingle($(this).data('repeat') === 'one');
  4072. });
  4073. $('#set-speed-grid').on('click', '.speed-btn', function () {
  4074. setPlaybackSpeed($(this).data('speed'));
  4075. });
  4076. $('#set-volbar-seg').on('click', '.set-seg-btn', function () {
  4077. setAlwaysShowVolumeBar($(this).data('volbar') === 'always');
  4078. });
  4079. $('#set-stream-seg').on('click', '.set-seg-btn', function () {
  4080. applyStreamMode(String($(this).data('stream')), true);
  4081. });
  4082. $('#set-quality-grid').on('click', '.speed-btn', function () {
  4083. applyStreamQuality(String($(this).data('quality')), true);
  4084. });
  4085. $('#set-video-props').on('click', function () { closeSettingsPopup(); openVideoInfo('props'); });
  4086. $('#set-advanced').on('click', function () { closeSettingsPopup(); openAdvancedSettings(); });
  4087. $('#adv-no-playlist-peek').on('change', function () {
  4088. disablePlaylistPeek = $(this).is(':checked');
  4089. localStorage.setItem('movie_no_playlist_peek', disablePlaylistPeek ? '1' : '0');
  4090. if (disablePlaylistPeek) { cancelPlaylistPeek(); }
  4091. });
  4092. // Apply persisted values to the video element
  4093. setRepeatSingle(repeatSingle);
  4094. setPlaybackSpeed(playbackSpeed);
  4095. setAlwaysShowVolumeBar(alwaysShowVolumeBar);
  4096. applyStreamMode(getStreamMode(), false);
  4097. renderStreamQuality();
  4098. // Auto quality only ever moves while playing, so it always resumes
  4099. new AutoQualityController(document.getElementById('main-video'), {
  4100. filepath: function () {
  4101. return (castMode && _castConnected()) ? null : currentPlayingFilepath();
  4102. },
  4103. isTranscoded: function () { return isTranscodedVideo; },
  4104. onSwitch: function () { renderStreamQuality(); reopenCurrentStream(true); }
  4105. });
  4106. // Changing episode — or a transcode seek — replaces the media source, which
  4107. // resets playbackRate. Reapply the chosen speed every time media loads.
  4108. $('#main-video').on('loadedmetadata.speed', function () {
  4109. this.playbackRate = playbackSpeed;
  4110. });
  4111. }
  4112. function openVideoInfo(tab) {
  4113. currentInfoTab = tab || 'props';
  4114. closeAdvancedSettings();
  4115. $('#video-info-modal').show();
  4116. $('.info-tab').removeClass('active').eq(currentInfoTab === 'props' ? 0 : 1).addClass('active');
  4117. $('#video-info-title').text(currentInfoTab === 'props' ? 'Video Properties' : 'Streaming Stats');
  4118. renderInfoContent();
  4119. if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
  4120. if (currentInfoTab === 'stats') {
  4121. infoRefreshTimer = setInterval(renderInfoContent, 1000);
  4122. }
  4123. }
  4124. function closeVideoInfo() {
  4125. $('#video-info-modal').hide();
  4126. if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
  4127. }
  4128. function openAdvancedSettings() {
  4129. closeVideoInfo();
  4130. $('#adv-no-playlist-peek').prop('checked', disablePlaylistPeek);
  4131. $('#adv-settings-modal').show();
  4132. }
  4133. function closeAdvancedSettings() { $('#adv-settings-modal').hide(); }
  4134. function showInfoTab(tab) {
  4135. currentInfoTab = tab;
  4136. $('.info-tab').removeClass('active').eq(tab === 'props' ? 0 : 1).addClass('active');
  4137. $('#video-info-title').text(tab === 'props' ? 'Video Properties' : 'Streaming Stats');
  4138. if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
  4139. if (tab === 'stats') { infoRefreshTimer = setInterval(renderInfoContent, 1000); }
  4140. renderInfoContent();
  4141. }
  4142. function infoRow(label, value) {
  4143. return '<div class="info-row"><span class="info-label">' + escapeHtml(String(label)) + '</span>'
  4144. + '<span class="info-value">' + escapeHtml(String(value)) + '</span></div>';
  4145. }
  4146. function renderInfoContent() {
  4147. var vid = document.getElementById('main-video');
  4148. var ep = (playingIndex >= 0 && currentEpisodes[playingIndex]) ? currentEpisodes[playingIndex] : null;
  4149. var html = '';
  4150. if (currentInfoTab === 'props') {
  4151. html += infoRow('Title', ep ? ep.name : '–');
  4152. html += infoRow('Resolution', (vid.videoWidth && vid.videoHeight)
  4153. ? vid.videoWidth + ' × ' + vid.videoHeight : '–');
  4154. var infoDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
  4155. var infoPosition = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
  4156. html += infoRow('Duration', infoDuration ? formatTime(infoDuration) : '–');
  4157. html += infoRow('Position', infoPosition ? formatTime(infoPosition) : '–');
  4158. html += infoRow('Playback speed', vid.playbackRate + '×');
  4159. html += infoRow('Volume', vid.muted ? 'Muted' : Math.round(vid.volume * 100) + '%');
  4160. if (ep) { html += infoRow('File path', ep.filepath || '–'); }
  4161. } else {
  4162. var rsLabels = ['No info', 'Metadata only', 'Have current data', 'Have future data', 'Enough data'];
  4163. var nsLabels = ['Empty', 'Idle', 'Loading', 'No source'];
  4164. html += infoRow('Ready state', rsLabels[vid.readyState] || vid.readyState);
  4165. html += infoRow('Network state', nsLabels[vid.networkState] || vid.networkState);
  4166. // Buffer ahead
  4167. var bufEnd = 0;
  4168. if (vid.buffered && vid.buffered.length > 0) {
  4169. for (var i = 0; i < vid.buffered.length; i++) {
  4170. if (vid.buffered.start(i) <= vid.currentTime + 0.1) {
  4171. bufEnd = Math.max(bufEnd, vid.buffered.end(i));
  4172. }
  4173. }
  4174. }
  4175. html += infoRow('Buffer ahead', Math.max(0, bufEnd - vid.currentTime).toFixed(1) + 's');
  4176. html += infoRow('Total buffered', vid.buffered.length > 0
  4177. ? formatTime(vid.buffered.end(vid.buffered.length - 1)) : '–');
  4178. if (vid.getVideoPlaybackQuality) {
  4179. var q = vid.getVideoPlaybackQuality();
  4180. html += infoRow('Frames decoded', q.totalVideoFrames || 0);
  4181. html += infoRow('Frames dropped', q.droppedVideoFrames || 0);
  4182. }
  4183. html += infoRow('Stalled / ended', vid.ended ? 'Ended' : (vid.readyState < 3 ? 'Yes' : 'No'));
  4184. }
  4185. $('#video-info-body').html(html);
  4186. }
  4187. function formatTime(s) {
  4188. if (isNaN(s)) { return '0:00'; }
  4189. var h = Math.floor(s / 3600);
  4190. var m = Math.floor((s % 3600) / 60);
  4191. var sec = Math.floor(s % 60);
  4192. var parts = [];
  4193. if (h > 0) { parts.push(h); }
  4194. parts.push(m);
  4195. parts.push(sec < 10 ? '0' + sec : sec);
  4196. return parts.join(':');
  4197. }
  4198. // ─── Keyboard / TV-remote navigation ─────────────────────────────────────────
  4199. function initKeyboard() {
  4200. $(document).on('keydown', function (e) {
  4201. var activeView = $('.view.active').attr('id');
  4202. // ── Player shortcuts ──────────────────────────────────────────────────
  4203. if (activeView === 'view-player') {
  4204. var vid = document.getElementById('main-video');
  4205. switch (e.key) {
  4206. case ' ':
  4207. case 'k':
  4208. e.preventDefault(); togglePlay(); showControls(); break;
  4209. case 'ArrowRight':
  4210. e.preventDefault();
  4211. if (castMode && _castConnected()) {
  4212. _castSend('media.seekrel', { delta: 10 });
  4213. castCurrentTime = Math.min(castDuration, castCurrentTime + 10);
  4214. _castUpdateProgressUI();
  4215. } else if (isTranscodedVideo && playingIndex >= 0 && currentEpisodes[playingIndex]) {
  4216. transcodeSeekTo(effectivePlaybackTime() + 10);
  4217. } else { vid.currentTime = Math.min(vid.duration || 0, vid.currentTime + 10); }
  4218. showControls(); break;
  4219. case 'ArrowLeft':
  4220. e.preventDefault();
  4221. if (castMode && _castConnected()) {
  4222. _castSend('media.seekrel', { delta: -10 });
  4223. castCurrentTime = Math.max(0, castCurrentTime - 10);
  4224. _castUpdateProgressUI();
  4225. } else if (isTranscodedVideo && playingIndex >= 0 && currentEpisodes[playingIndex]) {
  4226. transcodeSeekTo(effectivePlaybackTime() - 10);
  4227. } else { vid.currentTime = Math.max(0, vid.currentTime - 10); }
  4228. showControls(); break;
  4229. case 'ArrowUp':
  4230. e.preventDefault(); vid.volume = Math.min(1, vid.volume + 0.1);
  4231. if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
  4232. showControls(); break;
  4233. case 'ArrowDown':
  4234. e.preventDefault(); vid.volume = Math.max(0, vid.volume - 0.1);
  4235. if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
  4236. showControls(); break;
  4237. case 'f':
  4238. case 'F':
  4239. e.preventDefault(); toggleFullscreen(); break;
  4240. case 'm':
  4241. case 'M':
  4242. e.preventDefault(); vid.muted = !vid.muted;
  4243. if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
  4244. break;
  4245. case 'l':
  4246. case 'L':
  4247. e.preventDefault(); toggleSidebar(); break;
  4248. case 's':
  4249. case 'S':
  4250. e.preventDefault(); toggleSettingsPopup(); break;
  4251. case 'r':
  4252. case 'R':
  4253. e.preventDefault();
  4254. setRepeatSingle(!repeatSingle);
  4255. showToast('Repeat: ' + (repeatSingle ? 'On' : 'Off')); break;
  4256. case 'n':
  4257. e.preventDefault(); playOffset(1); break;
  4258. case 'p':
  4259. e.preventDefault(); playOffset(-1); break;
  4260. case 'Escape':
  4261. e.preventDefault();
  4262. // Escape dismisses an open overlay first; only closes the
  4263. // player once nothing is layered on top of it.
  4264. if ($('#settings-popup').hasClass('active') ||
  4265. $('#subtitle-popup').hasClass('active') ||
  4266. $('#player-ctx').is(':visible') ||
  4267. $('#video-info-modal').is(':visible') ||
  4268. $('#adv-settings-modal').is(':visible') ||
  4269. $('#subtitle-settings-modal').is(':visible')) {
  4270. closeSettingsPopup();
  4271. closeSubtitlePopup();
  4272. $('#player-ctx').hide();
  4273. closeVideoInfo();
  4274. closeAdvancedSettings();
  4275. closeSubtitleSettings();
  4276. } else {
  4277. closePlayer();
  4278. }
  4279. break;
  4280. case 'MediaPlayPause':
  4281. e.preventDefault(); togglePlay(); break;
  4282. case 'MediaTrackNext':
  4283. e.preventDefault(); playOffset(1); break;
  4284. case 'MediaTrackPrevious':
  4285. e.preventDefault(); playOffset(-1); break;
  4286. }
  4287. return;
  4288. }
  4289. // ── Grid / detail navigation (TV remote) ──────────────────────────────
  4290. if (e.key === 'Escape') {
  4291. e.preventDefault();
  4292. if (activeView === 'view-detail') { showLibrary(); }
  4293. return;
  4294. }
  4295. if (['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Enter'].indexOf(e.key) === -1) { return; }
  4296. e.preventDefault();
  4297. focusMode = true;
  4298. var $focusables = $('.view.active [tabindex="0"]:visible');
  4299. if ($focusables.length === 0) { return; }
  4300. var $cur = $(document.activeElement);
  4301. var curIdx = $focusables.index($cur);
  4302. if (curIdx < 0) {
  4303. // Nothing focused yet – focus first element
  4304. $focusables.first().focus();
  4305. return;
  4306. }
  4307. if (e.key === 'Enter') {
  4308. $cur.trigger('click');
  4309. return;
  4310. }
  4311. // Compute next focus index based on grid layout
  4312. var nextIdx = computeNextFocus($focusables, curIdx, e.key);
  4313. if (nextIdx >= 0 && nextIdx < $focusables.length) {
  4314. $focusables.eq(nextIdx).focus();
  4315. $focusables.eq(nextIdx)[0].scrollIntoView({ block: 'nearest', inline: 'nearest' });
  4316. }
  4317. });
  4318. }
  4319. function computeNextFocus($els, curIdx, key) {
  4320. if (key === 'ArrowDown') { return Math.min($els.length - 1, curIdx + 1); }
  4321. if (key === 'ArrowUp') { return Math.max(0, curIdx - 1); }
  4322. // For left/right in a grid, figure out how many columns there are
  4323. var $cur = $els.eq(curIdx);
  4324. var $parent = $cur.parent();
  4325. if ($parent.hasClass('album-grid')) {
  4326. var colCount = Math.round($parent.width() / ($cur.outerWidth(true) || 1)) || 1;
  4327. if (key === 'ArrowRight') { return Math.min($els.length - 1, curIdx + 1); }
  4328. if (key === 'ArrowLeft') { return Math.max(0, curIdx - 1); }
  4329. }
  4330. if (key === 'ArrowRight') { return Math.min($els.length - 1, curIdx + 1); }
  4331. if (key === 'ArrowLeft') { return Math.max(0, curIdx - 1); }
  4332. return curIdx;
  4333. }
  4334. // ─── Search ───────────────────────────────────────────────────────────────────
  4335. function initSearch() {
  4336. $('#search-input').on('input', function () {
  4337. var q = $(this).val().trim().toLowerCase();
  4338. if (q.length === 0) {
  4339. renderLibrary(library);
  4340. return;
  4341. }
  4342. var filtered = library.filter(function (a) {
  4343. return a.name.toLowerCase().indexOf(q) > -1;
  4344. });
  4345. renderLibrary(filtered);
  4346. });
  4347. // Prevent keyboard nav from hijacking search input
  4348. $('#search-input').on('keydown', function (e) {
  4349. e.stopPropagation();
  4350. if (e.key === 'Escape') { $(this).val(''); renderLibrary(library); $(this).blur(); }
  4351. });
  4352. }
  4353. // ─── Utilities ────────────────────────────────────────────────────────────────
  4354. function escapeHtml(str) {
  4355. if (!str) { return ''; }
  4356. return String(str)
  4357. .replace(/&/g, '&amp;')
  4358. .replace(/</g, '&lt;')
  4359. .replace(/>/g, '&gt;')
  4360. .replace(/"/g, '&quot;');
  4361. }
  4362. function escapeAttr(str) { return escapeHtml(str); }
  4363. // ─── Subtitle settings ────────────────────────────────────────────────────────
  4364. var subtitleSettings = { position: 'bottom', size: 22, font: 'system-ui, sans-serif', color: '#ffffff' };
  4365. function loadSubtitleSettings() {
  4366. try {
  4367. var s = JSON.parse(localStorage.getItem('movie_subtitle_settings') || 'null');
  4368. if (s) { Object.assign(subtitleSettings, s); }
  4369. } catch (e) {}
  4370. }
  4371. function saveSubtitleSettings() {
  4372. localStorage.setItem('movie_subtitle_settings', JSON.stringify(subtitleSettings));
  4373. }
  4374. function applySubtitleSettings() {
  4375. var s = subtitleSettings;
  4376. var $d = $('#subtitle-display');
  4377. $d.css({
  4378. 'font-size': s.size + 'px',
  4379. 'font-family': s.font,
  4380. 'color': s.color,
  4381. 'bottom': s.position === 'bottom' ? '72px' : 'auto',
  4382. 'top': s.position === 'top' ? '72px' : 'auto',
  4383. 'transform': 'translateX(-50%)'
  4384. });
  4385. }
  4386. function syncSettingsPreview() {
  4387. var s = subtitleSettings;
  4388. $('#sset-preview').css({
  4389. 'font-size': s.size + 'px',
  4390. 'font-family': s.font,
  4391. 'color': s.color,
  4392. '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)'
  4393. });
  4394. }
  4395. function openSubtitleSettings() {
  4396. var s = subtitleSettings;
  4397. // Sync all controls to current state
  4398. $('.sset-seg-btn').removeClass('active')
  4399. .filter('[data-val="' + s.position + '"]').addClass('active');
  4400. $('#sset-size').val(s.size);
  4401. $('#sset-size-val').text(s.size + 'px');
  4402. $('#sset-font').val(s.font);
  4403. var swatchMatch = $('.sset-color[data-color="' + s.color.toLowerCase() + '"]');
  4404. $('.sset-color, #sset-color-custom').removeClass('active');
  4405. if (swatchMatch.length) { swatchMatch.addClass('active'); }
  4406. else { $('#sset-color-custom').addClass('active'); }
  4407. $('#sset-color-custom').val(s.color);
  4408. syncSettingsPreview();
  4409. $('#subtitle-settings-modal').show();
  4410. }
  4411. function closeSubtitleSettings() {
  4412. $('#subtitle-settings-modal').hide();
  4413. }
  4414. function initSubtitleSettings() {
  4415. loadSubtitleSettings();
  4416. applySubtitleSettings();
  4417. $('#sset-close').on('click', closeSubtitleSettings);
  4418. // Position
  4419. $(document).on('click', '.sset-seg-btn', function () {
  4420. subtitleSettings.position = $(this).data('val');
  4421. $('.sset-seg-btn').removeClass('active');
  4422. $(this).addClass('active');
  4423. applySubtitleSettings();
  4424. saveSubtitleSettings();
  4425. });
  4426. // Size
  4427. $('#sset-size').on('input', function () {
  4428. subtitleSettings.size = parseInt($(this).val(), 10);
  4429. $('#sset-size-val').text(subtitleSettings.size + 'px');
  4430. applySubtitleSettings();
  4431. syncSettingsPreview();
  4432. saveSubtitleSettings();
  4433. });
  4434. // Font
  4435. $('#sset-font').on('change', function () {
  4436. subtitleSettings.font = $(this).val();
  4437. ensureEmbeddedFontLoaded(subtitleSettings.font); // no-op for built-in fonts
  4438. applySubtitleSettings();
  4439. syncSettingsPreview();
  4440. saveSubtitleSettings();
  4441. });
  4442. // Preset color swatches
  4443. $(document).on('click', '.sset-color', function () {
  4444. subtitleSettings.color = $(this).data('color');
  4445. $('.sset-color, #sset-color-custom').removeClass('active');
  4446. $(this).addClass('active');
  4447. $('#sset-color-custom').val(subtitleSettings.color);
  4448. applySubtitleSettings();
  4449. syncSettingsPreview();
  4450. saveSubtitleSettings();
  4451. });
  4452. // Custom color picker
  4453. $('#sset-color-custom').on('input', function () {
  4454. subtitleSettings.color = $(this).val();
  4455. $('.sset-color').removeClass('active');
  4456. $('#sset-color-custom').addClass('active');
  4457. applySubtitleSettings();
  4458. syncSettingsPreview();
  4459. saveSubtitleSettings();
  4460. });
  4461. }
  4462. // ─── Subtitle ─────────────────────────────────────────────────────────────────
  4463. var loadedSubtitleFiles = []; // [{path, name, cues:[{start,end,text}]}]
  4464. var activeSubtitleIndex = -1; // -1 = disabled
  4465. // Window-scoped callback required by ao_module file selector.
  4466. // The selector always delivers [{filename, filepath}, …]; handle gracefully.
  4467. window.movieOnSubtitleFile = function (raw) {
  4468. console.log('[subtitle] callback fired, raw value:', raw);
  4469. // Unwrap array
  4470. var entry = Array.isArray(raw) ? raw[0] : raw;
  4471. console.log('[subtitle] unwrapped entry:', entry);
  4472. // Accept either a plain object {filename, filepath} or a bare string path
  4473. var filePath = (entry && typeof entry === 'object') ? entry.filepath : entry;
  4474. console.log('[subtitle] resolved filePath:', filePath);
  4475. if (!filePath || typeof filePath !== 'string') {
  4476. console.warn('[subtitle] unexpected callback payload — aborting', raw);
  4477. return;
  4478. }
  4479. var url = MEDIA_API + '?file=' + encodeURIComponent(filePath);
  4480. console.log('[subtitle] fetching:', url);
  4481. $.ajax({
  4482. url: url,
  4483. dataType: 'text',
  4484. success: function (content) {
  4485. console.log('[subtitle] file fetched, length:', content.length);
  4486. var name = filePath.replace(/\\/g, '/').split('/').pop();
  4487. var cues = parseSrt(content);
  4488. console.log('[subtitle] parsed cues:', cues.length);
  4489. var existing = -1;
  4490. loadedSubtitleFiles.forEach(function (sf, i) {
  4491. if (sf.path === filePath) { existing = i; }
  4492. });
  4493. if (existing >= 0) {
  4494. loadedSubtitleFiles[existing].cues = cues;
  4495. activeSubtitleIndex = existing;
  4496. } else {
  4497. loadedSubtitleFiles.push({ path: filePath, name: name, cues: cues });
  4498. activeSubtitleIndex = loadedSubtitleFiles.length - 1;
  4499. }
  4500. showToast('Subtitle loaded: ' + name);
  4501. applyActiveSubtitle(); // a sidecar file replaces any styled track
  4502. updateSubtitleSubmenu();
  4503. },
  4504. error: function (xhr, status, err) {
  4505. console.error('[subtitle] fetch failed:', status, err, url);
  4506. showToast('Failed to load subtitle file');
  4507. }
  4508. });
  4509. };
  4510. function parseSrtTime(t) {
  4511. var m = t.match(/(\d+):(\d+):(\d+)[,.](\d+)/);
  4512. if (!m) { return 0; }
  4513. return parseInt(m[1]) * 3600 + parseInt(m[2]) * 60 + parseInt(m[3]) + parseInt(m[4]) / 1000;
  4514. }
  4515. function parseSrt(content) {
  4516. var cues = [];
  4517. var blocks = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim().split(/\n\n+/);
  4518. blocks.forEach(function (block) {
  4519. var lines = block.split('\n');
  4520. var tcIdx = -1;
  4521. for (var i = 0; i < lines.length; i++) {
  4522. if (lines[i].indexOf('-->') !== -1) { tcIdx = i; break; }
  4523. }
  4524. if (tcIdx < 0) { return; }
  4525. var parts = lines[tcIdx].split('-->');
  4526. if (parts.length < 2) { return; }
  4527. var start = parseSrtTime(parts[0].trim());
  4528. var end = parseSrtTime(parts[1].trim().split(' ')[0]);
  4529. // Strip inline SRT tags like <b>, <i>, <u>, <font>, plus any ASS
  4530. // override blocks such as {\an8} or {\pos(x,y)}. ffmpeg's ASS-to-SubRip
  4531. // conversion leaves positioning tags like those behind, so without this
  4532. // they would be shown to the viewer as literal text.
  4533. var text = lines.slice(tcIdx + 1).join('\n').trim()
  4534. .replace(/<[^>]+>/g, '')
  4535. .replace(/\{\\[^}]*\}/g, '')
  4536. .trim();
  4537. if (text) { cues.push({ start: start, end: end, text: text }); }
  4538. });
  4539. return cues;
  4540. }
  4541. function updateSubtitleDisplay() {
  4542. // Styled tracks are drawn by the ASS renderer on its own frame loop
  4543. if (assActive) { $('#subtitle-display').hide(); return; }
  4544. if (activeSubtitleIndex < 0 || !loadedSubtitleFiles[activeSubtitleIndex]) {
  4545. $('#subtitle-display').hide();
  4546. return;
  4547. }
  4548. var currentTime = document.getElementById('main-video').currentTime;
  4549. var cues = loadedSubtitleFiles[activeSubtitleIndex].cues;
  4550. var found = null;
  4551. for (var i = 0; i < cues.length; i++) {
  4552. if (cues[i].start < subtitleSeekFloor) { continue; } // in flight when we landed
  4553. if (currentTime >= cues[i].start && currentTime <= cues[i].end) {
  4554. found = cues[i]; break;
  4555. }
  4556. }
  4557. if (found) {
  4558. $('#subtitle-display').html(escapeHtml(found.text).replace(/\n/g, '<br>')).show();
  4559. } else {
  4560. $('#subtitle-display').hide();
  4561. }
  4562. }
  4563. // ─── Embedded subtitle tracks and fonts ───────────────────────────────────────
  4564. // MKV releases usually mux their subtitles (and the fonts they were typeset in)
  4565. // into the container rather than shipping sidecar files. The server lists them
  4566. // and extracts on demand; tracks are converted to SubRip, which keeps the text
  4567. // and timing but drops ASS styling, positioning and karaoke.
  4568. var embeddedSubtitles = []; // [{index, codec, language, title, forced, textual}]
  4569. var embeddedFonts = []; // [{index, filename, mimetype}]
  4570. var embeddedMediaPath = null; // file the two lists above describe
  4571. var embeddedProbeToken = 0; // invalidates in-flight probes on episode change
  4572. var embeddedFontFaces = []; // FontFace objects registered for this video
  4573. var embeddedFontsLoaded = {}; // family name -> already fetched
  4574. function resetEmbeddedTracks() {
  4575. embeddedProbeToken++;
  4576. stopAssTrack();
  4577. embeddedSubtitles = [];
  4578. embeddedFonts = [];
  4579. embeddedMediaPath = null;
  4580. // Font families are keyed by attachment ordinal, which means the same name
  4581. // refers to a different font in the next video — drop the old faces.
  4582. embeddedFontFaces.forEach(function (face) {
  4583. try { document.fonts.delete(face); } catch (e) {}
  4584. });
  4585. embeddedFontFaces = [];
  4586. embeddedFontsLoaded = {};
  4587. }
  4588. function loadEmbeddedTrackList(filepath) {
  4589. resetEmbeddedTracks();
  4590. if (!filepath) { return; }
  4591. embeddedMediaPath = filepath;
  4592. var token = embeddedProbeToken;
  4593. fetch(SUBTITLE_API + '?file=' + encodeURIComponent(filepath))
  4594. .then(function (r) { return r.json(); })
  4595. .then(function (info) {
  4596. if (token !== embeddedProbeToken) { return; } // episode changed
  4597. if (!info || info.error) { return; }
  4598. embeddedSubtitles = info.subtitles || [];
  4599. embeddedFonts = info.fonts || [];
  4600. updateSubtitleSubmenu();
  4601. refreshEmbeddedFontOptions();
  4602. })
  4603. .catch(function () {}); // embedded tracks are a bonus — fail quietly
  4604. }
  4605. function embeddedTrackLabel(track, position) {
  4606. var label = track.title || '';
  4607. if (!label) { label = 'Track ' + (position + 1); }
  4608. if (track.language) { label += ' [' + track.language + ']'; }
  4609. if (track.forced) { label += ' (forced)'; }
  4610. if (!track.textual) { label += ' — image based'; }
  4611. return label;
  4612. }
  4613. // Extraction has to scan the whole container, so it takes a few seconds on a
  4614. // large file. Results are kept in loadedSubtitleFiles, making reselection free.
  4615. function selectEmbeddedSubtitle(track, position) {
  4616. if (!track.textual) {
  4617. showToast('That track is image based and cannot be displayed');
  4618. return;
  4619. }
  4620. var cacheKey = 'embedded#' + track.index + '@' + embeddedMediaPath;
  4621. for (var i = 0; i < loadedSubtitleFiles.length; i++) {
  4622. if (loadedSubtitleFiles[i].path === cacheKey) {
  4623. activeSubtitleIndex = i;
  4624. applyActiveSubtitle();
  4625. updateSubtitleSubmenu();
  4626. return;
  4627. }
  4628. }
  4629. // ASS/SSA is fetched in its native form so the styling survives; everything
  4630. // else comes through as SubRip for the plain renderer.
  4631. var styled = /^(ass|ssa)$/i.test(track.codec) && typeof ASS !== 'undefined';
  4632. var mediaPath = embeddedMediaPath;
  4633. var url = SUBTITLE_API + '?file=' + encodeURIComponent(mediaPath) + '&track=' + track.index
  4634. + (styled ? '&format=ass' : '');
  4635. showToast('Extracting subtitle track…');
  4636. $.ajax({
  4637. url: url,
  4638. dataType: 'text',
  4639. success: function (content) {
  4640. if (mediaPath !== embeddedMediaPath) { return; } // episode changed
  4641. if (styled) {
  4642. var parsed = ASS.parse(content);
  4643. if (!parsed.events.length) {
  4644. showToast('That track contained no readable text');
  4645. return;
  4646. }
  4647. loadedSubtitleFiles.push({
  4648. path: cacheKey,
  4649. name: embeddedTrackLabel(track, position),
  4650. cues: [],
  4651. assTrack: parsed
  4652. });
  4653. activeSubtitleIndex = loadedSubtitleFiles.length - 1;
  4654. applyActiveSubtitle();
  4655. updateSubtitleSubmenu();
  4656. showToast('Subtitle loaded · ' + parsed.events.length + ' styled lines');
  4657. return;
  4658. }
  4659. var cues = parseSrt(content);
  4660. if (cues.length === 0) {
  4661. showToast('That track contained no readable text');
  4662. return;
  4663. }
  4664. loadedSubtitleFiles.push({
  4665. path: cacheKey,
  4666. name: embeddedTrackLabel(track, position),
  4667. cues: cues
  4668. });
  4669. activeSubtitleIndex = loadedSubtitleFiles.length - 1;
  4670. applyActiveSubtitle();
  4671. updateSubtitleSubmenu();
  4672. showToast('Subtitle loaded · ' + cues.length + ' lines');
  4673. },
  4674. error: function () { showToast('Could not extract that subtitle track'); }
  4675. });
  4676. }
  4677. // Switch the display between the styled ASS renderer and the plain SubRip
  4678. // overlay depending on what the newly selected track carries.
  4679. function applyActiveSubtitle() {
  4680. var entry = activeSubtitleIndex >= 0 ? loadedSubtitleFiles[activeSubtitleIndex] : null;
  4681. if (entry && entry.assTrack) {
  4682. startAssTrack(entry.assTrack);
  4683. } else {
  4684. stopAssTrack();
  4685. updateSubtitleDisplay();
  4686. }
  4687. }
  4688. // ─── Subtitle seek floor ──────────────────────────────────────────────────────
  4689. // After a seek, any line that had already begun before the landing point is
  4690. // skipped entirely; only lines that start at or after it are shown. Seeking to
  4691. // 1:02 with lines at 1:00-1:03 and 1:05-1:10 therefore shows nothing until 1:05.
  4692. var subtitleSeekFloor = 0;
  4693. function setSubtitleSeekFloor(time) {
  4694. subtitleSeekFloor = Math.max(0, time || 0);
  4695. if (assRenderer) { assRenderer.setSuppressBefore(subtitleSeekFloor); }
  4696. updateSubtitleDisplay();
  4697. }
  4698. function resetSubtitleSeekFloor() { setSubtitleSeekFloor(0); }
  4699. // ─── Styled ASS rendering ─────────────────────────────────────────────────────
  4700. // ASS tracks are fetched in their native form and drawn by script/ass.js, which
  4701. // preserves per-line styling and position. That is what makes dual-language
  4702. // releases work: the Japanese and Chinese lines are separate events shown at the
  4703. // same time, and a single-cue renderer can only ever display one of them.
  4704. var assRenderer = null;
  4705. var assActive = false;
  4706. var assFrameReq = null;
  4707. function initAssRenderer() {
  4708. var overlay = document.getElementById('ass-overlay');
  4709. if (overlay && typeof ASS !== 'undefined') { assRenderer = new ASS.Renderer(overlay); }
  4710. }
  4711. // Match the overlay to the letterboxed picture inside the video element, so
  4712. // script coordinates map onto what the viewer actually sees.
  4713. function syncAssOverlayGeometry() {
  4714. if (!assRenderer) { return; }
  4715. var vid = document.getElementById('main-video');
  4716. var overlay = document.getElementById('ass-overlay');
  4717. var cw = vid.clientWidth, ch = vid.clientHeight;
  4718. var vw = vid.videoWidth, vh = vid.videoHeight;
  4719. // Until the decoder reports the picture size there is no way to know where
  4720. // the letterbox bars are. Falling back to the raw element box would scale
  4721. // the script against the black bars too and push bottom-anchored lines down
  4722. // over the controls, so keep the last known good geometry instead.
  4723. if (!(vw > 0 && vh > 0 && cw > 0 && ch > 0)) { return; }
  4724. var scale = Math.min(cw / vw, ch / vh);
  4725. var width = vw * scale;
  4726. var height = vh * scale;
  4727. var left = (cw - width) / 2;
  4728. var top = (ch - height) / 2;
  4729. if (overlay._w !== width || overlay._h !== height || overlay._l !== left || overlay._t !== top) {
  4730. overlay._w = width; overlay._h = height; overlay._l = left; overlay._t = top;
  4731. overlay.style.left = left + 'px';
  4732. overlay.style.top = top + 'px';
  4733. overlay.style.width = width + 'px';
  4734. overlay.style.height = height + 'px';
  4735. assRenderer.resize(width, height);
  4736. }
  4737. }
  4738. function startAssTrack(track) {
  4739. if (!assRenderer) { return; }
  4740. stopAssTrack();
  4741. assRenderer.setTrack(track);
  4742. assActive = true;
  4743. $('#ass-overlay').addClass('active');
  4744. $('#subtitle-display').hide(); // the plain renderer must not double up
  4745. loadAssFonts(track);
  4746. var step = function () {
  4747. if (!assActive) { return; }
  4748. syncAssOverlayGeometry();
  4749. assRenderer.setTime(effectivePlaybackTime());
  4750. assFrameReq = requestAnimationFrame(step);
  4751. };
  4752. step();
  4753. }
  4754. function stopAssTrack() {
  4755. assActive = false;
  4756. if (assFrameReq) { cancelAnimationFrame(assFrameReq); assFrameReq = null; }
  4757. if (assRenderer) { assRenderer.clear(); }
  4758. $('#ass-overlay').removeClass('active');
  4759. }
  4760. // Only pull the fonts the track actually references — a release can attach a
  4761. // dozen and use half of them.
  4762. function loadAssFonts(track) {
  4763. if (typeof ASS === 'undefined') { return; }
  4764. ASS.referencedFonts(track).forEach(function (family) {
  4765. ensureEmbeddedFontLoaded(family);
  4766. });
  4767. }
  4768. // ─── Embedded fonts ───────────────────────────────────────────────────────────
  4769. // Registered under the font's own internal family name, which is what ASS styles
  4770. // reference, and offered in Subtitle Settings for SubRip tracks. Fetched lazily:
  4771. // a release can carry a dozen fonts and only a few are ever used.
  4772. function embeddedFontFamily(font) {
  4773. return font.family || ('aroz-embedded-' + font.index);
  4774. }
  4775. function findEmbeddedFontByFamily(family) {
  4776. var wanted = String(family || '').replace(/^@/, '').toLowerCase();
  4777. var found = null;
  4778. embeddedFonts.forEach(function (f) {
  4779. if (embeddedFontFamily(f).toLowerCase() === wanted) { found = f; }
  4780. });
  4781. return found;
  4782. }
  4783. function refreshEmbeddedFontOptions() {
  4784. var $select = $('#sset-font');
  4785. $select.find('optgroup.embedded-fonts').remove();
  4786. if (embeddedFonts.length > 0) {
  4787. var $group = $('<optgroup label="Embedded in this video" class="embedded-fonts"></optgroup>');
  4788. embeddedFonts.forEach(function (font) {
  4789. $group.append($('<option></option>')
  4790. .attr('value', embeddedFontFamily(font))
  4791. .text(font.filename || ('Font ' + (font.index + 1))));
  4792. });
  4793. $select.append($group);
  4794. }
  4795. // A font picked for a previous video may not exist in this one. Anything no
  4796. // longer offered by the dropdown (built-in or embedded) falls back.
  4797. var stillOffered = $select.find('option').filter(function () {
  4798. return this.value === subtitleSettings.font;
  4799. }).length > 0;
  4800. if (!stillOffered) {
  4801. subtitleSettings.font = 'system-ui, sans-serif';
  4802. applySubtitleSettings();
  4803. saveSubtitleSettings();
  4804. }
  4805. $select.val(subtitleSettings.font);
  4806. ensureEmbeddedFontLoaded(subtitleSettings.font);
  4807. }
  4808. function ensureEmbeddedFontLoaded(family) {
  4809. if (!family || embeddedFontsLoaded[family] || !embeddedMediaPath) { return; }
  4810. if (typeof FontFace === 'undefined' || !document.fonts) { return; }
  4811. var meta = findEmbeddedFontByFamily(family);
  4812. if (!meta) { return; } // a built-in font, or one this video does not carry
  4813. embeddedFontsLoaded[family] = true; // claim it so we do not refetch in a loop
  4814. var url = SUBTITLE_API + '?file=' + encodeURIComponent(embeddedMediaPath) + '&font=' + meta.index;
  4815. var face = new FontFace(embeddedFontFamily(meta), 'url("' + url + '")');
  4816. face.load().then(function (loaded) {
  4817. document.fonts.add(loaded);
  4818. embeddedFontFaces.push(loaded);
  4819. applySubtitleSettings();
  4820. syncSettingsPreview();
  4821. // The renderer sizes every run off the face's own ascent/descent, so a
  4822. // face arriving late invalidates the measurements taken against the
  4823. // fallback it was standing in for.
  4824. if (typeof ASS !== 'undefined' && ASS.invalidateFontMetrics) { ASS.invalidateFontMetrics(); }
  4825. if (assRenderer) { assRenderer.clear(); } // redraw with the real face
  4826. }).catch(function () {
  4827. embeddedFontsLoaded[family] = false;
  4828. });
  4829. }
  4830. // Builds the track list (Disable / embedded tracks / loaded sidecar files) into
  4831. // one menu, given its "Disable" and "Load" anchor items — shared by the
  4832. // right-click context submenu and the dedicated CC button popup so both stay
  4833. // in sync from a single call to updateSubtitleSubmenu().
  4834. function populateSubtitleTrackList($disable, $load, onSelect) {
  4835. $disable.siblings('.ctx-sub-dynamic').remove();
  4836. var disabled = (activeSubtitleIndex < 0);
  4837. $disable.toggleClass('ctx-active', disabled)
  4838. .find('.ctx-icon').text(disabled ? '✓' : '');
  4839. // Tracks muxed into the video, listed whether or not they are loaded yet
  4840. if (embeddedSubtitles.length > 0) {
  4841. $('<div class="ctx-divider ctx-sub-dynamic"></div>').insertBefore($load);
  4842. embeddedSubtitles.forEach(function (track, position) {
  4843. var cacheKey = 'embedded#' + track.index + '@' + embeddedMediaPath;
  4844. var isActive = activeSubtitleIndex >= 0 &&
  4845. loadedSubtitleFiles[activeSubtitleIndex] &&
  4846. loadedSubtitleFiles[activeSubtitleIndex].path === cacheKey;
  4847. $('<div class="ctx-item ctx-sub-dynamic'
  4848. + (isActive ? ' ctx-active' : '')
  4849. + (track.textual ? '' : ' ctx-disabled') + '">'
  4850. + '<i class="ctx-icon">' + (isActive ? '✓' : '') + '</i>'
  4851. + escapeHtml(embeddedTrackLabel(track, position))
  4852. + '</div>')
  4853. .on('click', function () {
  4854. selectEmbeddedSubtitle(track, position);
  4855. onSelect();
  4856. })
  4857. .insertBefore($load);
  4858. });
  4859. }
  4860. // Sidecar files the user loaded by hand
  4861. var external = [];
  4862. loadedSubtitleFiles.forEach(function (sf, idx) {
  4863. if (String(sf.path).indexOf('embedded#') !== 0) { external.push({ sf: sf, idx: idx }); }
  4864. });
  4865. if (external.length > 0) {
  4866. $('<div class="ctx-divider ctx-sub-dynamic"></div>').insertBefore($load);
  4867. external.forEach(function (entry) {
  4868. var isActive = (entry.idx === activeSubtitleIndex);
  4869. $('<div class="ctx-item ctx-sub-dynamic' + (isActive ? ' ctx-active' : '') + '" data-sub-idx="' + entry.idx + '">' +
  4870. '<i class="ctx-icon">' + (isActive ? '✓' : '') + '</i>' +
  4871. escapeHtml(entry.sf.name) +
  4872. '</div>')
  4873. .on('click', function () {
  4874. activeSubtitleIndex = parseInt($(this).data('sub-idx'), 10);
  4875. applyActiveSubtitle();
  4876. updateSubtitleSubmenu();
  4877. onSelect();
  4878. })
  4879. .insertBefore($load);
  4880. });
  4881. }
  4882. }
  4883. function updateSubtitleSubmenu() {
  4884. populateSubtitleTrackList($('#ctx-sub-disable'), $('#ctx-sub-load'), function () {
  4885. $('#player-ctx').hide();
  4886. });
  4887. populateSubtitleTrackList($('#sub-pop-disable'), $('#sub-pop-load'), function () {
  4888. closeSubtitlePopup();
  4889. });
  4890. if ($('#subtitle-popup').hasClass('active')) { clampBottomPopupHeight($('#subtitle-popup')); }
  4891. }
  4892. function initSubtitleMenu() {
  4893. var $ctx = $('#player-ctx');
  4894. var $parent = $('#ctx-subtitle-parent');
  4895. var $sub = $('#ctx-subtitle-sub');
  4896. var subHideTimer;
  4897. function cancelSubHide() { clearTimeout(subHideTimer); }
  4898. function scheduleSubHide() {
  4899. subHideTimer = setTimeout(function () { $sub.hide(); }, 120);
  4900. }
  4901. $parent.on('mouseenter', function () {
  4902. cancelSubHide();
  4903. // Flip submenu left if it would overflow the video container
  4904. var ctxRight = $ctx.offset().left + $ctx.outerWidth();
  4905. var subWidth = 200; // min-width; use before it's visible
  4906. var containerRight = $('#video-container').offset().left + $('#video-container').outerWidth();
  4907. if (ctxRight + subWidth > containerRight) {
  4908. $sub.css({ left: 'auto', right: '100%' });
  4909. } else {
  4910. $sub.css({ left: '100%', right: 'auto' });
  4911. }
  4912. // Clamp vertically so the submenu never runs past the container edge —
  4913. // flip to open upward when there's more room above than below, and
  4914. // cap its height to whichever side it opens on (scrollbar handles the rest).
  4915. var margin = 10;
  4916. var containerRect = document.getElementById('video-container').getBoundingClientRect();
  4917. var parentRect = this.getBoundingClientRect();
  4918. var spaceBelow = containerRect.bottom - parentRect.top - margin;
  4919. var spaceAbove = parentRect.bottom - containerRect.top - margin;
  4920. if (spaceBelow < 160 && spaceAbove > spaceBelow) {
  4921. $sub.css({ top: 'auto', bottom: 0, maxHeight: Math.max(120, spaceAbove) + 'px' });
  4922. } else {
  4923. $sub.css({ top: 0, bottom: 'auto', maxHeight: Math.max(120, spaceBelow) + 'px' });
  4924. }
  4925. $sub.show();
  4926. });
  4927. $parent.on('mouseleave', scheduleSubHide);
  4928. $sub.on('mouseenter', cancelSubHide);
  4929. $sub.on('mouseleave', scheduleSubHide);
  4930. $('#ctx-sub-disable').on('click', function () {
  4931. activeSubtitleIndex = -1;
  4932. stopAssTrack();
  4933. $('#subtitle-display').hide();
  4934. updateSubtitleSubmenu();
  4935. $ctx.hide();
  4936. });
  4937. $('#ctx-sub-load').on('click', function () {
  4938. $ctx.hide();
  4939. pickSubtitleFile();
  4940. });
  4941. document.getElementById('main-video')
  4942. .addEventListener('timeupdate', updateSubtitleDisplay);
  4943. }
  4944. // Open the ArozOS file selector, defaulted to the folder of the playing file
  4945. function pickSubtitleFile() {
  4946. var startDir = 'user:/';
  4947. if (playingIndex >= 0 && currentEpisodes[playingIndex]) {
  4948. var fp = currentEpisodes[playingIndex].filepath.replace(/\\/g, '/');
  4949. var slash = fp.lastIndexOf('/');
  4950. if (slash > 0) { startDir = fp.substring(0, slash); }
  4951. }
  4952. ao_module_openFileSelector(
  4953. window.movieOnSubtitleFile,
  4954. startDir, 'file', false,
  4955. { fnameOverride: 'movieOnSubtitleFile', extAllowed: '.srt' }
  4956. );
  4957. }
  4958. var toastTimer;
  4959. function showToast(msg) {
  4960. clearTimeout(toastTimer);
  4961. $('#toast').text(msg).addClass('show');
  4962. toastTimer = setTimeout(function () { $('#toast').removeClass('show'); }, 2800);
  4963. }
  4964. // play() returns a promise that rejects when the browser will not start the
  4965. // media — most commonly NotSupportedError on Safari, which refuses a transcoded
  4966. // stream because the endpoint cannot answer byte-range requests. Left
  4967. // unhandled it only shows up as an unhandled rejection in the console, so the
  4968. // player just sits there with no explanation. Surface it instead.
  4969. function playVideo(v) {
  4970. var p = v.play();
  4971. if (p && typeof p.catch === 'function') {
  4972. p.catch(function (err) {
  4973. if (err && err.name === 'AbortError') {
  4974. // Fired whenever a load or a new src interrupts a pending
  4975. // play() — routine during seek-by-reload, not a failure.
  4976. return;
  4977. }
  4978. if (err && err.name === 'NotSupportedError') {
  4979. showToast('This browser cannot play this transcoded format. Try Chrome or Firefox.');
  4980. } else {
  4981. showToast('Playback failed: ' + ((err && err.message) || 'unknown error'));
  4982. }
  4983. });
  4984. }
  4985. return p;
  4986. }
  4987. </script>
  4988. </body>
  4989. </html>