index.html 224 KB

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