| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
- <meta name="apple-mobile-web-app-capable" content="yes">
- <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
- <meta name="theme-color" content="#000000">
- <link rel="manifest" crossorigin="use-credentials" href="manifest.json">
- <title>Movie</title>
- <!-- ArozOS module helpers -->
- <script src="../script/jquery.min.js"></script>
- <script src="../script/ao_module.js"></script>
- <!-- App path config (single source of truth for all API paths) -->
- <!-- HLS via Media Source, so browsers without native HLS (Firefox,
- Chrome) can play the transcoded playlist without hls.js -->
- <script src="../script/hlsmse.js"></script>
- <script src="backend/common.js"></script>
- <!-- ASS/SSA subtitle parser + renderer (see script/ass.js) -->
- <script src="script/ass.js"></script>
- <style>
- /* ─── Reset & base ──────────────────────────────────────────────────────────── */
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
- :root {
- --bg: #0a0a0a;
- --surface: #1c1c1e;
- --surface2: #2c2c2e;
- --accent: #0a84ff;
- --accent2: #30d158;
- --text: #f5f5f7;
- --text-sub: #98989d;
- --radius: 12px;
- --card-w: 180px;
- --card-ratio: 1.5; /* height = width * ratio (poster aspect) */
- --header-h: 56px;
- --transition: 0.2s ease;
- }
- html, body {
- background: var(--bg);
- color: var(--text);
- font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Helvetica Neue", sans-serif;
- height: 100%;
- overflow: hidden;
- }
- /* ─── App shell ──────────────────────────────────────────────────────────────── */
- #app { width: 100vw; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
- /* ─── Top nav bar ────────────────────────────────────────────────────────────── */
- #topbar {
- flex-shrink: 0;
- height: var(--header-h);
- display: flex;
- align-items: center;
- padding: 0 20px;
- gap: 16px;
- background: linear-gradient(to bottom, rgba(0,0,0,0.9) 0%, transparent 100%);
- position: relative;
- z-index: 10;
- }
- #topbar h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.3px; }
- #topbar h1 span { color: var(--accent); }
- #search-wrap { margin-left: auto; display: flex; align-items: center; gap: 8px; }
- #search-input {
- background: var(--surface2);
- border: none;
- border-radius: 20px;
- color: var(--text);
- font-size: 14px;
- padding: 7px 14px;
- width: 200px;
- outline: none;
- transition: width var(--transition);
- }
- #search-input:focus { width: 280px; box-shadow: 0 0 0 2px var(--accent); }
- #search-input::placeholder { color: var(--text-sub); }
- /* ─── View containers ────────────────────────────────────────────────────────── */
- .view { display: none; flex: 1; overflow: hidden; flex-direction: column; }
- .view.active { display: flex; }
- /* ─── Library view ───────────────────────────────────────────────────────────── */
- #view-library { padding: 0; }
- /* Status bar ─────────────────────────────────────────────────────────────────── */
- #library-status-bar {
- flex-shrink: 0;
- display: flex;
- align-items: center;
- gap: 7px;
- padding: 3px 22px;
- font-size: 11px;
- color: var(--text-sub);
- border-bottom: 1px solid rgba(255,255,255,0.04);
- min-height: 26px;
- }
- .spinner-sm {
- width: 11px; height: 11px; flex-shrink: 0;
- border: 2px solid rgba(255,255,255,0.15);
- border-top-color: var(--accent);
- border-radius: 50%;
- animation: spin 0.8s linear infinite;
- }
- #library-refresh-btn {
- background: none; border: none; cursor: pointer;
- color: var(--accent); font-size: 11px; font-weight: 500;
- padding: 0; outline: none; transition: opacity var(--transition);
- }
- #library-refresh-btn:hover { opacity: 0.7; }
- #library-refresh-btn:disabled { opacity: 0.35; cursor: default; }
- #library-scroll {
- flex: 1;
- overflow-y: auto;
- overflow-x: hidden;
- padding: 8px 20px 40px;
- scroll-behavior: smooth;
- }
- #library-scroll::-webkit-scrollbar { width: 4px; }
- #library-scroll::-webkit-scrollbar-track { background: transparent; }
- #library-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
- #no-content {
- display: none;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- height: 60%;
- gap: 12px;
- color: var(--text-sub);
- font-size: 16px;
- }
- #no-content .icon img { width: 80px; height: 80px; opacity: 0.3; }
- #loading-overlay {
- position: absolute; inset: 0;
- background: var(--bg);
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 16px;
- z-index: 100;
- font-size: 15px;
- color: var(--text-sub);
- }
- .spinner {
- width: 40px; height: 40px;
- border: 3px solid var(--surface2);
- border-top-color: var(--accent);
- border-radius: 50%;
- animation: spin 0.8s linear infinite;
- }
- @keyframes spin { to { transform: rotate(360deg); } }
- /* ─── Section heading ────────────────────────────────────────────────────────── */
- .section-title {
- font-size: 20px;
- font-weight: 600;
- margin: 24px 0 12px;
- color: var(--text);
- }
- /* ─── Album grid ─────────────────────────────────────────────────────────────── */
- .album-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(var(--card-w), 1fr));
- gap: 16px;
- }
- .album-card {
- cursor: pointer;
- border-radius: var(--radius);
- overflow: hidden;
- background: var(--surface);
- transition: transform var(--transition), box-shadow var(--transition);
- outline: none;
- position: relative;
- }
- .album-card:hover,
- .album-card.focused {
- transform: scale(1.04);
- box-shadow: 0 8px 32px rgba(0,0,0,0.7), 0 0 0 2px var(--accent);
- z-index: 2;
- }
- .album-card .poster {
- width: 100%;
- aspect-ratio: 16 / 9;
- object-fit: cover;
- display: block;
- background: var(--surface2);
- }
- .poster-placeholder {
- width: 100%;
- aspect-ratio: 16 / 9;
- background: linear-gradient(135deg, var(--surface) 0%, var(--surface2) 100%);
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .poster-placeholder img { width: 100%; opacity: 1; }
- .album-card .card-info {
- padding: 8px 10px 10px;
- }
- .album-card .card-title {
- font-size: 13px;
- font-weight: 600;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
- .album-card .card-meta {
- font-size: 11px;
- color: var(--text-sub);
- margin-top: 2px;
- }
- .badge {
- position: absolute;
- top: 7px; right: 7px;
- background: rgba(0,0,0,0.65);
- backdrop-filter: blur(4px);
- border-radius: 6px;
- font-size: 10px;
- font-weight: 600;
- padding: 2px 6px;
- color: #fff;
- letter-spacing: 0.3px;
- text-transform: uppercase;
- }
- .badge.series { color: var(--accent2); }
- .badge.anime { color: #ff9f0a; } /* warm orange for anime */
- /* ─── Detail view ────────────────────────────────────────────────────────────── */
- #view-detail { position: relative; }
- #detail-hero {
- flex-shrink: 0;
- height: 38vh;
- min-height: 200px;
- position: relative;
- overflow: hidden;
- }
- #detail-hero-bg {
- position: absolute; inset: 0;
- background-size: cover;
- background-position: center top;
- filter: blur(4px) brightness(0.55);
- transform: scale(1.1);
- }
- #detail-hero-content {
- position: relative;
- display: flex;
- align-items: flex-end;
- height: 100%;
- padding: 0 28px 20px;
- gap: 20px;
- }
- #detail-poster {
- width: 120px;
- flex-shrink: 0;
- border-radius: 8px;
- overflow: hidden;
- box-shadow: 0 8px 24px rgba(0,0,0,0.6);
- }
- #detail-poster img, #detail-poster .poster-placeholder {
- width: 120px;
- aspect-ratio: 2 / 3;
- object-fit: cover;
- display: block;
- }
- #detail-meta { flex: 1; min-width: 0; }
- #detail-title { font-size: 26px; font-weight: 700; line-height: 1.15; overflow-wrap: anywhere; }
- #detail-subtitle { font-size: 14px; color: var(--text-sub); margin-top: 4px; }
- #detail-actions { display: flex; gap: 10px; margin-top: 14px; flex-wrap: wrap; }
- .btn {
- border: none; cursor: pointer; border-radius: 8px;
- font-size: 14px; font-weight: 600; padding: 10px 22px;
- transition: opacity var(--transition), transform var(--transition);
- outline: none;
- }
- .btn:hover, .btn.focused { opacity: 0.85; transform: scale(1.03); }
- .btn-primary { background: var(--text); color: #000; }
- .btn-secondary { background: var(--surface2); color: var(--text); }
- /* ─── Season tabs ────────────────────────────────────────────────────────────── */
- #season-tabs {
- flex-shrink: 0;
- display: flex;
- flex-wrap: wrap;
- gap: 6px 8px;
- padding: 10px 28px 8px;
- max-height: 120px; /* ~3 rows before scrolling */
- overflow-y: auto;
- scrollbar-width: thin;
- scrollbar-color: var(--surface2) transparent;
- }
- #season-tabs::-webkit-scrollbar { width: 3px; height: 3px; }
- #season-tabs::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 3px; }
- .season-tab {
- flex-shrink: 0;
- background: var(--surface2);
- border: none; cursor: pointer;
- border-radius: 20px;
- color: var(--text-sub);
- font-size: 13px; font-weight: 500;
- padding: 6px 16px;
- transition: background var(--transition), color var(--transition);
- outline: none;
- /* Season names can be as long as the whole release title — keep the pill
- inside the panel and ellipsise instead of running off the edge. */
- max-width: 100%;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .season-tab.active, .season-tab.focused {
- background: var(--text);
- color: #000;
- }
- /* ─── Episode list ───────────────────────────────────────────────────────────── */
- #episode-scroll {
- flex: 1;
- overflow-y: auto;
- padding: 12px 28px 40px;
- scroll-behavior: smooth;
- }
- #episode-scroll::-webkit-scrollbar { width: 4px; }
- #episode-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
- .episode-item {
- display: flex;
- align-items: center;
- gap: 14px;
- padding: 10px 12px;
- border-radius: var(--radius);
- cursor: pointer;
- transition: background var(--transition);
- outline: none;
- }
- .episode-item:hover, .episode-item.focused {
- background: var(--surface);
- box-shadow: 0 0 0 2px var(--accent);
- }
- .episode-item.playing { background: rgba(10,132,255,0.15); }
- .ep-thumb {
- width: 100px; flex-shrink: 0;
- aspect-ratio: 16 / 9;
- border-radius: 6px;
- overflow: hidden;
- background: var(--surface2);
- }
- .ep-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
- .ep-thumb-placeholder {
- width: 100%; height: 100%;
- display: flex; align-items: center; justify-content: center;
- }
- .ep-thumb-placeholder img { width: 22px; height: 22px; opacity: 0.5; }
- .ep-info { flex: 1; min-width: 0; }
- .ep-name { font-size: 14px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
- .ep-path { font-size: 11px; color: var(--text-sub); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .ep-play-icon {
- flex-shrink: 0;
- width: 32px; height: 32px;
- background: var(--surface2);
- border-radius: 50%;
- display: flex; align-items: center; justify-content: center;
- transition: background var(--transition);
- }
- .ep-play-icon img { width: 16px; height: 16px; }
- .episode-item.focused .ep-play-icon,
- .episode-item:hover .ep-play-icon { background: var(--accent); }
- #detail-back {
- position: absolute;
- top: 12px; left: 16px;
- background: rgba(0,0,0,0.5);
- backdrop-filter: blur(8px);
- border: none; cursor: pointer;
- border-radius: 20px;
- color: var(--text);
- font-size: 13px; font-weight: 500;
- padding: 6px 16px;
- z-index: 5;
- transition: background var(--transition);
- outline: none;
- }
- #detail-back:hover, #detail-back.focused { background: var(--accent); }
- /* ─── Player view ────────────────────────────────────────────────────────────── */
- #view-player {
- position: fixed; inset: 0;
- background: #000;
- z-index: 200;
- flex-direction: row;
- }
- #view-player.active { display: flex; }
- #video-container {
- flex: 1;
- display: flex;
- flex-direction: column;
- position: relative;
- overflow: hidden;
- }
- #main-video {
- width: 100%; height: 100%;
- object-fit: contain;
- background: #000;
- display: block;
- }
- /* ─── Custom video controls ──────────────────────────────────────────────────── */
- #video-controls {
- position: absolute;
- bottom: 0; left: 0; right: 0;
- background: linear-gradient(transparent, rgba(0,0,0,0.85) 100%);
- padding: 40px 20px 16px;
- transition: opacity 0.3s;
- }
- #video-controls.hidden { opacity: 0; pointer-events: none; }
- /* Hide cursor when controls auto-hide */
- #video-container:has(#video-controls.hidden) { cursor: none; }
- #progress-wrap {
- position: relative;
- height: 4px;
- background: rgba(255,255,255,0.25);
- border-radius: 4px;
- cursor: pointer;
- margin-bottom: 12px;
- }
- #progress-bar {
- height: 100%; border-radius: 4px;
- background: var(--accent);
- pointer-events: none;
- }
- #progress-wrap:hover { height: 6px; }
- /* Transparent hit-zone 16px above the visual bar */
- #progress-wrap::before {
- content: '';
- position: absolute;
- top: -16px; left: 0; right: 0;
- height: 16px;
- }
- #progress-thumb {
- position: absolute;
- top: 50%; transform: translateY(-50%);
- width: 14px; height: 14px;
- background: #fff; border-radius: 50%;
- pointer-events: none;
- display: none;
- }
- #progress-wrap:hover #progress-thumb { display: block; }
- #controls-row {
- display: flex;
- align-items: center;
- gap: 10px;
- }
- .ctrl-btn {
- background: none; border: none; cursor: pointer;
- color: #fff; padding: 4px;
- line-height: 1;
- transition: opacity var(--transition);
- outline: none;
- display: flex; align-items: center; justify-content: center;
- }
- .ctrl-btn img { width: 24px; height: 24px; display: block; }
- .ctrl-cc-icon {
- width: 24px; height: 24px;
- display: flex; align-items: center; justify-content: center;
- font-size: 10px; font-weight: 700; letter-spacing: 0.4px;
- border: 1.5px solid #fff; border-radius: 4px; line-height: 1;
- }
- .ctrl-btn:hover { opacity: 0.7; }
- .ctrl-btn.focused { background: rgba(10,132,255,0.18); border-radius: 6px; }
- #volume-wrap { display: flex; align-items: center; gap: 8px; }
- #volume-slider {
- -webkit-appearance: none;
- width: 80px; height: 4px;
- background: rgba(255,255,255,0.3);
- border-radius: 4px; outline: none;
- }
- #volume-slider::-webkit-slider-thumb {
- -webkit-appearance: none;
- width: 12px; height: 12px;
- background: #fff; border-radius: 50%;
- }
- /* Portrait phones/tablets drive playback volume with the hardware keys, so the
- in-page slider only eats toolbar width. Users who want it back can force it
- on from the player settings popup ("Volume bar → Always show"). */
- @media (max-width: 899px) and (orientation: portrait) {
- #volume-slider { display: none; }
- }
- body.always-show-volume #volume-slider { display: block; }
- /* ─── Centre play/pause flash indicator ──────────────────────────────────────── */
- #play-flash {
- position: absolute;
- top: 50%; left: 50%;
- width: 88px; height: 88px;
- margin: -44px 0 0 -44px;
- border-radius: 50%;
- background: rgba(0,0,0,0.55);
- backdrop-filter: blur(4px);
- -webkit-backdrop-filter: blur(4px);
- display: flex; align-items: center; justify-content: center;
- pointer-events: none;
- opacity: 0;
- z-index: 18;
- }
- #play-flash img { width: 40px; height: 40px; display: block; }
- #play-flash.flash { animation: playFlash 0.62s ease-out; }
- @keyframes playFlash {
- 0% { opacity: 0; transform: scale(0.68); }
- 18% { opacity: 0.95; transform: scale(0.92); }
- 100% { opacity: 0; transform: scale(1.32); }
- }
- /* ─── ASS subtitle overlay ───────────────────────────────────────────────────── */
- /* Sized in JS to the video's displayed rect so script coordinates land correctly
- regardless of letterboxing. Children are absolutely positioned by the renderer. */
- #ass-overlay {
- display: none;
- position: absolute;
- left: 0; top: 0; width: 0; height: 0;
- pointer-events: none;
- overflow: hidden;
- /* No z-index on purpose: subtitles sit directly after <video> in the DOM,
- so they paint above the (unpositioned) video but below every later
- positioned sibling — scrub preview, controls, menus and modals all stay
- on top of the text instead of being covered by it. */
- /* ...but that only holds if the cues stay *inside* this box. The renderer
- gives each cue an inline z-index so simultaneous lines stack in event
- order (see ass.js boxCss), and a positioned element with z-index:auto is
- not a stacking context — so those cues would otherwise be promoted into
- the player's stacking context and outrank the controls, which are
- themselves z-index:auto. Isolating creates the stacking context that keeps
- cue ordering internal, without giving this layer a z-index of its own. */
- isolation: isolate;
- }
- #ass-overlay.active { display: block; }
- /* ─── Scrub-bar hover preview ────────────────────────────────────────────────── */
- #scrub-preview {
- display: none;
- position: absolute;
- bottom: 100%;
- margin-bottom: 12px;
- transform: translateX(-50%);
- pointer-events: none;
- /* Above the centre play/pause flash, so scrubbing right after a click
- does not put the thumbnail behind it. (ASS cues no longer need
- outranking here — #ass-overlay isolates them.) */
- z-index: 20;
- flex-direction: column;
- align-items: center;
- gap: 6px;
- }
- #scrub-preview.active { display: flex; }
- #scrub-preview-thumb {
- display: none;
- border-radius: 8px;
- background-color: #000;
- background-repeat: no-repeat;
- box-shadow: 0 4px 18px rgba(0,0,0,0.8), 0 0 0 2px rgba(255,255,255,0.14);
- }
- #scrub-preview-thumb.ready { display: block; }
- #scrub-preview-time {
- background: rgba(0,0,0,0.82);
- border-radius: 6px;
- padding: 3px 9px;
- font-size: 12px;
- font-weight: 600;
- color: #fff;
- white-space: nowrap;
- font-variant-numeric: tabular-nums;
- }
- /* ─── Transcode-seek freeze frame ────────────────────────────────────────────── */
- /* Deliberately no z-index: both sit immediately after <video> in the DOM, so they
- paint above the (unpositioned) video but below every later positioned sibling
- — controls, top bar and menus all stay on top and clickable. */
- #seek-freeze {
- display: none;
- position: absolute; inset: 0;
- width: 100%; height: 100%;
- object-fit: contain;
- background: #000;
- pointer-events: none;
- }
- #seek-spinner {
- display: none;
- position: absolute; inset: 0;
- align-items: center; justify-content: center;
- pointer-events: none;
- }
- #seek-spinner.active { display: flex; }
- .seek-spinner-box {
- display: flex; flex-direction: column;
- align-items: center; gap: 10px;
- background: rgba(0,0,0,0.55);
- backdrop-filter: blur(4px);
- -webkit-backdrop-filter: blur(4px);
- border-radius: 14px;
- padding: 18px 24px;
- font-size: 12px; color: var(--text);
- }
- #time-display { font-size: 13px; color: rgba(255,255,255,0.8); margin-left: 6px; }
- #now-playing-title {
- font-size: 15px; font-weight: 600;
- flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- margin-left: 10px;
- }
- /* ─── Playlist sidebar ───────────────────────────────────────────────────────── */
- #playlist-sidebar {
- width: 300px;
- flex-shrink: 0;
- background: rgba(20,20,20,0.95);
- backdrop-filter: blur(12px);
- display: flex;
- flex-direction: column;
- border-left: 1px solid rgba(255,255,255,0.08);
- transform: translateX(0);
- transition: transform var(--transition), width var(--transition);
- }
- #playlist-sidebar.collapsed { width: 0; overflow: hidden; }
- #sidebar-header {
- padding: 14px 16px 10px;
- font-size: 15px; font-weight: 600;
- border-bottom: 1px solid rgba(255,255,255,0.08);
- display: flex; align-items: center; gap: 8px;
- }
- #sidebar-close {
- margin-left: auto;
- background: none; border: none; cursor: pointer;
- color: var(--text-sub); font-size: 18px; padding: 2px;
- outline: none;
- }
- #sidebar-close:hover { color: var(--text); }
- #sidebar-list { flex: 1; overflow-y: auto; padding: 8px; }
- #sidebar-list::-webkit-scrollbar { width: 3px; }
- #sidebar-list::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 3px; }
- .sidebar-ep {
- display: flex; align-items: center; gap: 10px;
- padding: 8px;
- border-radius: 8px; cursor: pointer;
- transition: background var(--transition);
- font-size: 13px; color: var(--text);
- outline: none;
- }
- .sidebar-ep:hover, .sidebar-ep.focused { background: var(--surface2); }
- .sidebar-ep.playing { background: rgba(10,132,255,0.2); color: var(--accent); }
- .sidebar-ep-num { flex-shrink: 0; width: 24px; text-align: center; color: var(--text-sub); font-size: 12px; }
- .sidebar-ep-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- /* ─── Player top bar (back btn + small-screen extras) ────────────────────────── */
- #player-topbar {
- position: absolute;
- top: 0; left: 0; right: 0;
- z-index: 10;
- display: flex;
- align-items: center;
- padding: 8px 10px;
- gap: 8px;
- /* transparent on large screens — only back button visible */
- }
- #player-back {
- flex-shrink: 0;
- background: rgba(0,0,0,0.55);
- backdrop-filter: blur(8px);
- border: none; cursor: pointer;
- border-radius: 20px;
- color: #fff;
- font-size: 13px; font-weight: 500;
- padding: 7px 16px;
- transition: background var(--transition);
- outline: none;
- }
- #player-back:hover { background: var(--accent); }
- /* Title + list + cast buttons shown only in topbar on small screens */
- #topbar-title {
- display: none;
- flex: 1;
- font-size: 13px; font-weight: 600;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- color: #fff;
- margin: 0 2px;
- }
- #ctrl-cast-top, #ctrl-list-top { display: none; }
- @media (max-width: 600px) {
- #player-topbar {
- background: rgba(0,0,0,0.88);
- backdrop-filter: blur(10px);
- }
- #topbar-title, #ctrl-cast-top, #ctrl-list-top { display: flex; align-items: center; }
- #topbar-title { display: block; }
- /* Hide these from the bottom controls bar */
- #now-playing-title, #ctrl-list, #ctrl-cast { display: none !important; }
- /* Push the settings + fullscreen pair right now that the title spacer is gone */
- #ctrl-settings { margin-left: auto; }
- /* Shrink volume slider to save space */
- #volume-slider { width: 56px; }
- #time-display { font-size: 11px; }
- }
- /* Fullscreen: hide entire topbar */
- #view-player:fullscreen #player-topbar,
- #view-player:-webkit-full-screen #player-topbar,
- #view-player:-moz-full-screen #player-topbar { display: none !important; }
- /* ─── Toast notification ─────────────────────────────────────────────────────── */
- #toast {
- position: fixed;
- bottom: 30px; left: 50%;
- transform: translateX(-50%) translateY(20px);
- background: rgba(30,30,30,0.95);
- backdrop-filter: blur(8px);
- color: var(--text);
- padding: 10px 20px;
- border-radius: 20px;
- font-size: 13px;
- opacity: 0;
- transition: opacity 0.3s, transform 0.3s;
- pointer-events: none;
- z-index: 1000;
- max-width: min(90vw, 30em);
- text-align: center; line-height: 1.45;
- }
- #toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
- /* ─── Responsive ─────────────────────────────────────────────────────────────── */
- @media (max-width: 600px) {
- :root { --card-w: 130px; }
- #library-scroll { padding: 8px 12px 40px; }
- #detail-hero { height: 44vw; min-height: 160px; }
- #detail-poster { width: 80px; }
- #detail-title { font-size: 18px; }
- #playlist-sidebar { width: 100%; position: absolute; right: 0; top: 0; bottom: 0; z-index: 5; }
- #playlist-sidebar.collapsed { width: 0; }
- #episode-scroll { padding: 10px 12px 40px; }
- .ep-thumb { width: 72px; }
- }
- /* ─── Phone: wrap topbar so the search bar never overflows ───────────────────── */
- @media (max-width: 540px) {
- #topbar {
- flex-wrap: wrap;
- height: auto;
- min-height: var(--header-h);
- padding: 6px 14px;
- row-gap: 4px;
- align-items: center;
- }
- #topbar h1 { font-size: 18px; flex-shrink: 0; }
- #mode-tabs { flex-shrink: 0; }
- /* Force search onto its own row, full width */
- #search-wrap {
- flex-basis: 100%;
- margin-left: 0;
- order: 10;
- }
- #search-input { width: 100%; max-width: none; }
- #search-input:focus { width: 100%; }
- }
- @media (max-width: 400px) {
- :root { --card-w: 110px; }
- .mode-tab { padding: 5px 8px; font-size: 12px; }
- }
- /* TV / large screen layout */
- @media (min-width: 1400px) {
- :root { --card-w: 200px; }
- }
- @media (min-width: 1800px) {
- :root { --card-w: 240px; }
- }
- /* ─── Mode tabs ──────────────────────────────────────────────────────────────── */
- #mode-tabs { display: flex; gap: 2px; }
- .mode-tab {
- background: none; border: none; cursor: pointer;
- border-radius: 6px; color: var(--text-sub);
- font-size: 13px; font-weight: 500; padding: 5px 12px;
- transition: background var(--transition), color var(--transition);
- outline: none;
- }
- .mode-tab.active { background: var(--surface2); color: var(--text); }
- .mode-tab:hover { color: var(--text); }
- /* ─── Folder view ────────────────────────────────────────────────────────────── */
- #folder-nav-bar {
- flex-shrink: 0;
- padding: 6px 20px;
- display: flex;
- align-items: center;
- overflow-x: auto;
- scrollbar-width: none;
- border-bottom: 1px solid rgba(255,255,255,0.06);
- min-height: 40px;
- }
- #folder-nav-bar::-webkit-scrollbar { display: none; }
- #folder-breadcrumb { display: flex; align-items: center; gap: 2px; }
- .crumb-btn {
- background: none; border: none; cursor: pointer;
- color: var(--text-sub); font-size: 13px;
- padding: 3px 7px; border-radius: 5px;
- transition: color var(--transition), background var(--transition);
- outline: none; white-space: nowrap;
- }
- .crumb-btn:hover { color: var(--text); background: var(--surface2); }
- .crumb-btn.crumb-current { color: var(--text); font-weight: 600; pointer-events: none; }
- .crumb-sep { color: var(--text-sub); font-size: 12px; opacity: 0.4; padding: 0 2px; }
- #folder-scroll {
- flex: 1; overflow-y: auto; overflow-x: hidden;
- padding: 8px 20px 40px; scroll-behavior: smooth;
- }
- #folder-scroll::-webkit-scrollbar { width: 4px; }
- #folder-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
- #folder-loading {
- display: none; flex-direction: column; align-items: center;
- justify-content: center; padding: 60px 0; gap: 12px; color: var(--text-sub);
- }
- #folder-loading.active { display: flex; }
- #folder-empty { display: none; color: var(--text-sub); padding: 60px 0; text-align: center; }
- .folder-thumb {
- width: 100%; aspect-ratio: 16/9;
- background: linear-gradient(135deg, #1c2640 0%, #2a3d6e 100%);
- display: flex; align-items: center; justify-content: center;
- font-size: 32px; user-select: none;
- }
- /* ─── Settings view ──────────────────────────────────────────────────────────── */
- #settings-scroll {
- flex: 1; overflow-y: auto; overflow-x: hidden;
- padding: 14px 20px 48px; scroll-behavior: smooth;
- }
- #settings-scroll::-webkit-scrollbar { width: 4px; }
- #settings-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
- .settings-card {
- background: var(--surface);
- border-radius: var(--radius);
- padding: 4px 18px 6px;
- margin-bottom: 14px;
- }
- .settings-card-title {
- font-size: 12px; font-weight: 700; letter-spacing: 0.4px;
- text-transform: uppercase; color: var(--text-sub);
- padding: 14px 0 10px;
- }
- .settings-row {
- display: flex; align-items: center; gap: 16px;
- padding: 12px 0;
- border-top: 1px solid rgba(255,255,255,0.06);
- }
- .settings-row-text { flex: 1; min-width: 0; }
- .settings-row-label { font-size: 14px; font-weight: 600; margin-bottom: 3px; }
- .settings-row-desc { font-size: 12px; color: var(--text-sub); line-height: 1.45; }
- .settings-row-desc code {
- background: var(--surface2); border-radius: 4px;
- padding: 1px 6px; font-size: 11px;
- overflow-wrap: anywhere;
- }
- .settings-btn { flex-shrink: 0; padding: 8px 18px; font-size: 13px; }
- .settings-btn-danger:hover { background: rgba(255,69,58,0.22); color: #ff453a; }
- .settings-btn[disabled] { opacity: 0.4; cursor: default; transform: none; }
- /* Toggle switch */
- .settings-switch { flex-shrink: 0; cursor: pointer; display: block; }
- .settings-switch input { display: none; }
- .settings-switch-track {
- display: block; width: 42px; height: 24px;
- background: var(--surface2); border-radius: 12px;
- position: relative; transition: background 0.2s;
- }
- .settings-switch input:checked + .settings-switch-track { background: var(--accent2); }
- .settings-switch-track::after {
- content: '';
- position: absolute; top: 3px; left: 3px;
- width: 18px; height: 18px;
- background: #fff; border-radius: 50%;
- transition: transform 0.2s;
- }
- .settings-switch input:checked + .settings-switch-track::after { transform: translateX(18px); }
- /* Stats */
- .stats-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
- gap: 10px;
- padding: 4px 0 12px;
- }
- .stat-box {
- background: var(--surface2);
- border-radius: calc(var(--radius) - 4px);
- padding: 12px 14px;
- }
- .stat-value { font-size: 20px; font-weight: 700; line-height: 1.2; overflow-wrap: anywhere; }
- .stat-label { font-size: 11px; color: var(--text-sub); margin-top: 3px; }
- .settings-breakdown {
- display: flex; flex-wrap: wrap; gap: 6px;
- padding-bottom: 10px;
- }
- .breakdown-chip {
- background: var(--surface2); border-radius: 20px;
- font-size: 11px; color: var(--text-sub);
- padding: 4px 11px;
- }
- .breakdown-chip b { color: var(--text); font-weight: 600; }
- .settings-meta {
- font-size: 11px; color: var(--text-sub);
- border-top: 1px solid rgba(255,255,255,0.06);
- padding: 10px 0 12px;
- }
- .settings-progress {
- display: none; align-items: center; gap: 8px;
- font-size: 12px; color: var(--text-sub);
- border-top: 1px solid rgba(255,255,255,0.06);
- padding: 12px 0;
- }
- .settings-progress.active { display: flex; }
- @media (max-width: 600px) {
- #settings-scroll { padding: 12px 12px 48px; }
- .settings-card { padding: 4px 14px 6px; }
- .settings-row { flex-wrap: wrap; gap: 10px; }
- .settings-btn { width: 100%; }
- }
- /* ─── Movie info panel ───────────────────────────────────────────────────────── */
- #view-movie-info { position: relative; }
- #movie-info-backdrop {
- position: absolute; inset: 0;
- background-size: cover; background-position: center 20%;
- filter: blur(4px) brightness(0.38);
- transform: scale(1.12); z-index: 0;
- }
- #movie-info-back {
- position: absolute; top: 14px; left: 16px; z-index: 10;
- background: rgba(0,0,0,0.5); backdrop-filter: blur(8px);
- border: none; cursor: pointer; border-radius: 20px;
- color: var(--text); font-size: 13px; font-weight: 500;
- padding: 6px 16px; transition: background var(--transition); outline: none;
- }
- #movie-info-back:hover { background: var(--accent); }
- #movie-info-scroll {
- flex: 1; overflow-y: auto; overflow-x: hidden;
- scroll-behavior: smooth; position: relative; z-index: 1;
- }
- #movie-info-scroll::-webkit-scrollbar { width: 4px; }
- #movie-info-scroll::-webkit-scrollbar-thumb { background: var(--surface2); border-radius: 4px; }
- #movie-info-hero {
- min-height: 280px; display: flex; align-items: flex-end; gap: 24px;
- padding: 70px 32px 28px;
- }
- #movie-info-poster-wrap {
- width: 130px; flex-shrink: 0; border-radius: 10px; overflow: hidden;
- box-shadow: 0 12px 32px rgba(0,0,0,0.7);
- aspect-ratio: 2/3; background: var(--surface2);
- }
- #movie-info-poster-wrap img { width: 100%; height: 100%; object-fit: cover; display: block; }
- #movie-info-meta { flex: 1; min-width: 0; }
- #movie-info-title { font-size: 26px; font-weight: 700; line-height: 1.15; margin-bottom: 2px; overflow-wrap: anywhere; }
- #movie-info-filename {
- font-size: 11px; color: var(--text-sub); opacity: 0.6;
- font-style: italic; margin-bottom: 6px;
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- display: none; /* shown only after IMDB title replaces the album name */
- }
- #movie-info-year { font-size: 14px; color: var(--text-sub); margin-bottom: 8px; }
- #movie-info-cast { font-size: 13px; color: var(--text-sub); line-height: 1.5; margin-bottom: 14px; }
- #movie-info-actions { display: flex; gap: 10px; flex-wrap: wrap; }
- .yt-badge {
- display: inline-flex; align-items: center;
- background: #ff0000; color: #fff;
- border-radius: 5px; font-size: 12px; font-weight: 800;
- padding: 5px 9px; cursor: pointer; border: none; outline: none;
- transition: opacity var(--transition);
- }
- .yt-badge:hover { opacity: 0.8; }
- .imdb-badge {
- display: inline-flex; align-items: center;
- background: #f5c518; color: #000;
- border-radius: 5px; font-size: 12px; font-weight: 800;
- padding: 5px 9px; cursor: pointer; border: none; outline: none;
- transition: opacity var(--transition);
- }
- .imdb-badge:hover { opacity: 0.8; }
- #movie-info-loading {
- display: none; flex-direction: column; align-items: center;
- justify-content: center; padding: 28px 0; gap: 10px; color: var(--text-sub);
- }
- #movie-info-loading.active { display: flex; }
- #movie-info-files { padding: 0 20px 48px; }
- #movie-info-wrong-wrap {
- display: none;
- padding: 10px 32px 0;
- }
- .reset-info-btn {
- background: none;
- border: 1px solid rgba(255,255,255,0.12);
- color: var(--text-sub);
- font-size: 11px; font-weight: 500;
- padding: 4px 12px;
- border-radius: 6px;
- cursor: pointer; outline: none;
- transition: border-color var(--transition), color var(--transition);
- }
- .reset-info-btn:hover { border-color: rgba(255,69,58,0.55); color: #ff453a; }
- @media (max-width: 600px) {
- #movie-info-hero { flex-direction: column; align-items: flex-start; padding: 56px 16px 20px; }
- #movie-info-poster-wrap { width: 90px; }
- #movie-info-title { font-size: 20px; }
- #movie-info-files { padding: 0 12px 48px; }
- }
- /* ─── Resume popup ───────────────────────────────────────────────────────────── */
- #resume-popup {
- display: none;
- position: absolute; bottom: 90px; right: 20px; z-index: 25;
- background: rgba(22,22,24,0.97); backdrop-filter: blur(16px);
- border-radius: 12px; padding: 16px 18px; min-width: 240px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.1);
- animation: slideUpPopup 0.2s ease;
- }
- #resume-popup.active { display: block; }
- @keyframes slideUpPopup {
- from { opacity: 0; transform: translateY(10px); }
- to { opacity: 1; transform: translateY(0); }
- }
- #resume-popup-title { font-size: 13px; font-weight: 600; margin-bottom: 4px; }
- #resume-popup-sub { font-size: 12px; color: var(--text-sub); margin-bottom: 12px; }
- #resume-popup-btns { display: flex; gap: 8px; }
- .resume-btn {
- flex: 1; padding: 8px; border: none; cursor: pointer;
- border-radius: 7px; font-size: 12px; font-weight: 600;
- outline: none; transition: opacity var(--transition);
- }
- .resume-btn:hover { opacity: 0.8; }
- #resume-btn-continue { background: var(--accent); color: #fff; }
- #resume-btn-restart { background: var(--surface2); color: var(--text); }
- /* Focus ring for TV remote navigation */
- .tv-focused {
- outline: 3px solid var(--accent) !important;
- outline-offset: 2px !important;
- }
- /* ─── Load More button ───────────────────────────────────────────────────────── */
- .load-more-wrap { text-align: center; padding: 16px 0 24px; }
- .load-more-btn {
- background: var(--surface2);
- border: 1px solid rgba(255,255,255,0.08); cursor: pointer;
- border-radius: 8px; color: var(--text);
- font-size: 13px; font-weight: 500; padding: 9px 28px;
- outline: none; transition: background var(--transition), box-shadow var(--transition);
- }
- .load-more-btn:hover { background: rgba(255,255,255,0.08); box-shadow: 0 0 0 1px var(--accent); }
- /* ─── Autoplay toggle (sidebar) ─────────────────────────────────────────────── */
- .autoplay-label {
- display: flex; align-items: center; gap: 5px;
- font-size: 11px; color: var(--text-sub);
- cursor: pointer; user-select: none;
- font-weight: 500;
- }
- .autoplay-label input[type="checkbox"] { display: none; }
- .autoplay-track {
- width: 30px; height: 17px;
- background: var(--surface2); border-radius: 9px;
- position: relative; flex-shrink: 0;
- transition: background 0.2s;
- }
- .autoplay-label input:checked + .autoplay-track { background: var(--accent2); }
- .autoplay-track::after {
- content: '';
- position: absolute; top: 2px; left: 2px;
- width: 13px; height: 13px;
- background: #fff; border-radius: 50%;
- transition: transform 0.2s;
- }
- .autoplay-label input:checked + .autoplay-track::after { transform: translateX(13px); }
- /* ─── Next-episode countdown ────────────────────────────────────────────────── */
- #next-countdown {
- display: none;
- position: absolute; bottom: 80px; right: 20px;
- background: rgba(20,20,20,0.92);
- backdrop-filter: blur(8px);
- border-radius: 10px; padding: 12px 16px;
- min-width: 210px; z-index: 20;
- }
- #next-countdown-text { font-size: 13px; color: var(--text-sub); margin-bottom: 8px; }
- #next-countdown-track {
- height: 4px; background: var(--surface2);
- border-radius: 4px; margin-bottom: 8px; overflow: hidden;
- }
- #next-countdown-bar { height: 100%; background: var(--accent); border-radius: 4px; transition: width 1s linear; }
- #next-countdown-cancel {
- display: block; width: 100%; background: var(--surface2);
- border: none; cursor: pointer; border-radius: 6px;
- color: var(--text); font-size: 12px; padding: 5px; outline: none;
- transition: background var(--transition);
- }
- #next-countdown-cancel:hover { background: rgba(255,59,48,0.28); }
- /* ─── Playback settings popup (gear button) ──────────────────────────────────── */
- #settings-popup {
- display: none;
- position: absolute;
- right: 20px; bottom: 62px;
- z-index: 35;
- background: rgba(28,28,30,0.97);
- backdrop-filter: blur(16px);
- -webkit-backdrop-filter: blur(16px);
- border-radius: 10px;
- padding: 6px 0;
- width: 236px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
- color: var(--text);
- user-select: none;
- overflow-y: auto;
- max-height: 320px;
- }
- #settings-popup.active { display: block; }
- #settings-popup::-webkit-scrollbar,
- #subtitle-popup::-webkit-scrollbar { width: 8px; }
- #settings-popup::-webkit-scrollbar-track,
- #subtitle-popup::-webkit-scrollbar-track { background: transparent; }
- #settings-popup::-webkit-scrollbar-thumb,
- #subtitle-popup::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.18); border-radius: 4px; }
- #settings-popup::-webkit-scrollbar-thumb:hover,
- #subtitle-popup::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.3); }
- /* ─── Subtitle popup (dedicated CC button) ───────────────────────────────────── */
- #subtitle-popup {
- display: none;
- position: absolute;
- right: 20px; bottom: 62px;
- z-index: 35;
- background: rgba(28,28,30,0.97);
- backdrop-filter: blur(16px);
- -webkit-backdrop-filter: blur(16px);
- border-radius: 10px;
- padding: 4px 0;
- min-width: 220px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
- color: var(--text);
- user-select: none;
- overflow-y: auto;
- max-height: 320px;
- }
- #subtitle-popup.active { display: block; }
- .set-section { padding: 6px 14px 8px; }
- .set-section + .set-section { border-top: 1px solid rgba(255,255,255,0.08); }
- .set-head {
- display: flex; align-items: center; gap: 8px;
- font-size: 11px; font-weight: 600; letter-spacing: 0.3px;
- text-transform: uppercase; color: var(--text-sub);
- margin-bottom: 7px;
- }
- .set-head img { width: 14px; height: 14px; opacity: 0.7; display: block; }
- .set-seg {
- display: flex; background: var(--surface2);
- border-radius: 7px; padding: 2px; gap: 2px;
- }
- .set-seg-btn {
- flex: 1; padding: 5px 0; font-size: 12px; font-family: inherit;
- border: none; border-radius: 5px; cursor: pointer;
- background: transparent; color: var(--text-sub);
- transition: background 0.15s, color 0.15s; outline: none;
- }
- .set-seg-btn:hover { color: var(--text); }
- .set-seg-btn.active { background: var(--surface); color: var(--text); }
- .speed-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; }
- .speed-btn {
- padding: 5px 0; font-size: 12px; font-family: inherit;
- border: none; border-radius: 5px; cursor: pointer;
- background: var(--surface2); color: var(--text-sub);
- transition: background 0.15s, color 0.15s; outline: none;
- }
- .speed-btn:hover { color: var(--text); }
- .speed-btn.active { background: var(--accent); color: #fff; font-weight: 600; }
- .set-link {
- display: flex; align-items: center; gap: 9px;
- padding: 8px 14px; font-size: 13px; cursor: pointer;
- color: var(--text); transition: background var(--transition);
- }
- .set-link:hover { background: rgba(255,255,255,0.08); }
- .set-link img { width: 15px; height: 15px; opacity: 0.8; display: block; }
- /* ─── Player context menu ────────────────────────────────────────────────────── */
- #player-ctx {
- display: none;
- position: absolute;
- z-index: 30;
- background: rgba(28,28,30,0.97);
- backdrop-filter: blur(16px);
- -webkit-backdrop-filter: blur(16px);
- border-radius: 10px;
- padding: 4px 0;
- min-width: 192px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
- user-select: none;
- }
- .ctx-item {
- padding: 9px 14px;
- font-size: 13px;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 10px;
- color: var(--text);
- transition: background var(--transition);
- }
- .ctx-item:hover { background: rgba(255,255,255,0.08); }
- .ctx-item.ctx-active { color: var(--accent); }
- .ctx-item.ctx-disabled { opacity: 0.3; pointer-events: none; }
- .ctx-icon { width: 16px; text-align: center; flex-shrink: 0; font-style: normal; }
- img.ctx-icon { height: 16px; opacity: 0.85; display: block; }
- .ctx-divider { height: 1px; background: rgba(255,255,255,0.08); margin: 3px 0; }
- .ctx-has-sub { justify-content: space-between; position: relative; }
- .ctx-sub-arrow { font-style: normal; opacity: 0.55; font-size: 15px; }
- /* Subtitle submenu — positioned relative to the parent .ctx-has-sub item */
- #ctx-subtitle-sub {
- display: none;
- position: absolute;
- top: 0;
- left: 100%;
- margin-left: 0;
- background: rgba(28,28,30,0.97);
- backdrop-filter: blur(16px);
- -webkit-backdrop-filter: blur(16px);
- border-radius: 10px;
- padding: 4px 0;
- min-width: 200px;
- box-shadow: 0 4px 24px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08);
- z-index: 32;
- overflow-y: auto;
- max-height: 320px;
- }
- #ctx-subtitle-sub::-webkit-scrollbar { width: 8px; }
- #ctx-subtitle-sub::-webkit-scrollbar-track { background: transparent; }
- #ctx-subtitle-sub::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.18); border-radius: 4px; }
- #ctx-subtitle-sub::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.3); }
- /* Subtitle overlay */
- #subtitle-display {
- display: none;
- position: absolute;
- bottom: 72px;
- left: 50%;
- transform: translateX(-50%);
- width: 90%;
- text-align: center;
- pointer-events: none; /* z-index deliberately unset, see #ass-overlay */
- color: #fff;
- font-size: 22px;
- font-weight: 500;
- line-height: 1.45;
- text-shadow:
- -1px -1px 0 #000, 1px -1px 0 #000,
- -1px 1px 0 #000, 1px 1px 0 #000,
- 0 2px 6px rgba(0,0,0,0.85);
- }
- /* ─── Subtitle settings modal ───────────────────────────────────────────────── */
- #subtitle-settings-modal {
- display: none;
- position: absolute;
- top: 50%; left: 50%;
- transform: translate(-50%, -50%);
- z-index: 40;
- background: rgba(18,18,20,0.97);
- backdrop-filter: blur(20px);
- -webkit-backdrop-filter: blur(20px);
- border-radius: 14px;
- padding: 20px 22px 18px;
- width: 340px;
- box-shadow: 0 8px 40px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.1);
- color: var(--text);
- }
- #subtitle-settings-modal h3 {
- font-size: 14px; font-weight: 600;
- margin-bottom: 14px;
- display: flex; align-items: center; justify-content: space-between;
- }
- #sset-close {
- background: none; border: none; cursor: pointer;
- color: var(--text-sub); font-size: 17px; line-height: 1; padding: 0; outline: none;
- }
- #sset-close img { width: 14px; height: 14px; display: block; opacity: 0.55; transition: opacity var(--transition); }
- #sset-close:hover img { opacity: 1; }
- .sset-row {
- display: flex; align-items: center; gap: 10px;
- padding: 8px 0;
- border-bottom: 1px solid rgba(255,255,255,0.05);
- font-size: 12px;
- }
- .sset-row:last-child { border-bottom: none; }
- .sset-label { color: var(--text-sub); flex-shrink: 0; width: 56px; }
- .sset-seg {
- display: flex; background: var(--surface2);
- border-radius: 7px; padding: 2px; gap: 2px; flex: 1;
- }
- .sset-seg-btn {
- flex: 1; padding: 4px 0; font-size: 12px; font-family: inherit;
- border: none; border-radius: 5px; cursor: pointer;
- background: transparent; color: var(--text-sub);
- transition: background 0.15s, color 0.15s;
- }
- .sset-seg-btn.active { background: var(--surface); color: var(--text); }
- #sset-size { flex: 1; accent-color: var(--accent); cursor: pointer; }
- #sset-size-val { color: var(--text-sub); font-size: 11px; min-width: 32px; text-align: right; }
- #sset-font {
- flex: 1; background: var(--surface2); color: var(--text);
- border: 1px solid rgba(255,255,255,0.08); border-radius: 7px;
- padding: 5px 8px; font-size: 12px; cursor: pointer; outline: none;
- appearance: auto;
- width: 100%;
- }
- .sset-colors { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; flex: 1; }
- .sset-color {
- width: 22px; height: 22px; border-radius: 50%;
- border: 2px solid transparent; outline: 2px solid transparent;
- cursor: pointer; padding: 0; flex-shrink: 0;
- transition: outline-color 0.15s, transform 0.1s;
- }
- .sset-color:hover { transform: scale(1.12); }
- .sset-color.active { outline-color: var(--text); transform: scale(1.15); }
- #sset-color-custom {
- width: 22px; height: 22px; border-radius: 50%;
- border: 2px solid rgba(255,255,255,0.2); padding: 0;
- cursor: pointer; background: transparent; flex-shrink: 0;
- }
- #sset-color-custom.active { border-color: var(--text); transform: scale(1.15); }
- #sset-preview {
- margin-top: 14px;
- background: rgba(0,0,0,0.65);
- border-radius: 8px;
- padding: 14px 12px;
- text-align: center;
- line-height: 1.4;
- }
- /* ─── Video info modal ───────────────────────────────────────────────────────── */
- #video-info-modal, #adv-settings-modal {
- display: none;
- position: absolute;
- top: 50%; left: 50%;
- transform: translate(-50%, -50%);
- z-index: 40;
- background: rgba(18,18,20,0.97);
- backdrop-filter: blur(20px);
- -webkit-backdrop-filter: blur(20px);
- border-radius: 14px;
- padding: 20px 22px 16px;
- width: 340px;
- box-shadow: 0 8px 40px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.1);
- }
- #video-info-modal h3, #adv-settings-modal h3 {
- font-size: 14px; font-weight: 600;
- margin-bottom: 12px;
- display: flex; align-items: center; justify-content: space-between;
- }
- #video-info-close, #adv-settings-close {
- background: none; border: none; cursor: pointer;
- color: var(--text-sub); font-size: 17px; line-height: 1; padding: 0; outline: none;
- }
- #video-info-close img, #adv-settings-close img { width: 14px; height: 14px; display: block; opacity: 0.55; transition: opacity var(--transition); }
- #video-info-close:hover img, #adv-settings-close:hover img { opacity: 1; }
- /* Advanced settings modal rows — same switch as the Settings tab, tighter */
- #adv-settings-modal { width: 380px; max-height: 70%; overflow-y: auto; }
- .adv-row {
- display: flex; align-items: center; gap: 14px;
- padding: 10px 0;
- border-top: 1px solid rgba(255,255,255,0.06);
- }
- .adv-row:first-child { border-top: none; }
- .adv-row-text { flex: 1; min-width: 0; }
- .adv-row-label { font-size: 13px; font-weight: 600; margin-bottom: 3px; }
- .adv-row-desc { font-size: 11px; color: var(--text-sub); line-height: 1.45; }
- #video-info-tabs {
- display: flex; gap: 3px;
- background: var(--surface2);
- border-radius: 8px;
- padding: 3px;
- margin-bottom: 12px;
- }
- .info-tab {
- flex: 1; text-align: center; padding: 5px 0;
- font-size: 12px; font-weight: 500;
- border-radius: 6px; cursor: pointer;
- color: var(--text-sub);
- transition: background var(--transition), color var(--transition);
- }
- .info-tab.active { background: var(--surface); color: var(--text); }
- .info-row {
- display: flex; gap: 8px;
- padding: 5px 0;
- border-bottom: 1px solid rgba(255,255,255,0.05);
- font-size: 12px;
- line-height: 1.4;
- }
- .info-row:last-child { border-bottom: none; }
- .info-label { color: var(--text-sub); flex-shrink: 0; width: 110px; }
- .info-value { color: var(--text); word-break: break-all; }
- /* ─── Arozcast cast ──────────────────────────────────────────────────────────── */
- #ctrl-cast img, #ctrl-cast-top img { opacity: 0.8; }
- #ctrl-cast.casting img, #ctrl-cast-top.casting img { filter: none; opacity: 1; }
- #ctrl-cast.casting, #ctrl-cast-top.casting { background: rgba(231,76,60,0.25); }
- #cast-modal {
- display: none;
- position: fixed; inset: 0; z-index: 9999;
- background: rgba(0,0,0,0.65);
- align-items: center; justify-content: center;
- }
- #cast-modal.active { display: flex; }
- .cast-dialog {
- background: var(--surface);
- border-radius: var(--radius);
- padding: 1.4em 1.8em;
- min-width: 260px;
- color: var(--text);
- font-family: inherit;
- box-shadow: 0 8px 32px rgba(0,0,0,0.6);
- }
- .cast-dialog h4 { margin: 0 0 0.9em; font-size: 1em; font-weight: 600; }
- .cast-dialog input[type=text] {
- width: 100%; padding: 0.45em 0.7em;
- border-radius: 8px; border: 1px solid rgba(255,255,255,0.12);
- background: var(--surface2); color: var(--text);
- font-size: 1.5em; letter-spacing: 0.35em; text-align: center;
- box-sizing: border-box; margin-bottom: 0.7em; outline: none;
- }
- .cast-dialog input[type=text]:focus { border-color: var(--accent); }
- .cast-err { color: #e74c3c; font-size: 0.82em; min-height: 1.2em; margin-bottom: 0.5em; }
- .cast-status-line { font-size: 0.85em; color: var(--text-sub); margin-bottom: 0.7em; }
- .cast-actions { display: flex; gap: 0.5em; justify-content: flex-end; }
- .cast-actions button {
- padding: 0.4em 1em; border-radius: 8px; border: none;
- cursor: pointer; font-size: 0.88em; font-family: inherit;
- }
- .btn-cast-connect { background: var(--accent); color: #fff; }
- .btn-cast-cancel { background: var(--surface2); color: var(--text-sub); }
- .btn-cast-disc { background: #444; color: var(--text); }
- </style>
- </head>
- <body>
- <div id="app">
- <!-- ─ Loading overlay ─────────────────────────────────────────────────── -->
- <div id="loading-overlay">
- <div class="spinner"></div>
- <span>Loading library…</span>
- </div>
- <!-- ─ Top bar ─────────────────────────────────────────────────────────── -->
- <div id="topbar">
- <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>
- <div id="mode-tabs">
- <button class="mode-tab active" id="tab-library" onclick="switchTab('library')">Library</button>
- <button class="mode-tab" id="tab-folder" onclick="switchTab('folder')">Browse</button>
- <button class="mode-tab" id="tab-settings" onclick="switchTab('settings')">Settings</button>
- </div>
- <div id="search-wrap">
- <input id="search-input" type="text" placeholder="Search…" autocomplete="off">
- </div>
- </div>
- <!-- ═══════════════ LIBRARY VIEW ═══════════════════════════════════════ -->
- <div id="view-library" class="view active">
- <div id="library-status-bar">
- <div class="spinner-sm" id="library-spinner"></div>
- <span id="library-status-text"></span>
- <button id="library-refresh-btn" onclick="refreshLibrary()" style="display:none">Refresh</button>
- </div>
- <div id="library-scroll">
- <div id="no-content">
- <div class="icon"><img src="img/icons/movie_white.svg" alt=""></div>
- <div>No videos found. Place your videos in a <strong>Video/</strong> folder on any storage.</div>
- </div>
- <div id="movies-section" style="display:none">
- <div class="section-title">Movies</div>
- <div id="movies-grid" class="album-grid"></div>
- <div class="load-more-wrap"><button class="load-more-btn" id="movies-load-more" style="display:none" onclick="loadMoreSection('movies')">Load more</button></div>
- </div>
- <div id="collections-section" style="display:none">
- <div class="section-title">Collections</div>
- <div id="collections-grid" class="album-grid"></div>
- <div class="load-more-wrap"><button class="load-more-btn" id="collections-load-more" style="display:none" onclick="loadMoreSection('collections')">Load more</button></div>
- </div>
- <div id="series-section" style="display:none">
- <div class="section-title">TV / Shows</div>
- <div id="series-grid" class="album-grid"></div>
- <div class="load-more-wrap"><button class="load-more-btn" id="shows-load-more" style="display:none" onclick="loadMoreSection('shows')">Load more</button></div>
- </div>
- <div id="anime-section" style="display:none">
- <div class="section-title">Anime</div>
- <div id="anime-grid" class="album-grid"></div>
- <div class="load-more-wrap"><button class="load-more-btn" id="anime-load-more" style="display:none" onclick="loadMoreSection('anime')">Load more</button></div>
- </div>
- <div id="shorts-section" style="display:none">
- <div class="section-title">Shorts</div>
- <div id="shorts-grid" class="album-grid"></div>
- <div class="load-more-wrap"><button class="load-more-btn" id="shorts-load-more" style="display:none" onclick="loadMoreSection('shorts')">Load more</button></div>
- </div>
- </div>
- </div>
- <!-- ═══════════════ DETAIL VIEW ════════════════════════════════════════ -->
- <div id="view-detail" class="view">
- <div id="detail-hero">
- <div id="detail-hero-bg"></div>
- <div id="detail-hero-content">
- <div id="detail-poster"><div class="poster-placeholder"><img src="img/icons/movie_white.svg" alt=""></div></div>
- <div id="detail-meta">
- <div id="detail-title">Album Title</div>
- <div id="detail-subtitle">0 episodes</div>
- <div id="detail-actions">
- <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>
- <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>
- </div>
- </div>
- </div>
- </div>
- <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>
- <div id="season-tabs"></div>
- <div id="episode-scroll">
- <div id="episode-list"></div>
- </div>
- </div>
- <!-- ═══════════════ MOVIE INFO VIEW ══════════════════════════════════════ -->
- <div id="view-movie-info" class="view">
- <div id="movie-info-backdrop"></div>
- <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>
- <div id="movie-info-scroll">
- <div id="movie-info-hero">
- <div id="movie-info-poster-wrap">
- <img id="movie-info-poster-img" src="img/thumbnail.png" alt="">
- </div>
- <div id="movie-info-meta">
- <div id="movie-info-title"></div>
- <div id="movie-info-filename"></div>
- <div id="movie-info-year"></div>
- <div id="movie-info-cast"></div>
- <div id="movie-info-actions">
- <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>
- <button class="btn btn-secondary" id="movie-info-fm-btn">Open in Files</button>
- <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>
- <button class="imdb-badge" id="movie-info-imdb-btn" style="display:none">IMDb</button>
- </div>
- </div>
- </div>
- <div id="movie-info-wrong-wrap">
- <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>
- </div>
- <div id="movie-info-loading"><div class="spinner"></div><span>Loading info…</span></div>
- <div id="movie-info-files" style="display:none">
- <div class="section-title" style="font-size:16px;margin:16px 20px 10px;">Files</div>
- <div id="movie-info-episode-list"></div>
- </div>
- </div>
- </div>
- <!-- ═══════════════ FOLDER VIEW ════════════════════════════════════════ -->
- <div id="view-folder" class="view">
- <div id="folder-nav-bar">
- <div id="folder-breadcrumb"></div>
- </div>
- <div id="folder-scroll">
- <div id="folder-loading"><div class="spinner"></div><span>Loading…</span></div>
- <div id="folder-empty"></div>
- <div id="folder-section-dirs" style="display:none">
- <div class="section-title">Folders</div>
- <div id="folder-dirs-grid" class="album-grid"></div>
- </div>
- <div id="folder-section-vids" style="display:none">
- <div class="section-title">Videos</div>
- <div id="folder-vids-grid" class="album-grid"></div>
- </div>
- </div>
- </div>
- <!-- ═══════════════ SETTINGS VIEW ══════════════════════════════════════ -->
- <div id="view-settings" class="view">
- <div id="settings-scroll">
- <div class="settings-card">
- <div class="settings-card-title">Indexing</div>
- <div class="settings-row">
- <div class="settings-row-text">
- <div class="settings-row-label">Auto indexing</div>
- <div class="settings-row-desc">
- Scan your storage for new videos automatically when the app opens.
- Turn this off if scanning is slow on large libraries — you can still
- scan on demand below.
- </div>
- </div>
- <label class="settings-switch" title="Toggle auto indexing">
- <input type="checkbox" id="setting-auto-index">
- <span class="settings-switch-track"></span>
- </label>
- </div>
- <div class="settings-row">
- <div class="settings-row-text">
- <div class="settings-row-label">Index location</div>
- <div class="settings-row-desc"><code>user:/.appdata/Movie/library_cache.json</code></div>
- </div>
- </div>
- </div>
- <div class="settings-card">
- <div class="settings-card-title">Index status</div>
- <div id="settings-stats-grid" class="stats-grid">
- <div class="stat-box"><div class="stat-value" id="stat-size">–</div><div class="stat-label">Index file size</div></div>
- <div class="stat-box"><div class="stat-value" id="stat-albums">–</div><div class="stat-label">Titles indexed</div></div>
- <div class="stat-box"><div class="stat-value" id="stat-videos">–</div><div class="stat-label">Video files indexed</div></div>
- <div class="stat-box"><div class="stat-value" id="stat-roots">–</div><div class="stat-label">Storage roots scanned</div></div>
- </div>
- <div id="settings-breakdown" class="settings-breakdown"></div>
- <div class="settings-meta" id="settings-last-scan">Last scan: never</div>
- </div>
- <div class="settings-card">
- <div class="settings-card-title">Maintenance</div>
- <div class="settings-row">
- <div class="settings-row-text">
- <div class="settings-row-label">Rescan library</div>
- <div class="settings-row-desc">Walk every storage root again and rebuild the index from scratch.</div>
- </div>
- <button class="btn btn-primary settings-btn" id="settings-scan-btn">Scan now</button>
- </div>
- <div class="settings-row">
- <div class="settings-row-text">
- <div class="settings-row-label">Clear index</div>
- <div class="settings-row-desc">
- Delete the cached scan result. Your video files are never touched —
- only the index is removed.
- </div>
- </div>
- <button class="btn btn-secondary settings-btn settings-btn-danger" id="settings-clear-btn">Clear index</button>
- </div>
- <div id="settings-progress" class="settings-progress">
- <div class="spinner-sm"></div><span id="settings-progress-text">Scanning…</span>
- </div>
- </div>
- </div>
- </div>
- <!-- ═══════════════ PLAYER VIEW ════════════════════════════════════════ -->
- <div id="view-player" class="view">
- <div id="video-container">
- <div id="player-topbar">
- <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>
- <span id="topbar-title"></span>
- <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>
- <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>
- </div>
- <video id="main-video" preload="metadata"></video>
- <!-- Frozen last frame + spinner, shown while a transcode seek re-buffers.
- Must stay directly after <video> — stacking relies on DOM order. -->
- <canvas id="seek-freeze"></canvas>
- <div id="seek-spinner">
- <div class="seek-spinner-box">
- <div class="spinner"></div>
- <span>Buffering…</span>
- </div>
- </div>
- <!-- Styled ASS/SSA subtitles are drawn here, sized to the video's
- displayed rectangle. The plain #subtitle-display below is used
- for SubRip tracks. -->
- <div id="ass-overlay"></div>
- <div id="subtitle-display"></div>
- <!-- Centre play/pause flash indicator -->
- <div id="play-flash"><img id="play-flash-icon" src="img/icons/play_white.svg" alt=""></div>
- <!-- Resume-from-last-position popup -->
- <div id="resume-popup">
- <div id="resume-popup-title">Resume playback?</div>
- <div id="resume-popup-sub"></div>
- <div id="resume-popup-btns">
- <button class="resume-btn" id="resume-btn-continue">Resume</button>
- <button class="resume-btn" id="resume-btn-restart">Start over</button>
- </div>
- </div>
- <!-- Auto-play countdown -->
- <div id="next-countdown">
- <div id="next-countdown-text">Next episode in <span id="countdown-num">5</span>s…</div>
- <div id="next-countdown-track"><div id="next-countdown-bar" style="width:100%"></div></div>
- <button id="next-countdown-cancel" onclick="cancelCountdown()">Cancel</button>
- </div>
- <!-- Player context menu -->
- <div id="player-ctx">
- <div class="ctx-item" id="ctx-play"><img class="ctx-icon" src="img/icons/play_white.svg" alt="">Play</div>
- <div class="ctx-item" id="ctx-pause"><img class="ctx-icon" src="img/icons/pause_white.svg" alt="">Pause</div>
- <div class="ctx-divider"></div>
- <div class="ctx-item" id="ctx-prev"><img class="ctx-icon" src="img/icons/skip_previous_white.svg" alt="">Previous</div>
- <div class="ctx-item" id="ctx-next"><img class="ctx-icon" src="img/icons/skip_next_white.svg" alt="">Next</div>
- <div class="ctx-divider"></div>
- <div class="ctx-item" id="ctx-repeat"><img class="ctx-icon" src="img/icons/repeat_white.svg" alt="">Repeat: Off</div>
- <div class="ctx-divider"></div>
- <div class="ctx-item ctx-has-sub" id="ctx-subtitle-parent">
- <span><i class="ctx-icon" style="display:inline-block">CC</i>Subtitles</span>
- <i class="ctx-sub-arrow">›</i>
- <!-- Subtitle submenu — child of parent item for easy relative positioning -->
- <div id="ctx-subtitle-sub">
- <div class="ctx-item ctx-active" id="ctx-sub-disable"><i class="ctx-icon">✓</i>Disable</div>
- <div class="ctx-divider"></div>
- <div class="ctx-item" id="ctx-sub-load"><i class="ctx-icon">+</i>Load SRT file…</div>
- </div>
- </div>
- <div class="ctx-divider"></div>
- <div class="ctx-item" id="ctx-subtitle-settings"><img class="ctx-icon" src="img/icons/settings_white.svg" alt="">Subtitle Settings</div>
- <div class="ctx-item" id="ctx-props">Video Properties</div>
- </div>
- <!-- Playback / subtitle settings modal -->
- <div id="subtitle-settings-modal">
- <h3>Subtitle Settings<button id="sset-close" title="Close"><img src="img/icons/close_white.svg" alt=""></button></h3>
- <div class="sset-row">
- <span class="sset-label">Position</span>
- <div class="sset-seg">
- <button class="sset-seg-btn active" data-val="bottom">Bottom</button>
- <button class="sset-seg-btn" data-val="top">Top</button>
- </div>
- </div>
- <div class="sset-row">
- <span class="sset-label">Size</span>
- <input type="range" id="sset-size" min="14" max="52" step="1" value="22">
- <span id="sset-size-val">22px</span>
- </div>
- <div class="sset-row">
- <span class="sset-label">Font</span>
- <select id="sset-font">
- <option value="system-ui, sans-serif">System Default</option>
- <option value="Arial, sans-serif">Arial</option>
- <option value="'Helvetica Neue', Helvetica, sans-serif">Helvetica</option>
- <option value="Georgia, serif">Georgia</option>
- <option value="'Times New Roman', Times, serif">Times New Roman</option>
- <option value="'Courier New', Courier, monospace">Courier New</option>
- <option value="Verdana, sans-serif">Verdana</option>
- <option value="'Trebuchet MS', sans-serif">Trebuchet MS</option>
- <option value="Impact, fantasy">Impact</option>
- </select>
- </div>
- <div class="sset-row">
- <span class="sset-label">Color</span>
- <div class="sset-colors">
- <button class="sset-color active" data-color="#ffffff" style="background:#ffffff" title="White"></button>
- <button class="sset-color" data-color="#ffff00" style="background:#ffff00" title="Yellow"></button>
- <button class="sset-color" data-color="#00ffff" style="background:#00ffff" title="Cyan"></button>
- <button class="sset-color" data-color="#00ff88" style="background:#00ff88" title="Green"></button>
- <button class="sset-color" data-color="#ff8800" style="background:#ff8800" title="Orange"></button>
- <input type="color" id="sset-color-custom" value="#ffffff" title="Custom color">
- </div>
- </div>
- <div id="sset-preview">Sample subtitle text</div>
- </div>
- <!-- Video info / stats modal -->
- <div id="video-info-modal">
- <h3><span id="video-info-title">Video Properties</span><button id="video-info-close" title="Close" onclick="closeVideoInfo()"><img src="img/icons/close_white.svg" alt=""></button></h3>
- <div id="video-info-tabs">
- <div class="info-tab active" onclick="showInfoTab('props')">Properties</div>
- <div class="info-tab" onclick="showInfoTab('stats')">Stats</div>
- </div>
- <div id="video-info-body"></div>
- </div>
- <!-- Advanced settings modal -->
- <div id="adv-settings-modal">
- <h3><span>Advanced Settings</span><button id="adv-settings-close" title="Close" onclick="closeAdvancedSettings()"><img src="img/icons/close_white.svg" alt=""></button></h3>
- <div id="adv-settings-body">
- <div class="adv-row">
- <div class="adv-row-text">
- <div class="adv-row-label">Disable playlist show when change episode</div>
- <div class="adv-row-desc">
- Keep the playlist hidden when you skip to another episode. When this is
- off, a hidden playlist peeks open for 2 seconds and closes again.
- </div>
- </div>
- <label class="settings-switch" title="Disable playlist show when change episode">
- <input type="checkbox" id="adv-no-playlist-peek">
- <span class="settings-switch-track"></span>
- </label>
- </div>
- </div>
- </div>
- <!-- Playback settings popup -->
- <div id="settings-popup">
- <div class="set-section">
- <div class="set-head"><img src="img/icons/repeat_white.svg" alt="">Repeat</div>
- <div class="set-seg" id="set-repeat-seg">
- <button class="set-seg-btn active" data-repeat="off">Off</button>
- <button class="set-seg-btn" data-repeat="one">Repeat one</button>
- </div>
- </div>
- <div class="set-section">
- <div class="set-head"><img src="img/icons/play_white.svg" alt="">Playback speed</div>
- <div class="speed-grid" id="set-speed-grid">
- <button class="speed-btn" data-speed="0.5">0.5×</button>
- <button class="speed-btn active" data-speed="1">1×</button>
- <button class="speed-btn" data-speed="1.2">1.2×</button>
- <button class="speed-btn" data-speed="1.5">1.5×</button>
- <button class="speed-btn" data-speed="2">2×</button>
- </div>
- </div>
- <div class="set-section">
- <div class="set-head"><img src="img/icons/volume_white.svg" alt="">Volume bar</div>
- <div class="set-seg" id="set-volbar-seg">
- <button class="set-seg-btn active" data-volbar="auto">Auto</button>
- <button class="set-seg-btn" data-volbar="always">Always show</button>
- </div>
- </div>
- <div class="set-section">
- <div class="set-head"><img src="img/icons/movie_white.svg" alt="">Streaming mode</div>
- <div class="set-seg" id="set-stream-seg">
- <button class="set-seg-btn active" data-stream="auto">Auto</button>
- <button class="set-seg-btn" data-stream="mp4">MP4</button>
- <button class="set-seg-btn" data-stream="hls">HLS</button>
- </div>
- </div>
- <div class="set-section" style="padding-left:0;padding-right:0;padding-bottom:2px;">
- <div class="set-link" id="set-video-props">
- <img src="img/icons/menu_white.svg" alt="">Video properties
- </div>
- <div class="set-link" id="set-advanced">
- <img src="img/icons/settings_white.svg" alt="">Advanced settings
- </div>
- </div>
- </div>
- <!-- Subtitle popup (dedicated CC button) -->
- <div id="subtitle-popup">
- <div class="ctx-item ctx-active" id="sub-pop-disable"><i class="ctx-icon">✓</i>Disable</div>
- <div class="ctx-divider"></div>
- <div class="ctx-item" id="sub-pop-load"><i class="ctx-icon">+</i>Load SRT file…</div>
- <div class="ctx-divider"></div>
- <div class="set-link" id="sub-pop-settings">
- <img src="img/icons/settings_white.svg" alt="">Subtitle settings
- </div>
- </div>
- <!-- Custom controls -->
- <div id="video-controls">
- <div id="progress-wrap">
- <div id="progress-bar" style="width:0%"></div>
- <div id="progress-thumb" style="left:0%"></div>
- <div id="scrub-preview">
- <div id="scrub-preview-thumb"></div>
- <div id="scrub-preview-time">0:00</div>
- </div>
- </div>
- <div id="controls-row">
- <button class="ctrl-btn" id="ctrl-prev" title="Previous (←)"><img src="img/icons/skip_previous_white.svg" alt=""></button>
- <button class="ctrl-btn" id="ctrl-play" title="Play/Pause (Space)"><img id="play-icon" src="img/icons/play_white.svg" alt=""></button>
- <button class="ctrl-btn" id="ctrl-next" title="Next (→)"><img src="img/icons/skip_next_white.svg" alt=""></button>
- <div id="volume-wrap">
- <button class="ctrl-btn" id="ctrl-mute" title="Mute (M)"><img id="mute-icon" src="img/icons/volume_white.svg" alt=""></button>
- <input id="volume-slider" type="range" min="0" max="1" step="0.05" value="1">
- </div>
- <span id="time-display">0:00 / 0:00</span>
- <span id="now-playing-title"></span>
- <button class="ctrl-btn" id="ctrl-list" title="Episode list (L)"><img src="img/icons/menu_white.svg" alt=""></button>
- <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>
- <button class="ctrl-btn" id="ctrl-subtitle" title="Subtitles"><span class="ctrl-cc-icon">CC</span></button>
- <button class="ctrl-btn" id="ctrl-settings" title="Playback settings (S)"><img src="img/icons/settings_white.svg" alt=""></button>
- <button class="ctrl-btn" id="ctrl-fs" title="Fullscreen (F)"><img src="img/icons/fullscreen_white.svg" alt=""></button>
- </div>
- </div>
- </div>
- <!-- Sidebar playlist -->
- <div id="playlist-sidebar">
- <div id="sidebar-header">
- <span>Playlist</span>
- <label class="autoplay-label" title="Auto-play next episode">
- <input type="checkbox" id="autoplay-check">
- <span class="autoplay-track"></span>
- <span>Auto</span>
- </label>
- <button id="sidebar-close" onclick="toggleSidebar()"><img style="width: 16px;" src="img/icons/close_white.svg" alt=""></button>
- </div>
- <div id="sidebar-list"></div>
- </div>
- </div>
- </div>
- <!-- Toast -->
- <div id="toast"></div>
- <!-- Arozcast cast modal -->
- <div id="cast-modal">
- <div class="cast-dialog">
- <h4>Cast to Arozcast</h4>
- <div id="cast-status-line" class="cast-status-line" style="display:none;"></div>
- <input type="text" id="cast-code-input" maxlength="4" placeholder="1234"
- oninput="this.value=this.value.replace(/\D/g,'')"
- onkeydown="if(event.key==='Enter') connectCast()">
- <div id="cast-err" class="cast-err"></div>
- <div class="cast-actions">
- <button class="btn-cast-cancel" onclick="closeCastDialog()">Cancel</button>
- <button class="btn-cast-disc" id="cast-disc-btn" style="display:none;" onclick="disconnectCast()">Disconnect</button>
- <button class="btn-cast-connect" id="cast-conn-btn" onclick="connectCast()">Connect</button>
- </div>
- </div>
- </div>
- <!-- ═══════════════ JAVASCRIPT ════════════════════════════════════════════════ -->
- <script>
- // ─── All configurable paths come from backend/common.js ──────────────────────
- // (SCRIPT_GET_LIBRARY, SCRIPT_GET_EPISODES, SCRIPT_GET_THUMBNAIL, MEDIA_API)
- // ─── Library cache ────────────────────────────────────────────────────────────
- // Cache is stored server-side (user:/.appdata/Movie/library_cache.json)
- // so it is shared across devices for the same user account.
- var libraryNeedsRedraw = false; // set when bg-refresh finishes outside the library view
- // ─── App state ────────────────────────────────────────────────────────────────
- var library = []; // full album array from server
- var currentAlbum = null; // album object currently shown in detail view
- var currentSeason = null; // season object currently active
- var currentEpisodes = []; // flat episode array for current season/album
- var playingIndex = -1; // index in currentEpisodes being played
- // TV-remote focus management
- var focusMode = false; // set to true when arrow-key pressed
- var focusedEl = null;
- // Controls auto-hide timer
- var controlsTimer = null;
- // Library pagination
- var PAGE_SIZE = 24;
- var moviesData = [];
- var collectionsData = [];
- var showsData = [];
- var shortsData = [];
- var animeData = [];
- var moviesShown = 0;
- var collectionsShown = 0;
- var showsShown = 0;
- var shortsShown = 0;
- var animeShown = 0;
- // Auto-play between episodes
- var autoplayEnabled = localStorage.getItem('movie_autoplay') !== '0'; // on by default
- var countdownTimer = null;
- // Single-repeat
- var repeatSingle = (localStorage.getItem('movie_repeat_one') === '1');
- // Playback speed (persisted, reapplied whenever a new source loads)
- // Snapped to the nearest preset on load: an earlier build let this be dragged
- // to any value, and the popup highlights presets only.
- // The preset rates offered in the settings popup. Declared here rather than
- // beside setPlaybackSpeed because the initialiser below runs on load, and a
- // `var` further down the file would still be undefined at that point.
- var PLAYBACK_SPEEDS = [0.5, 1, 1.2, 1.5, 2];
- var playbackSpeed = nearestPlaybackSpeed(localStorage.getItem('movie_playback_speed') || '1');
- // Force the volume slider visible even on portrait phones (see the media query)
- var alwaysShowVolumeBar = (localStorage.getItem('movie_always_volume_bar') === '1');
- // Indexing (Settings tab). Auto indexing governs the automatic scan on app open;
- // manual scans from the Settings tab always work regardless.
- var autoIndexEnabled = (localStorage.getItem('movie_auto_index') !== '0'); // on by default
- var libraryCacheTs = 0; // timestamp of the index currently in memory
- // Set once the user manually opens/closes the playlist, so orientation changes
- // stop auto-managing it until the next playback starts.
- var playlistUserToggled = false;
- // Skipping between episodes must not reshuffle the layout. A playlist that is
- // already open stays open; a closed one only peeks open for this long before
- // tucking itself away again (unless the user disabled the peek entirely).
- var PLAYLIST_PEEK_MS = 2000;
- var playlistPeekTimer = null;
- var disablePlaylistPeek = (localStorage.getItem('movie_no_playlist_peek') === '1');
- // ─── Arozcast cast state ──────────────────────────────────────────────────────
- var castWs = null;
- var castCode = null;
- var castMode = false;
- var castPingTimer = null;
- var castWatchTimer = null;
- var castLastSeen = 0;
- var castCurrentTime = 0;
- var castDuration = 0;
- var castIsPlaying = false;
- var castReconnectTimer = null; // setTimeout handle for next reconnect attempt
- var castReconnectCount = 0; // number of attempts made so far
- var castPendingCode = null; // room code kept alive during reconnect
- function _castConnected() {
- return castWs !== null && castWs.readyState === WebSocket.OPEN;
- }
- function _castSend(topic, payload) {
- if (!_castConnected()) { return; }
- castWs.send(JSON.stringify({ topic: topic, payload: payload || {} }));
- }
- function openCastDialog() {
- var $inp = $('#cast-code-input');
- var $stat = $('#cast-status-line');
- var $err = $('#cast-err');
- $('#cast-err').text('');
- if (_castConnected()) {
- $inp.hide();
- $stat.show().text('Casting to room ' + castCode);
- $('#cast-conn-btn').hide();
- $('#cast-disc-btn').show();
- } else {
- $inp.show().val('');
- $stat.hide();
- $('#cast-conn-btn').show();
- $('#cast-disc-btn').hide();
- }
- $('#cast-modal').addClass('active');
- if ($inp.is(':visible')) { setTimeout(function(){ $inp.focus(); }, 50); }
- }
- function closeCastDialog() { $('#cast-modal').removeClass('active'); }
- function connectCast() {
- var code = $('#cast-code-input').val().trim();
- if (code.length !== 4) { $('#cast-err').text('Enter a 4-digit room code.'); return; }
- $('#cast-err').text('');
- fetch(ao_root + 'api/arozcast/ping?code=' + code)
- .then(function(r) { return r.json(); })
- .then(function(data) {
- if (!data.exists) { $('#cast-err').text('Room not found. Is Arozcast running?'); return; }
- if (castWs) { castWs.onclose = null; castWs.close(); castWs = null; }
- clearInterval(castPingTimer); clearInterval(castWatchTimer);
- // Cancel any pending auto-reconnect to the old room — user is opening a new session
- clearTimeout(castReconnectTimer); castReconnectTimer = null;
- castReconnectCount = 0; castPendingCode = null;
- // Signal other apps (Musicify, Photo) to yield the cast room
- try { new BroadcastChannel('arozcast').postMessage({ type: 'arozcast.takeover' }); } catch(e) {}
- castCode = code;
- var wsUrl = new URL(ao_root + 'api/arozcast/ws?code=' + code, window.location.href);
- wsUrl.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
- castWs = new WebSocket(wsUrl.toString());
- castWs.onopen = function() {
- castLastSeen = Date.now();
- castMode = true;
- castWs.send(JSON.stringify({ topic: 'peer.hello', payload: {} }));
- var vid = document.getElementById('main-video');
- // Load current episode on Arozcast; stop local playback
- if (playingIndex >= 0 && currentEpisodes[playingIndex]) {
- var ep = currentEpisodes[playingIndex];
- var ext = ep.ext ? ep.ext.toLowerCase().replace(/^\./, '') : '';
- // Always hand the receiver the MP4 stream: it is a separate
- // client whose HLS support we cannot probe from here, and
- // this browser's streaming-mode preference says nothing
- // about it.
- var src = isWebPlayable(ext)
- ? MEDIA_API + '?file=' + encodeURIComponent(ep.filepath)
- : TRANSCODE_API + '?file=' + encodeURIComponent(ep.filepath);
- _castSend('media.load', {
- filepath: ep.filepath, name: ep.name, type: 'video',
- src: src, startTime: (isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime) || 0
- });
- // Volume after load, before play — ensures it overrides any default
- // the Arozcast side might apply during media initialisation.
- _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted });
- _castSend(vid.paused ? 'media.pause' : 'media.play', {});
- // Stop local video to avoid dual transcoding
- vid.pause();
- vid.removeAttribute('src');
- }
- castPingTimer = setInterval(function() { _castSend('peer.heartbeat', {}); }, 5000);
- castWatchTimer = setInterval(function() {
- if (Date.now() - castLastSeen > 12000 && castWs) { castWs.close(); }
- }, 4000);
- $('#ctrl-cast, #ctrl-cast-top').addClass('casting');
- closeCastDialog();
- showToast('Casting to room ' + code);
- };
- castWs.onmessage = function(evt) {
- castLastSeen = Date.now();
- try { _handleCastMessage(JSON.parse(evt.data)); } catch(e) {}
- };
- castWs.onclose = function() {
- clearInterval(castPingTimer); clearInterval(castWatchTimer);
- castPingTimer = castWatchTimer = null;
- var wasActive = castMode;
- var savedCode = castCode;
- castMode = false; castCode = null; castWs = null;
- $('#ctrl-cast, #ctrl-cast-top').removeClass('casting');
- if (wasActive) { _startCastReconnect(savedCode); }
- };
- castWs.onerror = function() {
- $('#cast-err').text('Connection error.');
- openCastDialog();
- };
- })
- .catch(function() { $('#cast-err').text('Network error.'); });
- }
- function disconnectCast() {
- // Cancel any pending auto-reconnect before tearing down
- clearTimeout(castReconnectTimer); castReconnectTimer = null;
- castReconnectCount = 0; castPendingCode = null;
- if (_castConnected()) { _castSend('media.stop', {}); }
- if (castWs) { castWs.onclose = null; castWs.close(); castWs = null; }
- clearInterval(castPingTimer); clearInterval(castWatchTimer);
- castPingTimer = castWatchTimer = null;
- castMode = false; castCode = null;
- $('#ctrl-cast, #ctrl-cast-top').removeClass('casting');
- closeCastDialog();
- _castResumeLocally();
- }
- function _castResumeLocally() {
- if (playingIndex < 0 || !currentEpisodes || !currentEpisodes[playingIndex]) { return; }
- var ep = currentEpisodes[playingIndex];
- var pos = castCurrentTime;
- var vid = document.getElementById('main-video');
- if (isTranscodedVideo && pos > 0) {
- // Restart the transcode at the cast position, on whichever transport
- // this browser is using
- transcodeSeekOffset = pos;
- attachTranscodeStream(vid, transcodeStreamURL(ep.filepath, pos));
- } else {
- var ext = ep.ext ? ep.ext.toLowerCase().replace(/^\./, '') : '';
- if (isWebPlayable(ext)) {
- vid.src = MEDIA_API + '?file=' + encodeURIComponent(ep.filepath);
- } else {
- attachTranscodeStream(vid, transcodeStreamURL(ep.filepath, 0));
- }
- if (pos > 0) {
- $(vid).one('loadedmetadata.castresume', function() { vid.currentTime = pos; });
- }
- }
- vid.load();
- $('#play-icon').attr('src', 'img/icons/play_white.svg');
- showToast('Arozcast disconnected — click play to resume');
- }
- // ── Arozcast auto-reconnect ───────────────────────────────────────────────────
- var _CAST_RECONNECT_DELAYS = [2000, 5000, 12000];
- function _startCastReconnect(code) {
- if (!code || castReconnectCount >= _CAST_RECONNECT_DELAYS.length) {
- if (castReconnectCount > 0) { _castResumeLocally(); }
- castReconnectCount = 0; castPendingCode = null;
- return;
- }
- castPendingCode = code;
- var delay = _CAST_RECONNECT_DELAYS[castReconnectCount++];
- clearTimeout(castReconnectTimer);
- castReconnectTimer = setTimeout(function() {
- castReconnectTimer = null;
- _attemptCastReconnect();
- }, delay);
- showToast('Arozcast disconnected — reconnecting…');
- }
- function _attemptCastReconnect() {
- if (!castPendingCode) return;
- var code = castPendingCode;
- var wsUrl = new URL(ao_root + 'api/arozcast/ws?code=' + code, window.location.href);
- wsUrl.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
- var ws = new WebSocket(wsUrl.toString());
- // If the socket doesn't open within 8 s, count as a failed attempt
- var openTimer = setTimeout(function() {
- ws.onopen = ws.onclose = ws.onerror = null; ws.close();
- _startCastReconnect(code);
- }, 8000);
- ws.onopen = function() { clearTimeout(openTimer); castPendingCode = null; _castDidReconnect(ws, code); };
- ws.onerror = function() {}; // let onclose handle it
- ws.onclose = function() { clearTimeout(openTimer); _startCastReconnect(code); };
- }
- function _castDidReconnect(ws, code) {
- castWs = ws; castCode = code; castMode = true; castLastSeen = Date.now();
- ws.onmessage = function(evt) {
- castLastSeen = Date.now();
- try { _handleCastMessage(JSON.parse(evt.data)); } catch(e) {}
- };
- ws.onclose = function() {
- clearInterval(castPingTimer); clearInterval(castWatchTimer);
- castPingTimer = castWatchTimer = null;
- var wasActive = castMode;
- var savedCode = castCode;
- castMode = false; castCode = null; castWs = null;
- $('#ctrl-cast, #ctrl-cast-top').removeClass('casting');
- if (wasActive) { _startCastReconnect(savedCode); }
- };
- // Re-announce presence and sync volume only — do NOT resend media.load.
- // Arozcast kept playing while the phone was asleep; its next status.update
- // will immediately sync castCurrentTime to the live remote position.
- _castSend('peer.hello', {});
- var vid = document.getElementById('main-video');
- _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted });
- castPingTimer = setInterval(function() { _castSend('peer.heartbeat', {}); }, 5000);
- castWatchTimer = setInterval(function() {
- if (Date.now() - castLastSeen > 12000 && castWs) { castWs.close(); }
- }, 4000);
- $('#ctrl-cast, #ctrl-cast-top').addClass('casting');
- showToast('Arozcast reconnected');
- }
- function _handleCastMessage(msg) {
- if (msg.topic === 'status.update') {
- castReconnectCount = 0; // receiver confirmed alive — reset retry counter
- castCurrentTime = msg.payload.currentTime || 0;
- castDuration = msg.payload.duration || 0;
- castIsPlaying = msg.payload.isPlaying || false;
- if (castDuration > 0) {
- var pct = (castCurrentTime / castDuration) * 100;
- $('#progress-bar').css('width', pct + '%');
- $('#progress-thumb').css('left', 'calc(' + pct + '% - 7px)');
- $('#time-display').text(formatTime(castCurrentTime) + ' / ' + formatTime(castDuration));
- }
- $('#play-icon').attr('src', castIsPlaying
- ? 'img/icons/pause_white.svg' : 'img/icons/play_white.svg');
- } else if (msg.topic === 'media.ended') {
- cancelCountdown();
- if (repeatSingle) {
- _castSend('media.seek', { time: 0 });
- _castSend('media.play', {});
- } else if (playingIndex < currentEpisodes.length - 1 && autoplayEnabled) {
- startNextCountdown();
- } else {
- castIsPlaying = false;
- $('#play-icon').attr('src', 'img/icons/play_white.svg');
- }
- }
- }
- // Movie info panel
- var currentMovieAlbum = null;
- var movieInfoEpisodes = [];
- var currentMovieImdbTitle = null; // IMDB title once fetched; null until then
- // Player return-destination and watch-position tracking
- var playerReturnView = 'library';
- var pendingResumePos = 0;
- var watchSaveInterval = null;
- // Transcode seek state (seek-by-reload for non-web-playable formats)
- var transcodeSeekOffset = 0; // seconds already consumed before current chunk start
- var isTranscodedVideo = false; // true when current video plays via transcode endpoint
- var transcodeDuration = 0; // duration pre-fetched via /media/duration/ (seconds)
- // Folder browse state
- var folderViewPath = '/';
- var folderViewVideos = [];
- // ─── Movie info panel ─────────────────────────────────────────────────────────
- function openMovieInfo(album) {
- currentMovieAlbum = album;
- currentAlbum = album;
- movieInfoEpisodes = [];
- currentMovieImdbTitle = null;
- // Seed with local data immediately
- $('#movie-info-title').text(album.name);
- $('#movie-info-filename').hide().text('');
- $('#movie-info-year').text('');
- $('#movie-info-cast').text('');
- $('#movie-info-imdb-btn').hide();
- $('#movie-info-wrong-wrap').hide();
- $('#movie-info-files').hide();
- $('#movie-info-loading').addClass('active');
- var localThumb = album.thumbnail
- ? 'data:image/jpeg;base64,' + album.thumbnail
- : 'img/thumbnail.png';
- $('#movie-info-poster-img').attr('src', localThumb);
- $('#movie-info-backdrop').css('background-image', 'url(' + localThumb + ')');
- // Bind Play button
- $('#movie-info-play-btn').off('click').on('click', function () {
- if (movieInfoEpisodes.length > 0) {
- currentAlbum = album; currentSeason = null;
- currentEpisodes = movieInfoEpisodes;
- startPlayback(0);
- }
- });
- // Bind Open in Files — opens file manager at the movie's location
- $('#movie-info-fm-btn').off('click').on('click', function () {
- if (!currentMovieAlbum) { return; }
- if (currentMovieAlbum._singleFile) {
- var fp = currentMovieAlbum._singleFile;
- var dir = fp.substring(0, fp.lastIndexOf('/'));
- var fname = fp.split('/').pop();
- ao_module_openPath(dir, fname);
- } else {
- ao_module_openPath(currentMovieAlbum.folderpath);
- }
- });
- // Bind YouTube search — uses IMDB title once available, raw name otherwise
- $('#movie-info-yt-btn').off('click').on('click', function () {
- var term = currentMovieImdbTitle || (currentMovieAlbum ? currentMovieAlbum.name : '');
- window.open('https://www.youtube.com/results?search_query=' + encodeURIComponent(term + ' trailer'), '_blank');
- });
- showView('movie-info');
- // Fetch IMDB metadata
- ao_module_agirun(SCRIPT_GET_MOVIE_INFO, { movie: album.name }, function (data) {
- $('#movie-info-loading').removeClass('active');
- if (data && !data.error) { applyMovieInfo(data); }
- }, function () {
- $('#movie-info-loading').removeClass('active');
- });
- // Build file list
- if (album._singleFile) {
- var ext = '.' + album._singleFile.split('.').pop().toLowerCase();
- movieInfoEpisodes = [{ name: album.name, filepath: album._singleFile, ext: ext, index: 0 }];
- // Single file — file list not needed (Play button is enough)
- } else {
- ao_module_agirun(SCRIPT_GET_EPISODES, { folder: album.folderpath }, function (data) {
- if (data && !data.error && data.length > 0) {
- movieInfoEpisodes = data;
- if (data.length > 1) { renderMovieFileList(data); }
- }
- });
- }
- }
- function applyMovieInfo(info) {
- var imdbTitle = info['#TITLE'] || '';
- var year = info['#YEAR'] ? String(info['#YEAR']) : '';
- var actors = info['#ACTORS'] || '';
- var imdbUrl = info['#IMDB_URL'] || '';
- var poster = info['#IMG_POSTER'] || '';
- // Replace the displayed title with the canonical IMDB title and show the
- // original filename as a small italic subtitle underneath.
- if (imdbTitle) {
- currentMovieImdbTitle = imdbTitle;
- $('#movie-info-title').text(imdbTitle);
- if (currentMovieAlbum && currentMovieAlbum.name !== imdbTitle) {
- $('#movie-info-filename').text(currentMovieAlbum.name).show();
- }
- }
- if (year) { $('#movie-info-year').text(year); }
- if (actors) {
- $('#movie-info-cast').html(
- '<span style="color:var(--text-sub);font-weight:600">Cast</span> ' + escapeHtml(actors)
- );
- }
- if (poster) {
- var img = document.getElementById('movie-info-poster-img');
- img.onerror = function () {
- img.src = (currentMovieAlbum && currentMovieAlbum.thumbnail)
- ? 'data:image/jpeg;base64,' + currentMovieAlbum.thumbnail
- : 'img/thumbnail.png';
- img.onerror = null;
- };
- img.onload = function () {
- $('#movie-info-backdrop').css('background-image', 'url(' + poster + ')');
- img.onload = null;
- };
- img.src = poster;
- }
- if (imdbUrl) {
- $('#movie-info-imdb-btn').show().off('click').on('click', function () {
- window.open(imdbUrl, '_blank');
- });
- }
- // Show the "wrong movie" reset button now that IMDB data is displayed
- $('#movie-info-wrong-wrap').show();
- $('#movie-info-reset-btn').off('click').on('click', function () {
- if (!currentMovieAlbum) { return; }
- ao_module_agirun(SCRIPT_DISABLE_MOVIE_INFO, { movie: currentMovieAlbum.name },
- function () { resetMovieInfo(); },
- function () { resetMovieInfo(); } // reset UI even if backend call fails
- );
- });
- }
- // Reset the movie info panel to local-only state (used after disabling IMDB info)
- function resetMovieInfo() {
- if (!currentMovieAlbum) { return; }
- currentMovieImdbTitle = null;
- var album = currentMovieAlbum;
- $('#movie-info-title').text(album.name);
- $('#movie-info-filename').hide().text('');
- $('#movie-info-year').text('');
- $('#movie-info-cast').text('');
- $('#movie-info-imdb-btn').hide();
- $('#movie-info-wrong-wrap').hide();
- // Restore local thumbnail as poster and backdrop
- var localThumb = album.thumbnail
- ? 'data:image/jpeg;base64,' + album.thumbnail
- : 'img/thumbnail.png';
- document.getElementById('movie-info-poster-img').src = localThumb;
- $('#movie-info-backdrop').css('background-image', 'url(' + localThumb + ')');
- }
- function renderMovieFileList(episodes) {
- var $list = $('#movie-info-episode-list').empty();
- episodes.forEach(function (ep, i) {
- var row = $('<div class="episode-item" tabindex="0" role="button">'
- + '<div class="ep-thumb"><div class="ep-thumb-placeholder"><img src="img/icons/play_white.svg" alt=""></div></div>'
- + '<div class="ep-info">'
- + '<div class="ep-name">' + escapeHtml(ep.name) + '</div>'
- + '<div class="ep-path">' + escapeHtml((ep.ext || '').replace('.', '').toUpperCase()) + '</div>'
- + '</div>'
- + '<div class="ep-play-icon"><img src="img/icons/play_white.svg" alt=""></div>'
- + '</div>');
- row.data('idx', i);
- row.on('click', function () {
- currentAlbum = currentMovieAlbum; currentSeason = null;
- currentEpisodes = movieInfoEpisodes;
- startPlayback($(this).data('idx'));
- });
- row.on('keydown', function (e) {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- currentAlbum = currentMovieAlbum; currentSeason = null;
- currentEpisodes = movieInfoEpisodes;
- startPlayback($(this).data('idx'));
- }
- });
- $list.append(row);
- // Lazy thumbnail
- (function (epObj, rowEl) {
- ao_module_agirun(SCRIPT_GET_THUMBNAIL, { file: epObj.filepath }, function (data) {
- if (data && !data.error && data.length > 20) {
- rowEl.find('.ep-thumb-placeholder')
- .replaceWith('<img src="data:image/jpeg;base64,' + data + '" alt="">');
- }
- });
- })(ep, row);
- });
- $('#movie-info-files').show();
- }
- function closeMovieInfo() {
- currentMovieAlbum = null;
- movieInfoEpisodes = [];
- showView('library');
- }
- // ─── Scrub-bar hover preview (storyboard) ─────────────────────────────────────
- // The server renders one sprite sheet per file holding a downscaled frame every
- // few seconds; we fetch it once and keep it in memory, so hovering the timeline
- // costs nothing. Asking ffmpeg for a frame per hover would be hopeless on a
- // software-decoded H.265 source, which is exactly where previews matter most.
- var storyboard = null; // layout from the server + the loaded sheet URL
- var storyboardToken = 0; // invalidates in-flight loads when the file changes
- var storyboardTimer = null;
- function resetStoryboard() {
- storyboardToken++;
- storyboard = null;
- clearTimeout(storyboardTimer);
- storyboardTimer = null;
- $('#scrub-preview-thumb').removeClass('ready');
- hideScrubPreview();
- }
- // Building the sheet runs ffmpeg, so hold off briefly and let playback (and any
- // transcode) get established before adding more load.
- function scheduleStoryboardLoad(filepath) {
- resetStoryboard();
- if (!filepath) { return; }
- var token = storyboardToken;
- storyboardTimer = setTimeout(function () { loadStoryboard(filepath, token); }, 3000);
- }
- function loadStoryboard(filepath, token) {
- var base = STORYBOARD_API + '?file=' + encodeURIComponent(filepath);
- fetch(base)
- .then(function (r) { return r.json(); })
- .then(function (meta) {
- if (token !== storyboardToken) { return; } // switched file while loading
- if (!meta || meta.error || !meta.interval || !meta.tileWidth) { return; }
- var img = new Image();
- img.onload = function () {
- if (token !== storyboardToken) { return; }
- meta.url = img.src;
- storyboard = meta;
- };
- img.src = base + '&image=1';
- })
- .catch(function () {}); // previews are optional — stay silent on failure
- }
- // Whole-file duration, whichever playback mode is active
- function scrubTotalDuration() {
- if (castMode && castDuration > 0) { return castDuration; }
- if (isTranscodedVideo) { return transcodeDuration; }
- return document.getElementById('main-video').duration || 0;
- }
- function initScrubPreview() {
- var $wrap = $('#progress-wrap');
- $wrap.on('mousemove', function (e) {
- var total = scrubTotalDuration();
- var rect = this.getBoundingClientRect();
- if (!total || !isFinite(total) || rect.width <= 0) { hideScrubPreview(); return; }
- var ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
- showScrubPreview(ratio * total, ratio, rect.width);
- });
- $wrap.on('mouseleave', hideScrubPreview);
- }
- function showScrubPreview(time, ratio, barWidth) {
- $('#scrub-preview-time').text(formatTime(time));
- var $thumb = $('#scrub-preview-thumb');
- var halfWidth;
- if (storyboard && storyboard.url) {
- var idx = Math.max(0, Math.min(storyboard.count - 1,
- Math.floor(time / storyboard.interval)));
- var col = idx % storyboard.cols;
- var row = Math.floor(idx / storyboard.cols);
- $thumb.addClass('ready').css({
- 'width': storyboard.tileWidth + 'px',
- 'height': storyboard.tileHeight + 'px',
- 'background-image': 'url("' + storyboard.url + '")',
- 'background-position': (-col * storyboard.tileWidth) + 'px '
- + (-row * storyboard.tileHeight) + 'px'
- });
- halfWidth = storyboard.tileWidth / 2;
- } else {
- // Sheet not ready (or unavailable) — the timestamp alone is still useful
- $thumb.removeClass('ready');
- halfWidth = 28;
- }
- // Keep the popup within the bar rather than letting it hang off an edge
- var x = Math.max(halfWidth, Math.min(barWidth - halfWidth, ratio * barWidth));
- $('#scrub-preview').css('left', x + 'px').addClass('active');
- }
- function hideScrubPreview() { $('#scrub-preview').removeClass('active'); }
- // ─── Transcode seek (seek-by-reload) ──────────────────────────────────────────
- // Formats the browser can't decode are streamed through ffmpeg, so "seeking"
- // means restarting the transcode at a new offset. Replacing .src blanks the
- // <video> to black until the first frame of the new segment arrives, which can
- // take seconds. Freeze the last painted frame under a spinner instead, and only
- // reveal the live element once it is genuinely playing again.
- var seekFreezeTimer = null;
- function showSeekFreeze() {
- var vid = document.getElementById('main-video');
- var canvas = document.getElementById('seek-freeze');
- if (canvas && vid.videoWidth > 0 && vid.videoHeight > 0) {
- canvas.width = vid.videoWidth;
- canvas.height = vid.videoHeight;
- try {
- canvas.getContext('2d').drawImage(vid, 0, 0, canvas.width, canvas.height);
- $(canvas).show();
- } catch (e) {
- // No decodable frame right now (e.g. seeking again mid-buffer) —
- // leave whatever is already frozen on screen rather than flashing black.
- }
- }
- $('#seek-spinner').addClass('active');
- clearTimeout(seekFreezeTimer);
- // Safety net: a stalled transcode must never leave the overlay stuck on
- seekFreezeTimer = setTimeout(hideSeekFreeze, 30000);
- }
- function hideSeekFreeze() {
- clearTimeout(seekFreezeTimer);
- seekFreezeTimer = null;
- $('#seek-freeze').hide();
- $('#seek-spinner').removeClass('active');
- }
- // Seek to `seconds` (absolute, whole-file time), clamped to the known duration.
- //
- // An HLS stream keeps every segment produced so far in its playlist, so a seek
- // landing inside the transcoded window is an ordinary <video> seek — no reload,
- // no re-transcode, no black frame. Only a seek past that window (or an MP4
- // stream, which has no seekable history at all) has to restart the transcode at
- // the new offset.
- // Restarting the transcode this close to the end of the file would leave ffmpeg
- // with nothing to encode, and the request comes back with no playable stream at
- // all — so a scrub to the very end lands just short of it instead.
- var TRANSCODE_SEEK_TAIL = 5;
- function transcodeSeekTo(seconds) {
- if (playingIndex < 0 || !currentEpisodes[playingIndex]) { return; }
- var vid = document.getElementById('main-video');
- var pos = Math.max(0, seconds);
- if (transcodeDuration > 0) {
- pos = Math.min(Math.max(0, transcodeDuration - TRANSCODE_SEEK_TAIL), pos);
- }
- if (usingHLS() && seekWithinTranscodedWindow(vid, pos)) {
- setSubtitleSeekFloor(pos);
- vid.currentTime = pos - transcodeSeekOffset;
- playVideo(vid);
- return;
- }
- showSeekFreeze();
- setSubtitleSeekFloor(pos);
- transcodeSeekOffset = pos;
- // The freeze frame stays up until the new stream is bound: attaching a
- // playlist waits on the server to start the transcode, so playback resumes
- // from the onReady callback rather than immediately.
- if (!attachTranscodeStream(vid, transcodeStreamURL(currentEpisodes[playingIndex].filepath, pos),
- function (reason) { hideSeekFreeze(); showToast(reason); },
- function () { playVideo(vid); })) {
- hideSeekFreeze();
- showToast('This browser cannot play the HLS stream. Switch streaming mode to MP4 in settings.');
- }
- }
- // Whether `pos` (absolute time) falls inside what the current stream has
- // already produced and can therefore be reached without reloading. seekable
- // spans every segment the playlist lists, for native HLS and for the Media
- // Source player alike (it publishes the playlist's length as the duration).
- function seekWithinTranscodedWindow(vid, pos) {
- var relative = pos - transcodeSeekOffset;
- if (relative < 0) { return false; }
- if (!vid.seekable || vid.seekable.length === 0) { return false; }
- var available = vid.seekable.end(vid.seekable.length - 1);
- // Stay a segment clear of the live edge; seeking right onto it stalls until
- // the next segment lands.
- return relative <= available - 4;
- }
- // ─── HLS stream recovery ──────────────────────────────────────────────────────
- // An HLS transcode lives on the server, and it can disappear from under the
- // player: reaped after a long pause, retired when the same player asked for a
- // different offset, or lost with a restart. The next segment then 404s and the
- // element reports a decode error, which leaves a black frame and no way back.
- // Re-open the stream where it stopped instead. The Media Source player reports
- // the same failures as STREAM_LOST_EVENT rather than an element error.
- //
- // Returns whether a recovery was started, so a caller holding a reason for the
- // failure can show it once recovery has given up.
- var streamRecoveryAttempts = 0;
- var STREAM_RECOVERY_LIMIT = 3; // consecutive tries before giving up
- function recoverTranscodeStream() {
- if (!isTranscodedVideo || !usingHLS()) { return false; }
- if (playingIndex < 0 || !currentEpisodes[playingIndex]) { return false; }
- // A file that genuinely cannot be transcoded fails every time; retrying it
- // forever would replace one dead player with a flickering one.
- if (streamRecoveryAttempts >= STREAM_RECOVERY_LIMIT) { return false; }
- streamRecoveryAttempts++;
- var vid = document.getElementById('main-video');
- var resumeAt = effectivePlaybackTime();
- showSeekFreeze();
- transcodeSeekOffset = resumeAt;
- attachTranscodeStream(vid, transcodeStreamURL(currentEpisodes[playingIndex].filepath, resumeAt),
- function (reason) { hideSeekFreeze(); showToast(reason); },
- function () { playVideo(vid); });
- return true;
- }
- // Current playback position in whole-file terms (transcode streams restart at 0)
- function effectivePlaybackTime() {
- var vid = document.getElementById('main-video');
- return isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
- }
- // ─── Watch position (resume) ──────────────────────────────────────────────────
- function saveWatchPosition() {
- var vid = document.getElementById('main-video');
- var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
- if (playingIndex < 0 || !currentEpisodes || !effectiveDuration || effectiveDuration < 3600) { return; }
- var ep = currentEpisodes[playingIndex];
- var effectiveTime = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
- if (!ep || effectiveTime < 10) { return; }
- ao_module_agirun(SCRIPT_SET_WATCHTIME, {
- filepath: ep.filepath,
- position: Math.floor(effectiveTime),
- duration: Math.floor(effectiveDuration)
- }, function () {}, function () {});
- }
- function clearWatchPosition() {
- if (playingIndex < 0 || !currentEpisodes) { return; }
- var ep = currentEpisodes[playingIndex];
- if (!ep) { return; }
- ao_module_agirun(SCRIPT_SET_WATCHTIME, { filepath: ep.filepath, position: 0, duration: 0 },
- function () {}, function () {});
- }
- function showResumePopup(savedPos, duration) {
- var vid = document.getElementById('main-video');
- vid.pause();
- pendingResumePos = savedPos;
- $('#resume-popup-sub').text(
- 'Last position: ' + formatTime(savedPos) + ' of ' + formatTime(duration)
- );
- $('#resume-popup').addClass('active');
- showControls();
- $('#resume-btn-continue').off('click').on('click', function () {
- if (isTranscodedVideo && playingIndex >= 0 && currentEpisodes[playingIndex]) {
- transcodeSeekTo(pendingResumePos);
- } else {
- vid.currentTime = pendingResumePos;
- playVideo(vid);
- }
- $('#resume-popup').removeClass('active');
- });
- $('#resume-btn-restart').off('click').on('click', function () {
- playVideo(vid);
- $('#resume-popup').removeClass('active');
- });
- }
- // ─── Tab switching ────────────────────────────────────────────────────────────
- function switchTab(tab) {
- if (tab === 'folder') {
- var wasAlreadyFolder = $('#view-folder').hasClass('active');
- showView('folder');
- if (!wasAlreadyFolder) { navigateFolder(folderViewPath); }
- } else if (tab === 'settings') {
- showView('settings');
- refreshIndexStats();
- } else {
- showView('library');
- }
- }
- // ─── Folder navigation ────────────────────────────────────────────────────────
- function buildBreadcrumbs(path) {
- var crumbs = [{ name: 'Home', path: '/' }];
- if (!path || path === '/') { return crumbs; }
- var colonIdx = path.indexOf(':/');
- if (colonIdx < 0) { return crumbs; }
- var root = path.substring(0, colonIdx + 2);
- crumbs.push({ name: root, path: root });
- var rest = path.substring(colonIdx + 2);
- if (!rest) { return crumbs; }
- var parts = rest.split('/').filter(function (s) { return s.length > 0; });
- var cumPath = root;
- for (var i = 0; i < parts.length; i++) {
- cumPath += parts[i] + '/';
- crumbs.push({ name: parts[i], path: cumPath });
- }
- return crumbs;
- }
- function renderBreadcrumb(path) {
- var crumbs = buildBreadcrumbs(path);
- var $bc = $('#folder-breadcrumb').empty();
- for (var i = 0; i < crumbs.length; i++) {
- var crumb = crumbs[i];
- var isLast = (i === crumbs.length - 1);
- if (i > 0) { $bc.append('<span class="crumb-sep">›</span>'); }
- var btn = $('<button class="crumb-btn' + (isLast ? ' crumb-current' : '') + '">'
- + escapeHtml(crumb.name) + '</button>');
- if (!isLast) {
- (function (p) { btn.on('click', function () { navigateFolder(p); }); })(crumb.path);
- }
- $bc.append(btn);
- }
- }
- function navigateFolder(path) {
- folderViewPath = path || '/';
- renderBreadcrumb(folderViewPath);
- loadFolderContents(folderViewPath);
- }
- function loadFolderContents(path) {
- $('#folder-loading').addClass('active');
- $('#folder-empty').hide();
- $('#folder-section-dirs').hide();
- $('#folder-section-vids').hide();
- var params = (path && path !== '/') ? { folder: path } : { folder: '' };
- ao_module_agirun(SCRIPT_LIST_FOLDER, params, function (data) {
- $('#folder-loading').removeClass('active');
- if (!data || data.error) {
- $('#folder-empty').text(data && data.error ? data.error : 'Failed to load folder.').show();
- return;
- }
- renderFolderContents(data);
- }, function () {
- $('#folder-loading').removeClass('active');
- $('#folder-empty').text('Error loading folder.').show();
- });
- }
- function renderFolderContents(data) {
- folderViewVideos = data.videos || [];
- var hasDirs = data.folders && data.folders.length > 0;
- var hasVids = data.videos && data.videos.length > 0;
- if (!hasDirs && !hasVids) {
- $('#folder-empty').text('This folder is empty.').show();
- return;
- }
- if (hasDirs) {
- var $dirs = $('#folder-dirs-grid').empty();
- $('#folder-section-dirs').show();
- data.folders.forEach(function (f) {
- var thumbHtml;
- if (f.isRoot) {
- thumbHtml = '<div class="poster-placeholder"><img src="img/root_placeholder.png" alt=""></div>';
- } else if (f.hasVideos && f.thumbnail && f.thumbnail.length > 20) {
- thumbHtml = '<img class="poster" src="data:image/jpeg;base64,' + f.thumbnail + '" alt="">';
- } else if (f.hasVideos) {
- thumbHtml = '<div class="poster-placeholder"><img src="img/playlist_placeholder.png" alt=""></div>';
- } else {
- thumbHtml = '<div class="poster-placeholder"><img src="img/folder_placeholder.png" alt=""></div>';
- }
- var meta = f.isRoot ? 'Storage root' : (f.hasVideos ? 'Playlist' : 'Folder');
- var card = $('<div class="album-card" tabindex="0" role="button" aria-label="' + escapeAttr(f.name) + '">'
- + thumbHtml
- + '<div class="card-info">'
- + '<div class="card-title">' + escapeHtml(f.name) + '</div>'
- + '<div class="card-meta">' + escapeHtml(meta) + '</div>'
- + '</div>'
- + '</div>');
- card.on('click', function () { navigateFolder(f.path); });
- card.on('keydown', function (e) {
- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); navigateFolder(f.path); }
- });
- $dirs.append(card);
- });
- }
- if (hasVids) {
- var $vids = $('#folder-vids-grid').empty();
- $('#folder-section-vids').show();
- data.videos.forEach(function (v, i) {
- var card = $('<div class="album-card" tabindex="0" role="button" aria-label="' + escapeAttr(v.name) + '">'
- + '<div class="poster-placeholder"><img src="img/thumbnail.png" alt=""></div>'
- + '<div class="card-info">'
- + '<div class="card-title">' + escapeHtml(v.name) + '</div>'
- + '<div class="card-meta">' + escapeHtml((v.ext || '').replace('.', '').toUpperCase()) + '</div>'
- + '</div>'
- + '</div>');
- card.data('vidIdx', i);
- card.data('vidInfo', v);
- card.on('click', function () { playFolderVideos(folderViewVideos, $(this).data('vidIdx')); });
- card.on('keydown', function (e) {
- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); playFolderVideos(folderViewVideos, $(this).data('vidIdx')); }
- });
- $vids.append(card);
- });
- // Lazy-load video thumbnails
- $('#folder-vids-grid .album-card').each(function () {
- var $card = $(this);
- var v = $card.data('vidInfo');
- if (!v) { return; }
- ao_module_agirun(SCRIPT_GET_THUMBNAIL, { file: v.filepath }, function (data) {
- if (data && !data.error && data.length > 20) {
- $card.find('.poster-placeholder')
- .replaceWith('<img class="poster" src="data:image/jpeg;base64,' + data + '" alt="">');
- }
- });
- });
- }
- }
- function playFolderVideos(videos, startIndex) {
- if (!videos || videos.length === 0) { return; }
- var segments = folderViewPath.split('/').filter(function (s) { return s.length > 0; });
- var folderName = segments.length > 0 ? segments[segments.length - 1] : 'Videos';
- currentAlbum = { name: folderName, type: 'folder', folderpath: folderViewPath };
- currentSeason = null;
- currentEpisodes = videos.map(function (v, i) {
- return { name: v.name, filepath: v.filepath, ext: v.ext, index: i };
- });
- startPlayback(startIndex);
- }
- // ─── Init ─────────────────────────────────────────────────────────────────────
- $(document).ready(function () {
- initSettings(); // must run before loadLibrary — it reads autoIndexEnabled
- loadLibrary();
- initVideoControls();
- initKeyboard();
- initSearch();
- initContextMenu();
- initSettingsPopup();
- initSubtitlePopup();
- initScrubPreview();
- initAssRenderer();
- initSubtitleMenu();
- initSubtitleSettings();
- // Rotating a phone/tablet into landscape should reveal the playlist again
- // (and back into portrait should tuck it away) — unless the user has taken
- // manual control of it for this playback.
- $(window).on('resize orientationchange', function () {
- if (!playlistUserToggled && $('#view-player').hasClass('active')) {
- applyPlaylistVisibility();
- }
- });
- // Autoplay toggle
- $('#autoplay-check').prop('checked', autoplayEnabled);
- $('#autoplay-check').on('change', function () {
- autoplayEnabled = $(this).is(':checked');
- localStorage.setItem('movie_autoplay', autoplayEnabled ? '1' : '0');
- });
- // Yield cast session to other apps (Photo, Musicify) if they take over
- try {
- var _acCh = new BroadcastChannel('arozcast');
- _acCh.onmessage = function(evt) {
- if (evt.data && evt.data.type === 'arozcast.takeover' && castMode) {
- disconnectCast();
- }
- };
- } catch(e) {}
- // When the user returns to this tab after the phone was asleep, reconnect immediately
- document.addEventListener('visibilitychange', function() {
- if (document.visibilityState === 'visible' && castPendingCode) {
- clearTimeout(castReconnectTimer);
- castReconnectTimer = null;
- _attemptCastReconnect();
- }
- });
- // Close WS cleanly on page unload — do NOT send media.stop so Arozcast keeps playing.
- // Only an explicit disconnectCast() call should stop remote playback.
- window.addEventListener('beforeunload', function() {
- if (castWs) { castWs.onclose = null; castWs.close(); }
- });
- });
- // ─── Library status bar helpers ────────────────────────────────────────────────
- // spinning=true shows the spinner and hides the Refresh button, and vice-versa.
- function setLibraryStatus(text, spinning) {
- $('#library-status-text').text(text);
- $('#library-spinner').toggle(spinning);
- $('#library-refresh-btn').toggle(!spinning);
- }
- function timeAgo(ts) {
- var d = Math.floor((Date.now() - ts) / 1000);
- if (d < 60) { return 'just now'; }
- if (d < 3600) { return Math.floor(d / 60) + 'm ago'; }
- if (d < 86400) { return Math.floor(d / 3600) + 'h ago'; }
- return Math.floor(d / 86400) + 'd ago';
- }
- // Re-render the library grid, preserving an active search filter if present.
- function renderCurrentLibrary() {
- var q = $('#search-input').val().trim().toLowerCase();
- renderLibrary(q ? library.filter(function (a) { return a.name.toLowerCase().indexOf(q) > -1; }) : library);
- }
- // Run a background full scan. getLibrary.js writes the cache file server-side
- // before it sends its response, so the cache is updated even if the tab closes
- // partway through — the browser just won't receive the response in that case.
- function backgroundScanLibrary() {
- ao_module_agirun(SCRIPT_GET_LIBRARY, {}, function (data) {
- if (!data || data.error) {
- setLibraryStatus('Refresh failed · showing cached data', false);
- return;
- }
- library = data;
- libraryCacheTs = Date.now();
- if ($('#view-library').hasClass('active')) {
- renderCurrentLibrary();
- libraryNeedsRedraw = false;
- } else {
- libraryNeedsRedraw = true;
- }
- var n = library.length;
- setLibraryStatus(n + ' item' + (n !== 1 ? 's' : ''), false);
- }, function () {
- setLibraryStatus('Refresh failed · showing cached data', false);
- });
- }
- // ─── Load library (server-side cache-first) ────────────────────────────────────
- // 1. Ask getLibraryCache.js for the last saved scan result (milliseconds, no scan).
- // 2a. Cache hit → render immediately, kick off backgroundScanLibrary().
- // 2b. Cache miss → show loading overlay, run full scan, render when done.
- function loadLibrary() {
- ao_module_agirun(SCRIPT_GET_LIBRARY_CACHE, {}, function (cached) {
- if (cached && !cached.error && Array.isArray(cached.data)) {
- // Fast path: paint the UI from cache right away
- $('#loading-overlay').hide();
- library = cached.data;
- libraryCacheTs = cached.ts || 0;
- renderLibrary(library);
- if (autoIndexEnabled) {
- setLibraryStatus('Cached · ' + timeAgo(cached.ts) + ' · refreshing…', true);
- backgroundScanLibrary();
- } else {
- // Auto indexing is off — serve the cache as-is and say so, so an
- // out-of-date library never looks like a bug.
- var n = library.length;
- setLibraryStatus(n + ' item' + (n !== 1 ? 's' : '')
- + ' · indexed ' + timeAgo(cached.ts) + ' · auto indexing off', false);
- }
- } else {
- coldStartLibrary();
- }
- }, function () {
- // getLibraryCache.js itself failed — treat as cold start
- coldStartLibrary();
- });
- }
- // No usable index yet. Scan if auto indexing is on; otherwise leave the library
- // empty and point the user at the manual scan rather than walking every root.
- function coldStartLibrary() {
- if (!autoIndexEnabled) {
- $('#loading-overlay').fadeOut(300);
- library = [];
- renderLibrary(library);
- setLibraryStatus('No index yet · auto indexing off', false);
- return;
- }
- setLibraryStatus('Loading…', true);
- ao_module_agirun(SCRIPT_GET_LIBRARY, {}, function (data) {
- $('#loading-overlay').fadeOut(300);
- if (!data || data.error) {
- showToast('Failed to load library');
- setLibraryStatus('Failed to load library', false);
- return;
- }
- library = data;
- libraryCacheTs = Date.now();
- renderLibrary(library);
- var n = library.length;
- setLibraryStatus(n + ' item' + (n !== 1 ? 's' : ''), false);
- }, function () {
- $('#loading-overlay').fadeOut(300);
- showToast('Error loading library');
- setLibraryStatus('Error loading library', false);
- });
- }
- // ─── Manual refresh (Refresh button) ──────────────────────────────────────────
- // Passes forceRefresh=1 to bypass the 8-hour staleness guard in getLibrary.js.
- function refreshLibrary() {
- $('#library-refresh-btn').prop('disabled', true);
- setLibraryStatus('Refreshing…', true);
- ao_module_agirun(SCRIPT_GET_LIBRARY, { forceRefresh: '1' }, function (data) {
- $('#library-refresh-btn').prop('disabled', false);
- if (!data || data.error) {
- showToast('Failed to refresh library');
- setLibraryStatus('Refresh failed', false);
- return;
- }
- library = data;
- libraryCacheTs = Date.now();
- renderCurrentLibrary();
- libraryNeedsRedraw = false;
- var n = library.length;
- setLibraryStatus(n + ' item' + (n !== 1 ? 's' : '') + ' · just refreshed', false);
- }, function () {
- $('#library-refresh-btn').prop('disabled', false);
- showToast('Error refreshing library');
- setLibraryStatus('Refresh failed', false);
- });
- }
- // ═══════════════ SETTINGS TAB ═══════════════════════════════════════════════
- // Indexing controls: toggle the automatic scan, rescan on demand, drop the
- // index, and report what the index currently costs on disk.
- function formatBytes(n) {
- if (!n || n < 0) { return '0 B'; }
- var units = ['B', 'KB', 'MB', 'GB'];
- var i = 0;
- while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; }
- return (i === 0 ? n : n.toFixed(n < 10 ? 1 : 0)) + ' ' + units[i];
- }
- function setAutoIndexEnabled(on) {
- autoIndexEnabled = !!on;
- localStorage.setItem('movie_auto_index', autoIndexEnabled ? '1' : '0');
- $('#setting-auto-index').prop('checked', autoIndexEnabled);
- }
- function setSettingsBusy(busy, text) {
- $('#settings-progress').toggleClass('active', !!busy);
- if (text) { $('#settings-progress-text').text(text); }
- $('#settings-scan-btn, #settings-clear-btn').prop('disabled', !!busy);
- }
- // Album/video totals come from the in-memory library (already loaded from the
- // same cache file), so this never re-parses the multi-MB index server-side.
- function renderIndexStats(stats) {
- var albums = library ? library.length : 0;
- var videos = 0;
- var byType = {};
- if (library) {
- for (var i = 0; i < library.length; i++) {
- var a = library[i];
- videos += (a.episodeCount || 0);
- byType[a.type] = (byType[a.type] || 0) + 1;
- }
- }
- $('#stat-size').text(stats && stats.exists ? formatBytes(stats.sizeBytes) : '—');
- $('#stat-albums').text(albums.toLocaleString());
- $('#stat-videos').text(videos.toLocaleString());
- $('#stat-roots').text(stats ? String(stats.roots) : '—');
- var labels = {
- movie: ['Movie', 'Movies'],
- collection: ['Collection', 'Collections'],
- series: ['TV show', 'TV shows'],
- anime: ['Anime', 'Anime'],
- short: ['Short', 'Shorts']
- };
- var $bd = $('#settings-breakdown').empty();
- ['movie', 'collection', 'series', 'anime', 'short'].forEach(function (t) {
- var n = byType[t];
- if (!n) { return; }
- var label = labels[t] ? labels[t][n === 1 ? 0 : 1] : t;
- $bd.append('<span class="breakdown-chip"><b>' + n + '</b> ' + escapeHtml(label) + '</span>');
- });
- if (stats && stats.skippedRoots > 0) {
- $bd.append('<span class="breakdown-chip"><b>' + stats.skippedRoots
- + '</b> root' + (stats.skippedRoots !== 1 ? 's' : '') + ' skipped</span>');
- }
- var when = (stats && stats.exists && libraryCacheTs)
- ? 'Last scan: ' + timeAgo(libraryCacheTs) + ' (' + new Date(libraryCacheTs).toLocaleString() + ')'
- : (stats && stats.exists ? 'Last scan: unknown' : 'No index on disk — run a scan to build one.');
- $('#settings-last-scan').text(when);
- }
- function refreshIndexStats() {
- renderIndexStats(null); // paint client-side counts immediately
- ao_module_agirun(SCRIPT_GET_INDEX_STATS, {}, function (stats) {
- if (stats && !stats.error) { renderIndexStats(stats); }
- }, function () {});
- }
- function settingsScanNow() {
- setSettingsBusy(true, 'Scanning every storage root — this can take a while…');
- setLibraryStatus('Rescanning…', true);
- ao_module_agirun(SCRIPT_GET_LIBRARY, { forceRefresh: '1' }, function (data) {
- setSettingsBusy(false);
- if (!data || data.error) {
- showToast('Scan failed');
- setLibraryStatus('Scan failed', false);
- return;
- }
- library = data;
- libraryCacheTs = Date.now();
- renderCurrentLibrary();
- libraryNeedsRedraw = false;
- var n = library.length;
- setLibraryStatus(n + ' item' + (n !== 1 ? 's' : '') + ' · just refreshed', false);
- refreshIndexStats();
- showToast('Scan complete — ' + n + ' title' + (n !== 1 ? 's' : '') + ' indexed');
- }, function () {
- setSettingsBusy(false);
- showToast('Error while scanning');
- setLibraryStatus('Scan failed', false);
- });
- }
- function settingsClearIndex() {
- if (!confirm('Clear the library index?\n\nOnly the cached scan result is deleted — your video files are not touched.')) {
- return;
- }
- setSettingsBusy(true, 'Clearing index…');
- ao_module_agirun(SCRIPT_CLEAR_INDEX, {}, function (res) {
- setSettingsBusy(false);
- if (!res || res.error) { showToast('Could not clear the index'); return; }
- library = [];
- libraryCacheTs = 0;
- renderLibrary(library);
- libraryNeedsRedraw = false;
- setLibraryStatus('No index yet' + (autoIndexEnabled ? '' : ' · auto indexing off'), false);
- refreshIndexStats();
- showToast(res.removed ? 'Index cleared' : 'No index to clear');
- }, function () {
- setSettingsBusy(false);
- showToast('Could not clear the index');
- });
- }
- function initSettings() {
- $('#setting-auto-index').prop('checked', autoIndexEnabled).on('change', function () {
- setAutoIndexEnabled($(this).is(':checked'));
- showToast('Auto indexing ' + (autoIndexEnabled ? 'enabled' : 'disabled'));
- });
- $('#settings-scan-btn').on('click', settingsScanNow);
- $('#settings-clear-btn').on('click', settingsClearIndex);
- }
- // ─── Render library grid ──────────────────────────────────────────────────────
- function renderLibrary(albums) {
- moviesData = albums.filter(function (a) { return a.type === 'movie'; });
- collectionsData = albums.filter(function (a) { return a.type === 'collection'; });
- showsData = albums.filter(function (a) { return a.type === 'series'; });
- animeData = albums.filter(function (a) { return a.type === 'anime'; });
- shortsData = albums.filter(function (a) { return a.type === 'short'; });
- moviesShown = 0;
- collectionsShown = 0;
- showsShown = 0;
- animeShown = 0;
- shortsShown = 0;
- $('#movies-grid').empty();
- $('#collections-grid').empty();
- $('#series-grid').empty();
- $('#shorts-grid').empty();
- $('#anime-grid').empty();
- if (!moviesData.length && !collectionsData.length && !showsData.length && !animeData.length && !shortsData.length) {
- $('#no-content').show();
- return;
- }
- $('#no-content').hide();
- if (moviesData.length > 0) { $('#movies-section').show(); loadMoreSection('movies'); }
- else { $('#movies-section').hide(); }
- if (collectionsData.length > 0) { $('#collections-section').show(); loadMoreSection('collections'); }
- else { $('#collections-section').hide(); }
- if (showsData.length > 0) { $('#series-section').show(); loadMoreSection('shows'); }
- else { $('#series-section').hide(); }
- if (animeData.length > 0) { $('#anime-section').show(); loadMoreSection('anime'); }
- else { $('#anime-section').hide(); }
- if (shortsData.length > 0) { $('#shorts-section').show(); loadMoreSection('shorts'); }
- else { $('#shorts-section').hide(); }
- }
- function loadMoreSection(which) {
- var data, $grid, $btn, start, end, i;
- if (which === 'movies') {
- data = moviesData;
- $grid = $('#movies-grid');
- $btn = $('#movies-load-more');
- start = moviesShown;
- end = Math.min(start + PAGE_SIZE, data.length);
- for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
- moviesShown = end;
- $btn.toggle(moviesShown < data.length);
- } else if (which === 'shows') {
- data = showsData;
- $grid = $('#series-grid');
- $btn = $('#shows-load-more');
- start = showsShown;
- end = Math.min(start + PAGE_SIZE, data.length);
- for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
- showsShown = end;
- $btn.toggle(showsShown < data.length);
- } else if (which === 'collections') {
- data = collectionsData;
- $grid = $('#collections-grid');
- $btn = $('#collections-load-more');
- start = collectionsShown;
- end = Math.min(start + PAGE_SIZE, data.length);
- for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
- collectionsShown = end;
- $btn.toggle(collectionsShown < data.length);
- } else if (which === 'anime') {
- data = animeData;
- $grid = $('#anime-grid');
- $btn = $('#anime-load-more');
- start = animeShown;
- end = Math.min(start + PAGE_SIZE, data.length);
- for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
- animeShown = end;
- $btn.toggle(animeShown < data.length);
- } else {
- data = shortsData;
- $grid = $('#shorts-grid');
- $btn = $('#shorts-load-more');
- start = shortsShown;
- end = Math.min(start + PAGE_SIZE, data.length);
- for (i = start; i < end; i++) { $grid.append(buildCard(data[i], i)); }
- shortsShown = end;
- $btn.toggle(shortsShown < data.length);
- }
- loadCardThumbnails();
- }
- function buildCard(album, idx) {
- var thumb = album.thumbnail && album.thumbnail.length > 0
- ? '<img class="poster" src="data:image/jpeg;base64,' + album.thumbnail + '" alt="">'
- : '<div class="poster-placeholder"><img src="img/thumbnail.png" alt=""></div>';
- var badge = album.type === 'series' ? '<span class="badge series">Series</span>'
- : album.type === 'anime' ? '<span class="badge anime">Anime</span>'
- : '';
- var ext = album._singleFile ? album._singleFile.split('.').pop().toUpperCase() : '';
- var meta = (album.type === 'series' || album.type === 'anime')
- ? album.episodeCount + ' ep'
- : album.type === 'short'
- ? (ext || 'Short')
- : album.type === 'collection'
- ? album.episodeCount + (album.episodeCount > 1 ? ' videos' : ' video')
- : album.episodeCount + (album.episodeCount > 1 ? ' parts' : ' movie');
- var card = $('<div class="album-card" tabindex="0" role="button" aria-label="' + escapeAttr(album.name) + '">'
- + thumb
- + badge
- + '<div class="card-info">'
- + '<div class="card-title">' + escapeHtml(album.name) + '</div>'
- + '<div class="card-meta">' + escapeHtml(meta) + '</div>'
- + '</div>'
- + '</div>');
- card.data('album', album);
- card.on('click', function () {
- if (album.type === 'short' && album._singleFile) {
- currentAlbum = album; currentSeason = null;
- currentEpisodes = [{ name: album.name, filepath: album._singleFile,
- ext: album._singleFile.split('.').pop().toLowerCase(), index: 0 }];
- startPlayback(0);
- } else if (album.type === 'movie') {
- openMovieInfo(album);
- } else { openDetail(album); }
- });
- card.on('keydown', function (e) {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- if (album.type === 'short' && album._singleFile) {
- currentAlbum = album; currentSeason = null;
- currentEpisodes = [{ name: album.name, filepath: album._singleFile,
- ext: album._singleFile.split('.').pop().toLowerCase(), index: 0 }];
- startPlayback(0);
- } else if (album.type === 'movie') {
- openMovieInfo(album);
- } else { openDetail(album); }
- }
- });
- return card;
- }
- // Load thumbnails in background (for cards that don't have one embedded)
- function loadCardThumbnails() {
- $('.album-card').each(function () {
- var $card = $(this);
- var album = $card.data('album');
- if (!album || album.thumbnail) { return; } // already has thumb
- // For shorts use the actual video file; folder path would yield the generic folder thumbnail
- var fileParam = (album.type === 'short' && album._singleFile) ? album._singleFile : album.folderpath;
- ao_module_agirun(SCRIPT_GET_THUMBNAIL, { file: fileParam }, function (data) {
- if (data && !data.error && data.length > 20) {
- $card.find('.poster-placeholder')
- .replaceWith('<img class="poster" src="data:image/jpeg;base64,' + data + '" alt="">');
- }
- });
- });
- }
- // ─── Detail view ──────────────────────────────────────────────────────────────
- function openDetail(album) {
- currentAlbum = album;
- // Hero background
- var bg = album.thumbnail ? 'data:image/jpeg;base64,' + album.thumbnail : '';
- $('#detail-hero-bg').css('background-image', bg ? 'url(' + bg + ')' : 'none');
- // Poster
- var posterHtml = album.thumbnail
- ? '<img src="data:image/jpeg;base64,' + album.thumbnail + '" alt="" style="width:100%;aspect-ratio:2/3;object-fit:cover;">'
- : '<div class="poster-placeholder"><img src="img/icons/movie_white.svg" alt=""></div>';
- $('#detail-poster').html(posterHtml);
- // Title & subtitle
- $('#detail-title').text(album.name);
- var sub = (album.type === 'series' || album.type === 'anime')
- ? album.seasons.length + ' season' + (album.seasons.length !== 1 ? 's' : '') + ' · ' + album.episodeCount + ' episodes'
- : album.type === 'collection'
- ? album.episodeCount + (album.episodeCount > 1 ? ' videos' : ' video')
- : album.episodeCount + (album.episodeCount > 1 ? ' parts' : ' movie');
- $('#detail-subtitle').text(sub);
- // Season tabs
- var $tabs = $('#season-tabs').empty();
- if ((album.type === 'series' || album.type === 'anime') && album.seasons.length > 0) {
- album.seasons.forEach(function (s, i) {
- var tab = $('<button class="season-tab" tabindex="0" title="' + escapeAttr(s.name) + '">'
- + escapeHtml(s.name) + '</button>');
- tab.data('season', s);
- tab.on('click', function () { selectSeason($(this).data('season')); activateTab(this); });
- $tabs.append(tab);
- });
- $tabs.show();
- selectSeason(album.seasons[0]);
- $tabs.find('.season-tab').first().addClass('active');
- } else {
- $tabs.hide();
- // Load the folder directly as episodes
- loadEpisodes(album.folderpath);
- }
- // Play / shuffle button bindings
- $('#btn-play-first').off('click').on('click', function () {
- if (currentEpisodes.length > 0) { startPlayback(0); }
- });
- $('#btn-shuffle').off('click').on('click', function () {
- if (currentEpisodes.length === 0) { return; }
- var idx = Math.floor(Math.random() * currentEpisodes.length);
- startPlayback(idx);
- });
- showView('detail');
- }
- function selectSeason(season) {
- currentSeason = season;
- loadEpisodes(season.folderpath);
- }
- function activateTab(el) {
- $('#season-tabs .season-tab').removeClass('active');
- $(el).addClass('active');
- }
- function loadEpisodes(folderpath) {
- $('#episode-list').html('<div style="color:var(--text-sub);padding:20px 0;">Loading…</div>');
- ao_module_agirun(SCRIPT_GET_EPISODES, { folder: folderpath }, function (data) {
- if (!data || data.error) {
- $('#episode-list').html('<div style="color:var(--text-sub);padding:20px 0;">No episodes found.</div>');
- currentEpisodes = [];
- return;
- }
- currentEpisodes = data;
- renderEpisodes(data);
- }, function () {
- $('#episode-list').html('<div style="color:var(--text-sub);padding:20px 0;">Error loading episodes.</div>');
- });
- }
- function renderEpisodes(episodes) {
- var $list = $('#episode-list').empty();
- episodes.forEach(function (ep, i) {
- var row = $('<div class="episode-item" tabindex="0" role="button">'
- + '<div class="ep-thumb"><div class="ep-thumb-placeholder"><img src="img/icons/play_white.svg" alt=""></div></div>'
- + '<div class="ep-info">'
- + '<div class="ep-name">' + escapeHtml(ep.name) + '</div>'
- + '<div class="ep-path">' + escapeHtml(ep.ext.replace('.', '').toUpperCase()) + '</div>'
- + '</div>'
- + '<div class="ep-play-icon"><img src="img/icons/play_white.svg" alt=""></div>'
- + '</div>');
- row.data('ep', ep);
- row.data('idx', i);
- row.on('click', function () { startPlayback($(this).data('idx')); });
- row.on('keydown', function (e) {
- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); startPlayback($(this).data('idx')); }
- });
- $list.append(row);
- // Lazy-load thumbnail
- (function (epObj, rowEl) {
- ao_module_agirun(SCRIPT_GET_THUMBNAIL, { file: epObj.filepath }, function (data) {
- if (data && !data.error && data.length > 20) {
- rowEl.find('.ep-thumb-placeholder')
- .replaceWith('<img src="data:image/jpeg;base64,' + data + '" alt="">');
- }
- });
- })(ep, row);
- });
- }
- // ─── Player ───────────────────────────────────────────────────────────────────
- function isWebPlayable(ext) {
- return ['mp4', 'webm', 'ogg'].includes(ext);
- }
- function startPlayback(index) {
- // Coming from inside the player means this is an episode change rather than
- // a fresh playback, and the playlist is handled differently (see below).
- var isEpisodeChange = $('#view-player').hasClass('active');
- cancelCountdown();
- hideSeekFreeze(); // never carry a frozen frame across to a different episode
- resetSubtitleSeekFloor(); // a fresh episode starts unsuppressed
- $('#resume-popup').removeClass('active');
- if (!currentEpisodes || currentEpisodes.length === 0) { return; }
- playingIndex = index;
- var ep = currentEpisodes[index];
- var ext = ep.ext ? ep.ext.toLowerCase().replace(/^\./, '') : '';
- // Reset transcode seek state for the new episode
- transcodeSeekOffset = 0;
- transcodeDuration = 0;
- var vid = document.getElementById('main-video');
- // The extension only says the container might be playable; the codec inside
- // decides. The cast receiver is a separate client but faces the same codecs,
- // so it is routed through the same verdict.
- resolveDirectPlay(ep.filepath, ext, function (directPlay) {
- if (playingIndex !== index) { return; } // episode changed while probing
- if (castMode && _castConnected()) {
- // Don't load locally — avoids transcoding the same file twice.
- // The receiver always gets the MP4 stream rather than this browser's
- // streaming-mode preference.
- isTranscodedVideo = !directPlay;
- vid.pause();
- _castSend('media.load', {
- filepath: ep.filepath, name: ep.name, type: 'video',
- src: directPlay ? MEDIA_API + '?file=' + encodeURIComponent(ep.filepath)
- : TRANSCODE_API + '?file=' + encodeURIComponent(ep.filepath),
- startTime: 0
- });
- // Volume after load, before play — guarantees device volume overrides
- // whatever Arozcast was previously playing at.
- _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted });
- _castSend('media.play', {});
- armResumePrompt(ep, index);
- return;
- }
- beginEpisodeStream(ep, index, directPlay);
- });
- $('#now-playing-title, #topbar-title').text(ep.name);
- ao_module_setWindowTitle('Movie – ' + ep.name);
- scheduleStoryboardLoad(ep.filepath);
- loadEmbeddedTrackList(ep.filepath);
- renderSidebar(currentEpisodes, index);
- if (isEpisodeChange) {
- peekPlaylistForEpisodeChange();
- } else {
- // New playback — drop any manual show/hide the user applied to the last one
- cancelPlaylistPeek();
- playlistUserToggled = false;
- applyPlaylistVisibility();
- }
- highlightPlayingEpisode(index);
- // Remember where we came from so closePlayer() can return there
- var curView = $('.view.active').attr('id');
- if (curView && curView !== 'view-player') {
- playerReturnView = curView.replace('view-', '');
- }
- showView('player');
- showControls();
- }
- // Bind the video element to the right stream and arm the resume prompt.
- //
- // Split out of startPlayback because the direct-play decision depends on a
- // codec probe and so arrives asynchronously; it is also the retry target when
- // direct playback turns out to fail anyway.
- function beginEpisodeStream(ep, index, directPlay) {
- var vid = document.getElementById('main-video');
- clearDirectPlaybackWatch(vid);
- detachTranscodeStream(vid);
- isTranscodedVideo = !directPlay;
- transcodeSeekOffset = 0;
- transcodeDuration = 0;
- if (directPlay) {
- vid.src = MEDIA_API + '?file=' + encodeURIComponent(ep.filepath);
- // Last resort: a browser without the platform decoder the probe assumed
- onDirectPlaybackFailure(vid, function () {
- if (playingIndex !== index) { return; }
- showToast('This browser cannot decode that file — switching to a transcode');
- beginEpisodeStream(ep, index, false);
- });
- playVideo(vid);
- } else if (!attachTranscodeStream(vid, transcodeStreamURL(ep.filepath, 0),
- function (reason) { showToast(reason); },
- function () { playVideo(vid); })) {
- showToast('This browser cannot play the transcoded stream. Switch streaming mode to MP4 in settings.');
- return;
- }
- armResumePrompt(ep, index);
- }
- // Offer to resume where the viewer left off. Direct playback learns its length
- // from the element; a transcode has to ask the server for it.
- function armResumePrompt(ep, index) {
- var vid = document.getElementById('main-video');
- if (!isTranscodedVideo) {
- (function (epFilepath) {
- $(vid).off('loadedmetadata.resume').one('loadedmetadata.resume', function () {
- if (vid.duration > 3600) {
- ao_module_agirun(SCRIPT_GET_WATCHTIME, { filepath: epFilepath }, function (data) {
- if (data && !data.error && data.position > 30 && data.position < vid.duration * 0.95) {
- showResumePopup(data.position, vid.duration);
- }
- });
- }
- });
- })(ep.filepath);
- } else {
- $(vid).off('loadedmetadata.resume'); // clear any stale handler
- (function (capturedEp, capturedIndex) {
- fetch(ao_root + 'media/duration/?file=' + encodeURIComponent(capturedEp.filepath))
- .then(function (r) { return r.json(); })
- .then(function (data) {
- if (data.duration > 0 && playingIndex === capturedIndex &&
- currentEpisodes[capturedIndex] &&
- currentEpisodes[capturedIndex].filepath === capturedEp.filepath) {
- transcodeDuration = data.duration;
- if (transcodeDuration > 3600) {
- ao_module_agirun(SCRIPT_GET_WATCHTIME, { filepath: capturedEp.filepath }, function (wdata) {
- if (wdata && !wdata.error && wdata.position > 30 && wdata.position < transcodeDuration * 0.95) {
- showResumePopup(wdata.position, transcodeDuration);
- }
- });
- }
- }
- }).catch(function () {});
- })(ep, index);
- }
- }
- function renderSidebar(episodes, playing) {
- var $list = $('#sidebar-list').empty();
- episodes.forEach(function (ep, i) {
- var row = $('<div class="sidebar-ep' + (i === playing ? ' playing' : '') + '" tabindex="0" role="button">'
- + '<span class="sidebar-ep-num">' + (i + 1) + '</span>'
- + '<span class="sidebar-ep-name">' + escapeHtml(ep.name) + '</span>'
- + '</div>');
- row.data('idx', i);
- row.on('click', function () {
- cancelCountdown();
- startPlayback($(this).data('idx'));
- });
- $list.append(row);
- });
- // Scroll to playing
- var $playing = $list.find('.playing');
- if ($playing.length) {
- setTimeout(function () { $playing[0].scrollIntoView({ block: 'center' }); }, 50);
- }
- }
- function highlightPlayingEpisode(idx) {
- $('#episode-list .episode-item').removeClass('playing');
- $('#episode-list .episode-item').eq(idx).addClass('playing');
- }
- function closePlayer() {
- // Always cancel any pending auto-reconnect
- clearTimeout(castReconnectTimer); castReconnectTimer = null;
- castReconnectCount = 0; castPendingCode = null;
- if (castMode) {
- // Do NOT send media.stop — Arozcast will keep playing.
- // Only disconnectCast() (explicit user action) stops remote playback.
- if (castWs) { castWs.onclose = null; castWs.close(); castWs = null; }
- clearInterval(castPingTimer); clearInterval(castWatchTimer);
- castPingTimer = castWatchTimer = null;
- castMode = false; castCode = null;
- $('#ctrl-cast, #ctrl-cast-top').removeClass('casting');
- }
- saveWatchPosition();
- cancelCountdown();
- cancelPlaylistPeek();
- hideSeekFreeze();
- resetStoryboard();
- resetEmbeddedTracks();
- if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
- var vid = document.getElementById('main-video');
- vid.pause();
- // Release the HLS attachment before clearing the source, or it keeps
- // fetching segments into an element nobody is watching.
- clearDirectPlaybackWatch(vid);
- detachTranscodeStream(vid);
- vid.removeAttribute('src');
- $('#resume-popup').removeClass('active');
- var returnTo = (currentAlbum && (currentAlbum.type === 'series' || currentAlbum.type === 'anime' || currentAlbum.type === 'collection'))
- ? 'detail'
- : playerReturnView;
- showView(returnTo);
- }
- function showLibrary() {
- showView('library');
- currentAlbum = null;
- // If a background refresh completed while the user was away, apply it now
- if (libraryNeedsRedraw) {
- libraryNeedsRedraw = false;
- renderCurrentLibrary();
- }
- }
- // ─── View switching ───────────────────────────────────────────────────────────
- function showView(name) {
- $('.view').removeClass('active');
- $('#view-' + name).addClass('active');
- if (name === 'library' || name === 'detail') {
- $('.mode-tab').removeClass('active');
- $('#tab-library').addClass('active');
- $('#search-wrap').show();
- } else if (name === 'folder') {
- $('.mode-tab').removeClass('active');
- $('#tab-folder').addClass('active');
- $('#search-wrap').hide();
- } else if (name === 'movie-info') {
- $('.mode-tab').removeClass('active');
- $('#tab-library').addClass('active');
- $('#search-wrap').hide();
- } else if (name === 'settings') {
- $('.mode-tab').removeClass('active');
- $('#tab-settings').addClass('active');
- $('#search-wrap').hide();
- }
- // player view leaves tab state unchanged
- }
- // ─── Video controls ───────────────────────────────────────────────────────────
- function initVideoControls() {
- var vid = document.getElementById('main-video');
- var $ctrl = $('#video-controls');
- var $prog = $('#progress-bar');
- var $thumb = $('#progress-thumb');
- var $time = $('#time-display');
- var $play = $('#ctrl-play');
- var $mute = $('#ctrl-mute');
- // Restore saved volume from last session
- var savedVol = parseFloat(localStorage.getItem('movie_volume'));
- if (!isNaN(savedVol) && savedVol >= 0 && savedVol <= 1) {
- vid.volume = savedVol;
- $('#volume-slider').val(savedVol);
- }
- if (localStorage.getItem('movie_muted') === '1') { vid.muted = true; }
- // Play/Pause
- $('#ctrl-play').on('click', function () { togglePlay(); });
- $('#ctrl-mute').on('click', function () {
- vid.muted = !vid.muted;
- updateMuteIcon();
- if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
- });
- $('#ctrl-prev').on('click', function () { playOffset(-1); });
- $('#ctrl-next').on('click', function () { playOffset(1); });
- $('#ctrl-fs').on('click', function () { toggleFullscreen(); });
- $('#ctrl-list').on('click', function () { toggleSidebar(); });
- $('#volume-slider').on('input', function () {
- vid.volume = parseFloat($(this).val());
- updateMuteIcon();
- if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
- });
- // Progress bar click / drag
- $('#progress-wrap').on('click', function (e) {
- if (castMode && _castConnected()) {
- if (castDuration > 0) {
- var pct = e.offsetX / $(this).width();
- var seekTo = pct * castDuration;
- _castSend('media.seek', { time: seekTo });
- // Optimistic update — reflect position immediately
- castCurrentTime = seekTo;
- _castUpdateProgressUI();
- }
- return;
- }
- if (isTranscodedVideo && transcodeDuration > 0 && playingIndex >= 0 && currentEpisodes[playingIndex]) {
- transcodeSeekTo((e.offsetX / $(this).width()) * transcodeDuration);
- return;
- }
- if (vid.duration) {
- var pct = e.offsetX / $(this).width();
- vid.currentTime = pct * vid.duration;
- }
- });
- // Video events
- $(vid).on('timeupdate', function () {
- if (isTranscodedVideo) {
- var displayTime = vid.currentTime + transcodeSeekOffset;
- if (transcodeDuration > 0) {
- var pct = (displayTime / transcodeDuration) * 100;
- $prog.css('width', pct + '%');
- $thumb.css('left', 'calc(' + pct + '% - 7px)');
- $time.text(formatTime(displayTime) + ' / ' + formatTime(transcodeDuration));
- } else {
- $time.text(formatTime(displayTime) + ' / --:--');
- }
- return;
- }
- if (!vid.duration) { return; }
- var pct = (vid.currentTime / vid.duration) * 100;
- $prog.css('width', pct + '%');
- $thumb.css('left', 'calc(' + pct + '% - 7px)');
- $time.text(formatTime(vid.currentTime) + ' / ' + formatTime(vid.duration));
- });
- $(vid).on('play', function () {
- $('#play-icon').attr('src', 'img/icons/pause_white.svg');
- // Periodically save position for videos longer than 1 hr
- if (watchSaveInterval) { clearInterval(watchSaveInterval); }
- watchSaveInterval = setInterval(function () {
- var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
- if (!vid.paused && effectiveDuration > 3600) { saveWatchPosition(); }
- }, 30000);
- });
- $(vid).on('pause', function () {
- $('#play-icon').attr('src', 'img/icons/play_white.svg');
- if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
- var effectiveDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
- var effectiveTime = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
- if (effectiveDuration > 3600 && effectiveTime > 30) { saveWatchPosition(); }
- });
- $(vid).on('ended', function () {
- clearWatchPosition(); // video finished naturally — remove resume point
- if (watchSaveInterval) { clearInterval(watchSaveInterval); watchSaveInterval = null; }
- cancelCountdown();
- if (repeatSingle) {
- vid.currentTime = 0;
- playVideo(vid);
- } else if (playingIndex < currentEpisodes.length - 1 && autoplayEnabled) {
- startNextCountdown();
- }
- });
- $(vid).on('volumechange', function () {
- updateMuteIcon();
- localStorage.setItem('movie_volume', vid.volume);
- localStorage.setItem('movie_muted', vid.muted ? '1' : '0');
- });
- // Drop the transcode-seek freeze frame the moment the new segment is live.
- // 'playing' is the accurate signal; 'loadeddata' covers a seek made while
- // paused (where 'playing' never fires), and 'error' avoids a stuck overlay.
- // Any seek — native or transcode reload — re-bases the subtitle floor
- $(vid).on('seeking', function () { setSubtitleSeekFloor(effectivePlaybackTime()); });
- $(vid).on('playing', function () {
- hideSeekFreeze();
- streamRecoveryAttempts = 0; // the stream is healthy again
- });
- $(vid).on('loadeddata', function () { if (vid.paused) { hideSeekFreeze(); } });
- $(vid).on('error', function () {
- hideSeekFreeze();
- recoverTranscodeStream();
- });
- $(vid).on(STREAM_LOST_EVENT, function (e) {
- hideSeekFreeze();
- if (recoverTranscodeStream()) { return; }
- var detail = (e.originalEvent && e.originalEvent.detail) || {};
- showToast(detail.reason || 'The HLS stream stopped and could not be reopened.');
- });
- // Auto-hide controls
- $('#video-container').on('mousemove touchstart', function () { showControls(); });
- // Click on video = play/pause
- $(vid).on('click', function () { togglePlay(); });
- // Hide back button when in fullscreen (JS reinforcement)
- document.addEventListener('fullscreenchange', function () {
- $('#player-topbar').toggle(!document.fullscreenElement);
- });
- document.addEventListener('webkitfullscreenchange', function () {
- $('#player-topbar').toggle(!document.webkitFullscreenElement);
- });
- function updateMuteIcon() {
- var isMuted = vid.muted || vid.volume === 0;
- $('#mute-icon').attr('src', isMuted ? 'img/icons/mute_white.svg' : 'img/icons/volume_white.svg');
- $('#volume-slider').val(vid.muted ? 0 : vid.volume);
- }
- }
- // Optimistic UI sync for cast mode — call immediately after sending a seek/play/pause command
- // so the user sees instant feedback instead of waiting up to 3 s for status.update.
- function _castUpdateProgressUI() {
- if (!castDuration) return;
- var pct = (castCurrentTime / castDuration) * 100;
- $('#progress-bar').css('width', pct + '%');
- $('#progress-thumb').css('left', 'calc(' + pct + '% - 7px)');
- $('#time-display').text(formatTime(castCurrentTime) + ' / ' + formatTime(castDuration));
- }
- function togglePlay() {
- $('#resume-popup').removeClass('active');
- if (castMode && _castConnected()) {
- if (castIsPlaying) {
- _castSend('media.pause', {});
- castIsPlaying = false;
- $('#play-icon').attr('src', 'img/icons/play_white.svg');
- } else {
- _castSend('media.play', {});
- castIsPlaying = true;
- $('#play-icon').attr('src', 'img/icons/pause_white.svg');
- }
- flashPlayState(castIsPlaying);
- return;
- }
- var vid = document.getElementById('main-video');
- var willPlay = vid.paused;
- if (willPlay) { playVideo(vid); } else { vid.pause(); }
- flashPlayState(willPlay);
- }
- function playOffset(offset) {
- var next = playingIndex + offset;
- if (next < 0) { next = 0; }
- if (next >= currentEpisodes.length) { next = currentEpisodes.length - 1; }
- if (next !== playingIndex) { startPlayback(next); }
- }
- function showControls() {
- $('#video-controls').removeClass('hidden');
- clearTimeout(controlsTimer);
- controlsTimer = setTimeout(function () {
- var isPlaying = castMode ? castIsPlaying : !document.getElementById('main-video').paused;
- // Keep the bar up while a popup is open — both are anchored to it
- if (isPlaying && !$('#settings-popup').hasClass('active') && !$('#subtitle-popup').hasClass('active')) {
- $('#video-controls').addClass('hidden');
- }
- }, 3000);
- }
- function toggleFullscreen() {
- var el = document.getElementById('view-player');
- if (!document.fullscreenElement) {
- el.requestFullscreen && el.requestFullscreen();
- } else {
- document.exitFullscreen && document.exitFullscreen();
- }
- }
- function toggleSidebar() {
- cancelPlaylistPeek(); // a manual toggle outranks a pending auto-close
- playlistUserToggled = true; // stop auto-management until the next playback
- $('#playlist-sidebar').toggleClass('collapsed');
- }
- function cancelPlaylistPeek() {
- if (playlistPeekTimer) { clearTimeout(playlistPeekTimer); playlistPeekTimer = null; }
- }
- // Skipping to another episode used to re-run applyPlaylistVisibility(), which
- // popped the sidebar open and left it there. Instead: leave an open playlist
- // alone, and let a closed one peek open just long enough to show what is playing
- // now — or not at all, when disabled in Advanced settings.
- function peekPlaylistForEpisodeChange() {
- cancelPlaylistPeek();
- var $sidebar = $('#playlist-sidebar');
- if (!$sidebar.hasClass('collapsed')) { return; } // already open — nothing to do
- if (disablePlaylistPeek) { return; }
- if (!currentEpisodes || currentEpisodes.length <= 1) { return; }
- $sidebar.removeClass('collapsed');
- playlistPeekTimer = setTimeout(function () {
- playlistPeekTimer = null;
- $('#playlist-sidebar').addClass('collapsed');
- // The peek is transient — keep a later resize from re-opening it
- playlistUserToggled = true;
- }, PLAYLIST_PEEK_MS);
- }
- // The playlist sidebar eats a lot of width, so it is only opened automatically
- // where there is room for it: a wide (desktop/laptop) viewport, or any device
- // held in landscape. A phone/tablet in portrait starts with it collapsed — the
- // list button in the player top bar still opens it on demand.
- function shouldAutoShowPlaylist() {
- if (!window.matchMedia) { return true; }
- return window.matchMedia('(min-width: 900px), (orientation: landscape)').matches;
- }
- function applyPlaylistVisibility() {
- var hasPlaylist = currentEpisodes && currentEpisodes.length > 1;
- $('#playlist-sidebar').toggleClass('collapsed', !(hasPlaylist && shouldAutoShowPlaylist()));
- }
- function startNextCountdown() {
- var total = 5;
- var remaining = total;
- var $bar = $('#next-countdown-bar');
- var $num = $('#countdown-num');
- $bar.css('transition', 'none').css('width', '100%');
- $num.text(remaining);
- $('#next-countdown').show();
- countdownTimer = setInterval(function () {
- remaining--;
- $num.text(remaining);
- $bar.css('transition', 'width 1s linear').css('width', (remaining / total * 100) + '%');
- if (remaining <= 0) { cancelCountdown(); playOffset(1); }
- }, 1000);
- }
- function cancelCountdown() {
- if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null; }
- $('#next-countdown').hide();
- }
- // ─── Player context menu ──────────────────────────────────────────────────────
- var infoRefreshTimer = null;
- var currentInfoTab = 'props';
- function initContextMenu() {
- var vid = document.getElementById('main-video');
- var $ctx = $('#player-ctx');
- // Right-click on the video container
- $('#video-container').on('contextmenu', function (e) {
- e.preventDefault();
- if (playingIndex < 0) { return; }
- // Update item disabled / active states
- var paused = castMode ? !castIsPlaying : vid.paused;
- $('#ctx-play').toggleClass('ctx-disabled', !paused);
- $('#ctx-pause').toggleClass('ctx-disabled', paused);
- $('#ctx-prev').toggleClass('ctx-disabled', playingIndex <= 0);
- $('#ctx-next').toggleClass('ctx-disabled', playingIndex >= currentEpisodes.length - 1);
- $('#ctx-repeat').toggleClass('ctx-active', repeatSingle)
- .html('<img class="ctx-icon" src="img/icons/'
- + (repeatSingle ? 'repeat_one_white.svg' : 'repeat_white.svg')
- + '" alt="">Repeat: ' + (repeatSingle ? 'On' : 'Off'));
- // Always collapse subtitle submenu on fresh open
- $('#ctx-subtitle-sub').hide();
- closeSettingsPopup();
- closeSubtitlePopup();
- // Position menu, clamp inside container
- var rect = this.getBoundingClientRect();
- var x = e.clientX - rect.left;
- var y = e.clientY - rect.top;
- $ctx.css({ left: x, top: y, display: 'block' });
- var mw = $ctx.outerWidth(), mh = $ctx.outerHeight();
- if (x + mw > rect.width) { $ctx.css('left', Math.max(0, x - mw)); }
- if (y + mh > rect.height) { $ctx.css('top', Math.max(0, y - mh)); }
- showControls();
- });
- // Dismiss on any click outside the menu
- $(document).on('mousedown.ctx', function (e) {
- if (!$(e.target).closest('#player-ctx').length) { $ctx.hide(); }
- });
- // Dismiss on Escape
- $(document).on('keydown.ctx', function (e) {
- if (e.key === 'Escape') { $ctx.hide(); closeVideoInfo(); closeSubtitleSettings(); }
- });
- $('#ctx-play').on('click', function () {
- if (castMode && _castConnected()) {
- _castSend('media.play', {}); castIsPlaying = true;
- $('#play-icon').attr('src', 'img/icons/pause_white.svg');
- } else { playVideo(vid); }
- flashPlayState(true);
- $ctx.hide();
- });
- $('#ctx-pause').on('click', function () {
- if (castMode && _castConnected()) {
- _castSend('media.pause', {}); castIsPlaying = false;
- $('#play-icon').attr('src', 'img/icons/play_white.svg');
- } else { vid.pause(); }
- flashPlayState(false);
- $ctx.hide();
- });
- $('#ctx-prev').on('click', function () { cancelCountdown(); playOffset(-1); $ctx.hide(); });
- $('#ctx-next').on('click', function () { cancelCountdown(); playOffset(1); $ctx.hide(); });
- $('#ctx-repeat').on('click', function () { setRepeatSingle(!repeatSingle); $ctx.hide(); });
- $('#ctx-subtitle-settings').on('click', function () { $ctx.hide(); openSubtitleSettings(); });
- $('#ctx-props').on('click', function () { $ctx.hide(); openVideoInfo('props'); });
- $('#ctx-stats').on('click', function () { $ctx.hide(); openVideoInfo('stats'); });
- }
- // Flash a large play/pause glyph in the centre of the video so the user gets
- // immediate feedback that their click / key press registered.
- function flashPlayState(isPlaying) {
- var $f = $('#play-flash');
- if (!$f.length) { return; }
- $('#play-flash-icon').attr('src',
- isPlaying ? 'img/icons/play_white.svg' : 'img/icons/pause_white.svg');
- $f.removeClass('flash');
- void $f[0].offsetWidth; // force reflow so the animation restarts
- $f.addClass('flash');
- }
- // ─── Playback settings popup (gear button) ────────────────────────────────────
- function setAlwaysShowVolumeBar(on) {
- alwaysShowVolumeBar = !!on;
- localStorage.setItem('movie_always_volume_bar', alwaysShowVolumeBar ? '1' : '0');
- $('body').toggleClass('always-show-volume', alwaysShowVolumeBar);
- $('#set-volbar-seg .set-seg-btn').removeClass('active')
- .filter('[data-volbar="' + (alwaysShowVolumeBar ? 'always' : 'auto') + '"]').addClass('active');
- }
- function setRepeatSingle(on) {
- repeatSingle = !!on;
- localStorage.setItem('movie_repeat_one', repeatSingle ? '1' : '0');
- $('#set-repeat-seg .set-seg-btn').removeClass('active')
- .filter('[data-repeat="' + (repeatSingle ? 'one' : 'off') + '"]').addClass('active');
- }
- // Apply a streaming mode. Changing it mid-playback re-opens the current file on
- // the other transport, resuming where the viewer was.
- function applyStreamMode(mode, reloadCurrent) {
- var previous = getStreamMode();
- setStreamMode(mode);
- $('#set-stream-seg .set-seg-btn').removeClass('active')
- .filter('[data-stream="' + getStreamMode() + '"]').addClass('active');
- if (!reloadCurrent || previous === getStreamMode()) { return; }
- // Warn only when the viewer actively picks a mode this browser cannot play
- warnIfStreamModeUnplayable();
- if (!isTranscodedVideo || playingIndex < 0 || !currentEpisodes[playingIndex]) { return; }
- // Restart the current file on the newly chosen transport, at the same spot.
- // Opening it directly at that offset rather than at zero avoids starting a
- // transcode from the beginning only to abandon it a moment later.
- var resumeAt = effectivePlaybackTime();
- var startAt = resumeAt > 1 ? resumeAt : 0;
- var vid = document.getElementById('main-video');
- transcodeSeekOffset = startAt;
- if (!attachTranscodeStream(vid, transcodeStreamURL(currentEpisodes[playingIndex].filepath, startAt),
- function (reason) { showToast(reason); },
- function () { playVideo(vid); })) {
- showToast('This browser cannot play the HLS stream.');
- }
- }
- function playerVideoElement() { return document.getElementById('main-video'); }
- // Surface the two streaming modes that cannot work on a given browser. Anything
- // that is simply working says nothing at all.
- function warnIfStreamModeUnplayable() {
- var mode = getStreamMode();
- if (mode === 'mp4' && isWebKitClient()) {
- showToast('This browser cannot play the MP4 stream. Use Auto or HLS.');
- } else if (mode === 'hls' && !hlsPlaybackSupported(playerVideoElement())) {
- showToast('This browser has no HLS support (needs Media Source Extensions).');
- }
- }
- function setPlaybackSpeed(rate) {
- playbackSpeed = parseFloat(rate) || 1;
- document.getElementById('main-video').playbackRate = playbackSpeed;
- localStorage.setItem('movie_playback_speed', String(playbackSpeed));
- $('#set-speed-grid .speed-btn').removeClass('active')
- .filter('[data-speed="' + playbackSpeed + '"]').addClass('active');
- }
- // Snap an arbitrary stored rate onto the nearest preset, so the popup always
- // has exactly one button highlighted. Needed because an earlier build persisted
- // free-form rates from a drag slider.
- function nearestPlaybackSpeed(rate) {
- var value = parseFloat(rate);
- if (!value || value <= 0) { return 1; }
- return PLAYBACK_SPEEDS.reduce(function (best, preset) {
- return Math.abs(preset - value) < Math.abs(best - value) ? preset : best;
- }, PLAYBACK_SPEEDS[0]);
- }
- // Cap a bottom-anchored popup's height so it never runs past the top edge of
- // the player (it only ever opens upward) — the popup's own scrollbar takes
- // over for whatever doesn't fit.
- function clampBottomPopupHeight($popup) {
- var container = document.getElementById('video-container');
- if (!container) { return; }
- var margin = 10;
- var containerRect = container.getBoundingClientRect();
- var popupRect = $popup[0].getBoundingClientRect();
- var available = popupRect.bottom - containerRect.top - margin;
- $popup.css('max-height', Math.max(120, available) + 'px');
- }
- function openSettingsPopup() {
- setRepeatSingle(repeatSingle);
- setPlaybackSpeed(playbackSpeed);
- setAlwaysShowVolumeBar(alwaysShowVolumeBar);
- applyStreamMode(getStreamMode(), false);
- $('#player-ctx').hide();
- closeSubtitlePopup();
- $('#settings-popup').addClass('active');
- clampBottomPopupHeight($('#settings-popup'));
- showControls();
- }
- function closeSettingsPopup() { $('#settings-popup').removeClass('active'); }
- function toggleSettingsPopup() {
- if ($('#settings-popup').hasClass('active')) { closeSettingsPopup(); }
- else { openSettingsPopup(); }
- }
- // ── Subtitle popup (dedicated CC button) ────────────────────────────────────
- function openSubtitlePopup() {
- updateSubtitleSubmenu();
- $('#player-ctx').hide();
- closeSettingsPopup();
- $('#subtitle-popup').addClass('active');
- clampBottomPopupHeight($('#subtitle-popup'));
- showControls();
- }
- function closeSubtitlePopup() { $('#subtitle-popup').removeClass('active'); }
- function toggleSubtitlePopup() {
- if ($('#subtitle-popup').hasClass('active')) { closeSubtitlePopup(); }
- else { openSubtitlePopup(); }
- }
- function initSubtitlePopup() {
- $('#ctrl-subtitle').on('click', function (e) {
- e.stopPropagation();
- toggleSubtitlePopup();
- });
- $(document).on('mousedown.subpop', function (e) {
- if (!$(e.target).closest('#subtitle-popup, #ctrl-subtitle').length) {
- closeSubtitlePopup();
- }
- });
- $('#sub-pop-disable').on('click', function () {
- activeSubtitleIndex = -1;
- stopAssTrack();
- $('#subtitle-display').hide();
- updateSubtitleSubmenu();
- closeSubtitlePopup();
- });
- $('#sub-pop-load').on('click', function () { closeSubtitlePopup(); pickSubtitleFile(); });
- $('#sub-pop-settings').on('click', function () { closeSubtitlePopup(); openSubtitleSettings(); });
- }
- function initSettingsPopup() {
- $('#ctrl-settings').on('click', function (e) {
- e.stopPropagation();
- toggleSettingsPopup();
- });
- // Dismiss when clicking anywhere outside the popup or its button
- $(document).on('mousedown.setpop', function (e) {
- if (!$(e.target).closest('#settings-popup, #ctrl-settings').length) {
- closeSettingsPopup();
- }
- });
- $('#set-repeat-seg').on('click', '.set-seg-btn', function () {
- setRepeatSingle($(this).data('repeat') === 'one');
- });
- $('#set-speed-grid').on('click', '.speed-btn', function () {
- setPlaybackSpeed($(this).data('speed'));
- });
- $('#set-volbar-seg').on('click', '.set-seg-btn', function () {
- setAlwaysShowVolumeBar($(this).data('volbar') === 'always');
- });
- $('#set-stream-seg').on('click', '.set-seg-btn', function () {
- applyStreamMode(String($(this).data('stream')), true);
- });
- $('#set-video-props').on('click', function () { closeSettingsPopup(); openVideoInfo('props'); });
- $('#set-advanced').on('click', function () { closeSettingsPopup(); openAdvancedSettings(); });
- $('#adv-no-playlist-peek').on('change', function () {
- disablePlaylistPeek = $(this).is(':checked');
- localStorage.setItem('movie_no_playlist_peek', disablePlaylistPeek ? '1' : '0');
- if (disablePlaylistPeek) { cancelPlaylistPeek(); }
- });
- // Apply persisted values to the video element
- setRepeatSingle(repeatSingle);
- setPlaybackSpeed(playbackSpeed);
- setAlwaysShowVolumeBar(alwaysShowVolumeBar);
- applyStreamMode(getStreamMode(), false);
- // Changing episode — or a transcode seek — replaces the media source, which
- // resets playbackRate. Reapply the chosen speed every time media loads.
- $('#main-video').on('loadedmetadata.speed', function () {
- this.playbackRate = playbackSpeed;
- });
- }
- function openVideoInfo(tab) {
- currentInfoTab = tab || 'props';
- closeAdvancedSettings();
- $('#video-info-modal').show();
- $('.info-tab').removeClass('active').eq(currentInfoTab === 'props' ? 0 : 1).addClass('active');
- $('#video-info-title').text(currentInfoTab === 'props' ? 'Video Properties' : 'Streaming Stats');
- renderInfoContent();
- if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
- if (currentInfoTab === 'stats') {
- infoRefreshTimer = setInterval(renderInfoContent, 1000);
- }
- }
- function closeVideoInfo() {
- $('#video-info-modal').hide();
- if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
- }
- function openAdvancedSettings() {
- closeVideoInfo();
- $('#adv-no-playlist-peek').prop('checked', disablePlaylistPeek);
- $('#adv-settings-modal').show();
- }
- function closeAdvancedSettings() { $('#adv-settings-modal').hide(); }
- function showInfoTab(tab) {
- currentInfoTab = tab;
- $('.info-tab').removeClass('active').eq(tab === 'props' ? 0 : 1).addClass('active');
- $('#video-info-title').text(tab === 'props' ? 'Video Properties' : 'Streaming Stats');
- if (infoRefreshTimer) { clearInterval(infoRefreshTimer); infoRefreshTimer = null; }
- if (tab === 'stats') { infoRefreshTimer = setInterval(renderInfoContent, 1000); }
- renderInfoContent();
- }
- function infoRow(label, value) {
- return '<div class="info-row"><span class="info-label">' + escapeHtml(String(label)) + '</span>'
- + '<span class="info-value">' + escapeHtml(String(value)) + '</span></div>';
- }
- function renderInfoContent() {
- var vid = document.getElementById('main-video');
- var ep = (playingIndex >= 0 && currentEpisodes[playingIndex]) ? currentEpisodes[playingIndex] : null;
- var html = '';
- if (currentInfoTab === 'props') {
- html += infoRow('Title', ep ? ep.name : '–');
- html += infoRow('Resolution', (vid.videoWidth && vid.videoHeight)
- ? vid.videoWidth + ' × ' + vid.videoHeight : '–');
- var infoDuration = isTranscodedVideo ? transcodeDuration : vid.duration;
- var infoPosition = isTranscodedVideo ? (vid.currentTime + transcodeSeekOffset) : vid.currentTime;
- html += infoRow('Duration', infoDuration ? formatTime(infoDuration) : '–');
- html += infoRow('Position', infoPosition ? formatTime(infoPosition) : '–');
- html += infoRow('Playback speed', vid.playbackRate + '×');
- html += infoRow('Volume', vid.muted ? 'Muted' : Math.round(vid.volume * 100) + '%');
- if (ep) { html += infoRow('File path', ep.filepath || '–'); }
- } else {
- var rsLabels = ['No info', 'Metadata only', 'Have current data', 'Have future data', 'Enough data'];
- var nsLabels = ['Empty', 'Idle', 'Loading', 'No source'];
- html += infoRow('Ready state', rsLabels[vid.readyState] || vid.readyState);
- html += infoRow('Network state', nsLabels[vid.networkState] || vid.networkState);
- // Buffer ahead
- var bufEnd = 0;
- if (vid.buffered && vid.buffered.length > 0) {
- for (var i = 0; i < vid.buffered.length; i++) {
- if (vid.buffered.start(i) <= vid.currentTime + 0.1) {
- bufEnd = Math.max(bufEnd, vid.buffered.end(i));
- }
- }
- }
- html += infoRow('Buffer ahead', Math.max(0, bufEnd - vid.currentTime).toFixed(1) + 's');
- html += infoRow('Total buffered', vid.buffered.length > 0
- ? formatTime(vid.buffered.end(vid.buffered.length - 1)) : '–');
- if (vid.getVideoPlaybackQuality) {
- var q = vid.getVideoPlaybackQuality();
- html += infoRow('Frames decoded', q.totalVideoFrames || 0);
- html += infoRow('Frames dropped', q.droppedVideoFrames || 0);
- }
- html += infoRow('Stalled / ended', vid.ended ? 'Ended' : (vid.readyState < 3 ? 'Yes' : 'No'));
- }
- $('#video-info-body').html(html);
- }
- function formatTime(s) {
- if (isNaN(s)) { return '0:00'; }
- var h = Math.floor(s / 3600);
- var m = Math.floor((s % 3600) / 60);
- var sec = Math.floor(s % 60);
- var parts = [];
- if (h > 0) { parts.push(h); }
- parts.push(m);
- parts.push(sec < 10 ? '0' + sec : sec);
- return parts.join(':');
- }
- // ─── Keyboard / TV-remote navigation ─────────────────────────────────────────
- function initKeyboard() {
- $(document).on('keydown', function (e) {
- var activeView = $('.view.active').attr('id');
- // ── Player shortcuts ──────────────────────────────────────────────────
- if (activeView === 'view-player') {
- var vid = document.getElementById('main-video');
- switch (e.key) {
- case ' ':
- case 'k':
- e.preventDefault(); togglePlay(); showControls(); break;
- case 'ArrowRight':
- e.preventDefault();
- if (castMode && _castConnected()) {
- _castSend('media.seekrel', { delta: 10 });
- castCurrentTime = Math.min(castDuration, castCurrentTime + 10);
- _castUpdateProgressUI();
- } else if (isTranscodedVideo && playingIndex >= 0 && currentEpisodes[playingIndex]) {
- transcodeSeekTo(effectivePlaybackTime() + 10);
- } else { vid.currentTime = Math.min(vid.duration || 0, vid.currentTime + 10); }
- showControls(); break;
- case 'ArrowLeft':
- e.preventDefault();
- if (castMode && _castConnected()) {
- _castSend('media.seekrel', { delta: -10 });
- castCurrentTime = Math.max(0, castCurrentTime - 10);
- _castUpdateProgressUI();
- } else if (isTranscodedVideo && playingIndex >= 0 && currentEpisodes[playingIndex]) {
- transcodeSeekTo(effectivePlaybackTime() - 10);
- } else { vid.currentTime = Math.max(0, vid.currentTime - 10); }
- showControls(); break;
- case 'ArrowUp':
- e.preventDefault(); vid.volume = Math.min(1, vid.volume + 0.1);
- if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
- showControls(); break;
- case 'ArrowDown':
- e.preventDefault(); vid.volume = Math.max(0, vid.volume - 0.1);
- if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
- showControls(); break;
- case 'f':
- case 'F':
- e.preventDefault(); toggleFullscreen(); break;
- case 'm':
- case 'M':
- e.preventDefault(); vid.muted = !vid.muted;
- if (castMode && _castConnected()) { _castSend('media.volume', { volume: vid.volume * 100, muted: vid.muted }); }
- break;
- case 'l':
- case 'L':
- e.preventDefault(); toggleSidebar(); break;
- case 's':
- case 'S':
- e.preventDefault(); toggleSettingsPopup(); break;
- case 'r':
- case 'R':
- e.preventDefault();
- setRepeatSingle(!repeatSingle);
- showToast('Repeat: ' + (repeatSingle ? 'On' : 'Off')); break;
- case 'n':
- e.preventDefault(); playOffset(1); break;
- case 'p':
- e.preventDefault(); playOffset(-1); break;
- case 'Escape':
- e.preventDefault();
- // Escape dismisses an open overlay first; only closes the
- // player once nothing is layered on top of it.
- if ($('#settings-popup').hasClass('active') ||
- $('#subtitle-popup').hasClass('active') ||
- $('#player-ctx').is(':visible') ||
- $('#video-info-modal').is(':visible') ||
- $('#adv-settings-modal').is(':visible') ||
- $('#subtitle-settings-modal').is(':visible')) {
- closeSettingsPopup();
- closeSubtitlePopup();
- $('#player-ctx').hide();
- closeVideoInfo();
- closeAdvancedSettings();
- closeSubtitleSettings();
- } else {
- closePlayer();
- }
- break;
- case 'MediaPlayPause':
- e.preventDefault(); togglePlay(); break;
- case 'MediaTrackNext':
- e.preventDefault(); playOffset(1); break;
- case 'MediaTrackPrevious':
- e.preventDefault(); playOffset(-1); break;
- }
- return;
- }
- // ── Grid / detail navigation (TV remote) ──────────────────────────────
- if (e.key === 'Escape') {
- e.preventDefault();
- if (activeView === 'view-detail') { showLibrary(); }
- return;
- }
- if (['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Enter'].indexOf(e.key) === -1) { return; }
- e.preventDefault();
- focusMode = true;
- var $focusables = $('.view.active [tabindex="0"]:visible');
- if ($focusables.length === 0) { return; }
- var $cur = $(document.activeElement);
- var curIdx = $focusables.index($cur);
- if (curIdx < 0) {
- // Nothing focused yet – focus first element
- $focusables.first().focus();
- return;
- }
- if (e.key === 'Enter') {
- $cur.trigger('click');
- return;
- }
- // Compute next focus index based on grid layout
- var nextIdx = computeNextFocus($focusables, curIdx, e.key);
- if (nextIdx >= 0 && nextIdx < $focusables.length) {
- $focusables.eq(nextIdx).focus();
- $focusables.eq(nextIdx)[0].scrollIntoView({ block: 'nearest', inline: 'nearest' });
- }
- });
- }
- function computeNextFocus($els, curIdx, key) {
- if (key === 'ArrowDown') { return Math.min($els.length - 1, curIdx + 1); }
- if (key === 'ArrowUp') { return Math.max(0, curIdx - 1); }
- // For left/right in a grid, figure out how many columns there are
- var $cur = $els.eq(curIdx);
- var $parent = $cur.parent();
- if ($parent.hasClass('album-grid')) {
- var colCount = Math.round($parent.width() / ($cur.outerWidth(true) || 1)) || 1;
- if (key === 'ArrowRight') { return Math.min($els.length - 1, curIdx + 1); }
- if (key === 'ArrowLeft') { return Math.max(0, curIdx - 1); }
- }
- if (key === 'ArrowRight') { return Math.min($els.length - 1, curIdx + 1); }
- if (key === 'ArrowLeft') { return Math.max(0, curIdx - 1); }
- return curIdx;
- }
- // ─── Search ───────────────────────────────────────────────────────────────────
- function initSearch() {
- $('#search-input').on('input', function () {
- var q = $(this).val().trim().toLowerCase();
- if (q.length === 0) {
- renderLibrary(library);
- return;
- }
- var filtered = library.filter(function (a) {
- return a.name.toLowerCase().indexOf(q) > -1;
- });
- renderLibrary(filtered);
- });
- // Prevent keyboard nav from hijacking search input
- $('#search-input').on('keydown', function (e) {
- e.stopPropagation();
- if (e.key === 'Escape') { $(this).val(''); renderLibrary(library); $(this).blur(); }
- });
- }
- // ─── Utilities ────────────────────────────────────────────────────────────────
- function escapeHtml(str) {
- if (!str) { return ''; }
- return String(str)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"');
- }
- function escapeAttr(str) { return escapeHtml(str); }
- // ─── Subtitle settings ────────────────────────────────────────────────────────
- var subtitleSettings = { position: 'bottom', size: 22, font: 'system-ui, sans-serif', color: '#ffffff' };
- function loadSubtitleSettings() {
- try {
- var s = JSON.parse(localStorage.getItem('movie_subtitle_settings') || 'null');
- if (s) { Object.assign(subtitleSettings, s); }
- } catch (e) {}
- }
- function saveSubtitleSettings() {
- localStorage.setItem('movie_subtitle_settings', JSON.stringify(subtitleSettings));
- }
- function applySubtitleSettings() {
- var s = subtitleSettings;
- var $d = $('#subtitle-display');
- $d.css({
- 'font-size': s.size + 'px',
- 'font-family': s.font,
- 'color': s.color,
- 'bottom': s.position === 'bottom' ? '72px' : 'auto',
- 'top': s.position === 'top' ? '72px' : 'auto',
- 'transform': 'translateX(-50%)'
- });
- }
- function syncSettingsPreview() {
- var s = subtitleSettings;
- $('#sset-preview').css({
- 'font-size': s.size + 'px',
- 'font-family': s.font,
- 'color': s.color,
- 'text-shadow': '-1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000, 0 2px 6px rgba(0,0,0,0.85)'
- });
- }
- function openSubtitleSettings() {
- var s = subtitleSettings;
- // Sync all controls to current state
- $('.sset-seg-btn').removeClass('active')
- .filter('[data-val="' + s.position + '"]').addClass('active');
- $('#sset-size').val(s.size);
- $('#sset-size-val').text(s.size + 'px');
- $('#sset-font').val(s.font);
- var swatchMatch = $('.sset-color[data-color="' + s.color.toLowerCase() + '"]');
- $('.sset-color, #sset-color-custom').removeClass('active');
- if (swatchMatch.length) { swatchMatch.addClass('active'); }
- else { $('#sset-color-custom').addClass('active'); }
- $('#sset-color-custom').val(s.color);
- syncSettingsPreview();
- $('#subtitle-settings-modal').show();
- }
- function closeSubtitleSettings() {
- $('#subtitle-settings-modal').hide();
- }
- function initSubtitleSettings() {
- loadSubtitleSettings();
- applySubtitleSettings();
- $('#sset-close').on('click', closeSubtitleSettings);
- // Position
- $(document).on('click', '.sset-seg-btn', function () {
- subtitleSettings.position = $(this).data('val');
- $('.sset-seg-btn').removeClass('active');
- $(this).addClass('active');
- applySubtitleSettings();
- saveSubtitleSettings();
- });
- // Size
- $('#sset-size').on('input', function () {
- subtitleSettings.size = parseInt($(this).val(), 10);
- $('#sset-size-val').text(subtitleSettings.size + 'px');
- applySubtitleSettings();
- syncSettingsPreview();
- saveSubtitleSettings();
- });
- // Font
- $('#sset-font').on('change', function () {
- subtitleSettings.font = $(this).val();
- ensureEmbeddedFontLoaded(subtitleSettings.font); // no-op for built-in fonts
- applySubtitleSettings();
- syncSettingsPreview();
- saveSubtitleSettings();
- });
- // Preset color swatches
- $(document).on('click', '.sset-color', function () {
- subtitleSettings.color = $(this).data('color');
- $('.sset-color, #sset-color-custom').removeClass('active');
- $(this).addClass('active');
- $('#sset-color-custom').val(subtitleSettings.color);
- applySubtitleSettings();
- syncSettingsPreview();
- saveSubtitleSettings();
- });
- // Custom color picker
- $('#sset-color-custom').on('input', function () {
- subtitleSettings.color = $(this).val();
- $('.sset-color').removeClass('active');
- $('#sset-color-custom').addClass('active');
- applySubtitleSettings();
- syncSettingsPreview();
- saveSubtitleSettings();
- });
- }
- // ─── Subtitle ─────────────────────────────────────────────────────────────────
- var loadedSubtitleFiles = []; // [{path, name, cues:[{start,end,text}]}]
- var activeSubtitleIndex = -1; // -1 = disabled
- // Window-scoped callback required by ao_module file selector.
- // The selector always delivers [{filename, filepath}, …]; handle gracefully.
- window.movieOnSubtitleFile = function (raw) {
- console.log('[subtitle] callback fired, raw value:', raw);
- // Unwrap array
- var entry = Array.isArray(raw) ? raw[0] : raw;
- console.log('[subtitle] unwrapped entry:', entry);
- // Accept either a plain object {filename, filepath} or a bare string path
- var filePath = (entry && typeof entry === 'object') ? entry.filepath : entry;
- console.log('[subtitle] resolved filePath:', filePath);
- if (!filePath || typeof filePath !== 'string') {
- console.warn('[subtitle] unexpected callback payload — aborting', raw);
- return;
- }
- var url = MEDIA_API + '?file=' + encodeURIComponent(filePath);
- console.log('[subtitle] fetching:', url);
- $.ajax({
- url: url,
- dataType: 'text',
- success: function (content) {
- console.log('[subtitle] file fetched, length:', content.length);
- var name = filePath.replace(/\\/g, '/').split('/').pop();
- var cues = parseSrt(content);
- console.log('[subtitle] parsed cues:', cues.length);
- var existing = -1;
- loadedSubtitleFiles.forEach(function (sf, i) {
- if (sf.path === filePath) { existing = i; }
- });
- if (existing >= 0) {
- loadedSubtitleFiles[existing].cues = cues;
- activeSubtitleIndex = existing;
- } else {
- loadedSubtitleFiles.push({ path: filePath, name: name, cues: cues });
- activeSubtitleIndex = loadedSubtitleFiles.length - 1;
- }
- showToast('Subtitle loaded: ' + name);
- applyActiveSubtitle(); // a sidecar file replaces any styled track
- updateSubtitleSubmenu();
- },
- error: function (xhr, status, err) {
- console.error('[subtitle] fetch failed:', status, err, url);
- showToast('Failed to load subtitle file');
- }
- });
- };
- function parseSrtTime(t) {
- var m = t.match(/(\d+):(\d+):(\d+)[,.](\d+)/);
- if (!m) { return 0; }
- return parseInt(m[1]) * 3600 + parseInt(m[2]) * 60 + parseInt(m[3]) + parseInt(m[4]) / 1000;
- }
- function parseSrt(content) {
- var cues = [];
- var blocks = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim().split(/\n\n+/);
- blocks.forEach(function (block) {
- var lines = block.split('\n');
- var tcIdx = -1;
- for (var i = 0; i < lines.length; i++) {
- if (lines[i].indexOf('-->') !== -1) { tcIdx = i; break; }
- }
- if (tcIdx < 0) { return; }
- var parts = lines[tcIdx].split('-->');
- if (parts.length < 2) { return; }
- var start = parseSrtTime(parts[0].trim());
- var end = parseSrtTime(parts[1].trim().split(' ')[0]);
- // Strip inline SRT tags like <b>, <i>, <u>, <font>, plus any ASS
- // override blocks such as {\an8} or {\pos(x,y)}. ffmpeg's ASS-to-SubRip
- // conversion leaves positioning tags like those behind, so without this
- // they would be shown to the viewer as literal text.
- var text = lines.slice(tcIdx + 1).join('\n').trim()
- .replace(/<[^>]+>/g, '')
- .replace(/\{\\[^}]*\}/g, '')
- .trim();
- if (text) { cues.push({ start: start, end: end, text: text }); }
- });
- return cues;
- }
- function updateSubtitleDisplay() {
- // Styled tracks are drawn by the ASS renderer on its own frame loop
- if (assActive) { $('#subtitle-display').hide(); return; }
- if (activeSubtitleIndex < 0 || !loadedSubtitleFiles[activeSubtitleIndex]) {
- $('#subtitle-display').hide();
- return;
- }
- var currentTime = document.getElementById('main-video').currentTime;
- var cues = loadedSubtitleFiles[activeSubtitleIndex].cues;
- var found = null;
- for (var i = 0; i < cues.length; i++) {
- if (cues[i].start < subtitleSeekFloor) { continue; } // in flight when we landed
- if (currentTime >= cues[i].start && currentTime <= cues[i].end) {
- found = cues[i]; break;
- }
- }
- if (found) {
- $('#subtitle-display').html(escapeHtml(found.text).replace(/\n/g, '<br>')).show();
- } else {
- $('#subtitle-display').hide();
- }
- }
- // ─── Embedded subtitle tracks and fonts ───────────────────────────────────────
- // MKV releases usually mux their subtitles (and the fonts they were typeset in)
- // into the container rather than shipping sidecar files. The server lists them
- // and extracts on demand; tracks are converted to SubRip, which keeps the text
- // and timing but drops ASS styling, positioning and karaoke.
- var embeddedSubtitles = []; // [{index, codec, language, title, forced, textual}]
- var embeddedFonts = []; // [{index, filename, mimetype}]
- var embeddedMediaPath = null; // file the two lists above describe
- var embeddedProbeToken = 0; // invalidates in-flight probes on episode change
- var embeddedFontFaces = []; // FontFace objects registered for this video
- var embeddedFontsLoaded = {}; // family name -> already fetched
- function resetEmbeddedTracks() {
- embeddedProbeToken++;
- stopAssTrack();
- embeddedSubtitles = [];
- embeddedFonts = [];
- embeddedMediaPath = null;
- // Font families are keyed by attachment ordinal, which means the same name
- // refers to a different font in the next video — drop the old faces.
- embeddedFontFaces.forEach(function (face) {
- try { document.fonts.delete(face); } catch (e) {}
- });
- embeddedFontFaces = [];
- embeddedFontsLoaded = {};
- }
- function loadEmbeddedTrackList(filepath) {
- resetEmbeddedTracks();
- if (!filepath) { return; }
- embeddedMediaPath = filepath;
- var token = embeddedProbeToken;
- fetch(SUBTITLE_API + '?file=' + encodeURIComponent(filepath))
- .then(function (r) { return r.json(); })
- .then(function (info) {
- if (token !== embeddedProbeToken) { return; } // episode changed
- if (!info || info.error) { return; }
- embeddedSubtitles = info.subtitles || [];
- embeddedFonts = info.fonts || [];
- updateSubtitleSubmenu();
- refreshEmbeddedFontOptions();
- })
- .catch(function () {}); // embedded tracks are a bonus — fail quietly
- }
- function embeddedTrackLabel(track, position) {
- var label = track.title || '';
- if (!label) { label = 'Track ' + (position + 1); }
- if (track.language) { label += ' [' + track.language + ']'; }
- if (track.forced) { label += ' (forced)'; }
- if (!track.textual) { label += ' — image based'; }
- return label;
- }
- // Extraction has to scan the whole container, so it takes a few seconds on a
- // large file. Results are kept in loadedSubtitleFiles, making reselection free.
- function selectEmbeddedSubtitle(track, position) {
- if (!track.textual) {
- showToast('That track is image based and cannot be displayed');
- return;
- }
- var cacheKey = 'embedded#' + track.index + '@' + embeddedMediaPath;
- for (var i = 0; i < loadedSubtitleFiles.length; i++) {
- if (loadedSubtitleFiles[i].path === cacheKey) {
- activeSubtitleIndex = i;
- applyActiveSubtitle();
- updateSubtitleSubmenu();
- return;
- }
- }
- // ASS/SSA is fetched in its native form so the styling survives; everything
- // else comes through as SubRip for the plain renderer.
- var styled = /^(ass|ssa)$/i.test(track.codec) && typeof ASS !== 'undefined';
- var mediaPath = embeddedMediaPath;
- var url = SUBTITLE_API + '?file=' + encodeURIComponent(mediaPath) + '&track=' + track.index
- + (styled ? '&format=ass' : '');
- showToast('Extracting subtitle track…');
- $.ajax({
- url: url,
- dataType: 'text',
- success: function (content) {
- if (mediaPath !== embeddedMediaPath) { return; } // episode changed
- if (styled) {
- var parsed = ASS.parse(content);
- if (!parsed.events.length) {
- showToast('That track contained no readable text');
- return;
- }
- loadedSubtitleFiles.push({
- path: cacheKey,
- name: embeddedTrackLabel(track, position),
- cues: [],
- assTrack: parsed
- });
- activeSubtitleIndex = loadedSubtitleFiles.length - 1;
- applyActiveSubtitle();
- updateSubtitleSubmenu();
- showToast('Subtitle loaded · ' + parsed.events.length + ' styled lines');
- return;
- }
- var cues = parseSrt(content);
- if (cues.length === 0) {
- showToast('That track contained no readable text');
- return;
- }
- loadedSubtitleFiles.push({
- path: cacheKey,
- name: embeddedTrackLabel(track, position),
- cues: cues
- });
- activeSubtitleIndex = loadedSubtitleFiles.length - 1;
- applyActiveSubtitle();
- updateSubtitleSubmenu();
- showToast('Subtitle loaded · ' + cues.length + ' lines');
- },
- error: function () { showToast('Could not extract that subtitle track'); }
- });
- }
- // Switch the display between the styled ASS renderer and the plain SubRip
- // overlay depending on what the newly selected track carries.
- function applyActiveSubtitle() {
- var entry = activeSubtitleIndex >= 0 ? loadedSubtitleFiles[activeSubtitleIndex] : null;
- if (entry && entry.assTrack) {
- startAssTrack(entry.assTrack);
- } else {
- stopAssTrack();
- updateSubtitleDisplay();
- }
- }
- // ─── Subtitle seek floor ──────────────────────────────────────────────────────
- // After a seek, any line that had already begun before the landing point is
- // skipped entirely; only lines that start at or after it are shown. Seeking to
- // 1:02 with lines at 1:00-1:03 and 1:05-1:10 therefore shows nothing until 1:05.
- var subtitleSeekFloor = 0;
- function setSubtitleSeekFloor(time) {
- subtitleSeekFloor = Math.max(0, time || 0);
- if (assRenderer) { assRenderer.setSuppressBefore(subtitleSeekFloor); }
- updateSubtitleDisplay();
- }
- function resetSubtitleSeekFloor() { setSubtitleSeekFloor(0); }
- // ─── Styled ASS rendering ─────────────────────────────────────────────────────
- // ASS tracks are fetched in their native form and drawn by script/ass.js, which
- // preserves per-line styling and position. That is what makes dual-language
- // releases work: the Japanese and Chinese lines are separate events shown at the
- // same time, and a single-cue renderer can only ever display one of them.
- var assRenderer = null;
- var assActive = false;
- var assFrameReq = null;
- function initAssRenderer() {
- var overlay = document.getElementById('ass-overlay');
- if (overlay && typeof ASS !== 'undefined') { assRenderer = new ASS.Renderer(overlay); }
- }
- // Match the overlay to the letterboxed picture inside the video element, so
- // script coordinates map onto what the viewer actually sees.
- function syncAssOverlayGeometry() {
- if (!assRenderer) { return; }
- var vid = document.getElementById('main-video');
- var overlay = document.getElementById('ass-overlay');
- var cw = vid.clientWidth, ch = vid.clientHeight;
- var vw = vid.videoWidth, vh = vid.videoHeight;
- // Until the decoder reports the picture size there is no way to know where
- // the letterbox bars are. Falling back to the raw element box would scale
- // the script against the black bars too and push bottom-anchored lines down
- // over the controls, so keep the last known good geometry instead.
- if (!(vw > 0 && vh > 0 && cw > 0 && ch > 0)) { return; }
- var scale = Math.min(cw / vw, ch / vh);
- var width = vw * scale;
- var height = vh * scale;
- var left = (cw - width) / 2;
- var top = (ch - height) / 2;
- if (overlay._w !== width || overlay._h !== height || overlay._l !== left || overlay._t !== top) {
- overlay._w = width; overlay._h = height; overlay._l = left; overlay._t = top;
- overlay.style.left = left + 'px';
- overlay.style.top = top + 'px';
- overlay.style.width = width + 'px';
- overlay.style.height = height + 'px';
- assRenderer.resize(width, height);
- }
- }
- function startAssTrack(track) {
- if (!assRenderer) { return; }
- stopAssTrack();
- assRenderer.setTrack(track);
- assActive = true;
- $('#ass-overlay').addClass('active');
- $('#subtitle-display').hide(); // the plain renderer must not double up
- loadAssFonts(track);
- var step = function () {
- if (!assActive) { return; }
- syncAssOverlayGeometry();
- assRenderer.setTime(effectivePlaybackTime());
- assFrameReq = requestAnimationFrame(step);
- };
- step();
- }
- function stopAssTrack() {
- assActive = false;
- if (assFrameReq) { cancelAnimationFrame(assFrameReq); assFrameReq = null; }
- if (assRenderer) { assRenderer.clear(); }
- $('#ass-overlay').removeClass('active');
- }
- // Only pull the fonts the track actually references — a release can attach a
- // dozen and use half of them.
- function loadAssFonts(track) {
- if (typeof ASS === 'undefined') { return; }
- ASS.referencedFonts(track).forEach(function (family) {
- ensureEmbeddedFontLoaded(family);
- });
- }
- // ─── Embedded fonts ───────────────────────────────────────────────────────────
- // Registered under the font's own internal family name, which is what ASS styles
- // reference, and offered in Subtitle Settings for SubRip tracks. Fetched lazily:
- // a release can carry a dozen fonts and only a few are ever used.
- function embeddedFontFamily(font) {
- return font.family || ('aroz-embedded-' + font.index);
- }
- function findEmbeddedFontByFamily(family) {
- var wanted = String(family || '').replace(/^@/, '').toLowerCase();
- var found = null;
- embeddedFonts.forEach(function (f) {
- if (embeddedFontFamily(f).toLowerCase() === wanted) { found = f; }
- });
- return found;
- }
- function refreshEmbeddedFontOptions() {
- var $select = $('#sset-font');
- $select.find('optgroup.embedded-fonts').remove();
- if (embeddedFonts.length > 0) {
- var $group = $('<optgroup label="Embedded in this video" class="embedded-fonts"></optgroup>');
- embeddedFonts.forEach(function (font) {
- $group.append($('<option></option>')
- .attr('value', embeddedFontFamily(font))
- .text(font.filename || ('Font ' + (font.index + 1))));
- });
- $select.append($group);
- }
- // A font picked for a previous video may not exist in this one. Anything no
- // longer offered by the dropdown (built-in or embedded) falls back.
- var stillOffered = $select.find('option').filter(function () {
- return this.value === subtitleSettings.font;
- }).length > 0;
- if (!stillOffered) {
- subtitleSettings.font = 'system-ui, sans-serif';
- applySubtitleSettings();
- saveSubtitleSettings();
- }
- $select.val(subtitleSettings.font);
- ensureEmbeddedFontLoaded(subtitleSettings.font);
- }
- function ensureEmbeddedFontLoaded(family) {
- if (!family || embeddedFontsLoaded[family] || !embeddedMediaPath) { return; }
- if (typeof FontFace === 'undefined' || !document.fonts) { return; }
- var meta = findEmbeddedFontByFamily(family);
- if (!meta) { return; } // a built-in font, or one this video does not carry
- embeddedFontsLoaded[family] = true; // claim it so we do not refetch in a loop
- var url = SUBTITLE_API + '?file=' + encodeURIComponent(embeddedMediaPath) + '&font=' + meta.index;
- var face = new FontFace(embeddedFontFamily(meta), 'url("' + url + '")');
- face.load().then(function (loaded) {
- document.fonts.add(loaded);
- embeddedFontFaces.push(loaded);
- applySubtitleSettings();
- syncSettingsPreview();
- // The renderer sizes every run off the face's own ascent/descent, so a
- // face arriving late invalidates the measurements taken against the
- // fallback it was standing in for.
- if (typeof ASS !== 'undefined' && ASS.invalidateFontMetrics) { ASS.invalidateFontMetrics(); }
- if (assRenderer) { assRenderer.clear(); } // redraw with the real face
- }).catch(function () {
- embeddedFontsLoaded[family] = false;
- });
- }
- // Builds the track list (Disable / embedded tracks / loaded sidecar files) into
- // one menu, given its "Disable" and "Load" anchor items — shared by the
- // right-click context submenu and the dedicated CC button popup so both stay
- // in sync from a single call to updateSubtitleSubmenu().
- function populateSubtitleTrackList($disable, $load, onSelect) {
- $disable.siblings('.ctx-sub-dynamic').remove();
- var disabled = (activeSubtitleIndex < 0);
- $disable.toggleClass('ctx-active', disabled)
- .find('.ctx-icon').text(disabled ? '✓' : '');
- // Tracks muxed into the video, listed whether or not they are loaded yet
- if (embeddedSubtitles.length > 0) {
- $('<div class="ctx-divider ctx-sub-dynamic"></div>').insertBefore($load);
- embeddedSubtitles.forEach(function (track, position) {
- var cacheKey = 'embedded#' + track.index + '@' + embeddedMediaPath;
- var isActive = activeSubtitleIndex >= 0 &&
- loadedSubtitleFiles[activeSubtitleIndex] &&
- loadedSubtitleFiles[activeSubtitleIndex].path === cacheKey;
- $('<div class="ctx-item ctx-sub-dynamic'
- + (isActive ? ' ctx-active' : '')
- + (track.textual ? '' : ' ctx-disabled') + '">'
- + '<i class="ctx-icon">' + (isActive ? '✓' : '') + '</i>'
- + escapeHtml(embeddedTrackLabel(track, position))
- + '</div>')
- .on('click', function () {
- selectEmbeddedSubtitle(track, position);
- onSelect();
- })
- .insertBefore($load);
- });
- }
- // Sidecar files the user loaded by hand
- var external = [];
- loadedSubtitleFiles.forEach(function (sf, idx) {
- if (String(sf.path).indexOf('embedded#') !== 0) { external.push({ sf: sf, idx: idx }); }
- });
- if (external.length > 0) {
- $('<div class="ctx-divider ctx-sub-dynamic"></div>').insertBefore($load);
- external.forEach(function (entry) {
- var isActive = (entry.idx === activeSubtitleIndex);
- $('<div class="ctx-item ctx-sub-dynamic' + (isActive ? ' ctx-active' : '') + '" data-sub-idx="' + entry.idx + '">' +
- '<i class="ctx-icon">' + (isActive ? '✓' : '') + '</i>' +
- escapeHtml(entry.sf.name) +
- '</div>')
- .on('click', function () {
- activeSubtitleIndex = parseInt($(this).data('sub-idx'), 10);
- applyActiveSubtitle();
- updateSubtitleSubmenu();
- onSelect();
- })
- .insertBefore($load);
- });
- }
- }
- function updateSubtitleSubmenu() {
- populateSubtitleTrackList($('#ctx-sub-disable'), $('#ctx-sub-load'), function () {
- $('#player-ctx').hide();
- });
- populateSubtitleTrackList($('#sub-pop-disable'), $('#sub-pop-load'), function () {
- closeSubtitlePopup();
- });
- if ($('#subtitle-popup').hasClass('active')) { clampBottomPopupHeight($('#subtitle-popup')); }
- }
- function initSubtitleMenu() {
- var $ctx = $('#player-ctx');
- var $parent = $('#ctx-subtitle-parent');
- var $sub = $('#ctx-subtitle-sub');
- var subHideTimer;
- function cancelSubHide() { clearTimeout(subHideTimer); }
- function scheduleSubHide() {
- subHideTimer = setTimeout(function () { $sub.hide(); }, 120);
- }
- $parent.on('mouseenter', function () {
- cancelSubHide();
- // Flip submenu left if it would overflow the video container
- var ctxRight = $ctx.offset().left + $ctx.outerWidth();
- var subWidth = 200; // min-width; use before it's visible
- var containerRight = $('#video-container').offset().left + $('#video-container').outerWidth();
- if (ctxRight + subWidth > containerRight) {
- $sub.css({ left: 'auto', right: '100%' });
- } else {
- $sub.css({ left: '100%', right: 'auto' });
- }
- // Clamp vertically so the submenu never runs past the container edge —
- // flip to open upward when there's more room above than below, and
- // cap its height to whichever side it opens on (scrollbar handles the rest).
- var margin = 10;
- var containerRect = document.getElementById('video-container').getBoundingClientRect();
- var parentRect = this.getBoundingClientRect();
- var spaceBelow = containerRect.bottom - parentRect.top - margin;
- var spaceAbove = parentRect.bottom - containerRect.top - margin;
- if (spaceBelow < 160 && spaceAbove > spaceBelow) {
- $sub.css({ top: 'auto', bottom: 0, maxHeight: Math.max(120, spaceAbove) + 'px' });
- } else {
- $sub.css({ top: 0, bottom: 'auto', maxHeight: Math.max(120, spaceBelow) + 'px' });
- }
- $sub.show();
- });
- $parent.on('mouseleave', scheduleSubHide);
- $sub.on('mouseenter', cancelSubHide);
- $sub.on('mouseleave', scheduleSubHide);
- $('#ctx-sub-disable').on('click', function () {
- activeSubtitleIndex = -1;
- stopAssTrack();
- $('#subtitle-display').hide();
- updateSubtitleSubmenu();
- $ctx.hide();
- });
- $('#ctx-sub-load').on('click', function () {
- $ctx.hide();
- pickSubtitleFile();
- });
- document.getElementById('main-video')
- .addEventListener('timeupdate', updateSubtitleDisplay);
- }
- // Open the ArozOS file selector, defaulted to the folder of the playing file
- function pickSubtitleFile() {
- var startDir = 'user:/';
- if (playingIndex >= 0 && currentEpisodes[playingIndex]) {
- var fp = currentEpisodes[playingIndex].filepath.replace(/\\/g, '/');
- var slash = fp.lastIndexOf('/');
- if (slash > 0) { startDir = fp.substring(0, slash); }
- }
- ao_module_openFileSelector(
- window.movieOnSubtitleFile,
- startDir, 'file', false,
- { fnameOverride: 'movieOnSubtitleFile', extAllowed: '.srt' }
- );
- }
- var toastTimer;
- function showToast(msg) {
- clearTimeout(toastTimer);
- $('#toast').text(msg).addClass('show');
- toastTimer = setTimeout(function () { $('#toast').removeClass('show'); }, 2800);
- }
- // play() returns a promise that rejects when the browser will not start the
- // media — most commonly NotSupportedError on Safari, which refuses a transcoded
- // stream because the endpoint cannot answer byte-range requests. Left
- // unhandled it only shows up as an unhandled rejection in the console, so the
- // player just sits there with no explanation. Surface it instead.
- function playVideo(v) {
- var p = v.play();
- if (p && typeof p.catch === 'function') {
- p.catch(function (err) {
- if (err && err.name === 'AbortError') {
- // Fired whenever a load or a new src interrupts a pending
- // play() — routine during seek-by-reload, not a failure.
- return;
- }
- if (err && err.name === 'NotSupportedError') {
- showToast('This browser cannot play this transcoded format. Try Chrome or Firefox.');
- } else {
- showToast('Playback failed: ' + ((err && err.message) || 'unknown error'));
- }
- });
- }
- return p;
- }
- </script>
- </body>
- </html>
|