common.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. /*
  2. Movie App - Common Configuration
  3. If the app folder is renamed, update APP_NAME below and all paths
  4. will automatically adjust everywhere this file is included via requirepkg().
  5. */
  6. // ── App identity ─────────────────────────────────────────────────────────────
  7. var APP_NAME = "Movie";
  8. var BACKEND_PATH = APP_NAME + "/backend/";
  9. // ── Server API endpoints (relative from any page in this app) ────────────────
  10. var MEDIA_API = "../media"; // ?file=<vpath> streams a file
  11. var TRANSCODE_API = "../media/transcode"; // ?file
  12. var HLS_API = "../media/hls"; // ?file same transcode, as an HLS playlist
  13. var PROBE_API = "../media/probe/"; // ?file real codecs + playability
  14. var STORYBOARD_API = "../media/storyboard/"; // ?file[&image=1] scrub previews
  15. var SUBTITLE_API = "../media/subtitles/"; // ?file[&track=n|&font=n] embedded tracks
  16. var AGI_INTERFACE = "../system/ajgi/interface?script=";
  17. // ── Script paths (used when calling ao_module_agirun from the frontend) ──────
  18. var SCRIPT_GET_LIBRARY = BACKEND_PATH + "getLibrary.js";
  19. var SCRIPT_GET_LIBRARY_CACHE = BACKEND_PATH + "getLibraryCache.js";
  20. var SCRIPT_GET_EPISODES = BACKEND_PATH + "getEpisodes.js";
  21. var SCRIPT_GET_THUMBNAIL = BACKEND_PATH + "getThumbnail.js";
  22. var SCRIPT_LIST_FOLDER = BACKEND_PATH + "listFolder.js";
  23. var SCRIPT_GET_MOVIE_INFO = BACKEND_PATH + "getMovieInfo.js";
  24. var SCRIPT_DISABLE_MOVIE_INFO = BACKEND_PATH + "disableMovieInfo.js";
  25. var SCRIPT_GET_WATCHTIME = BACKEND_PATH + "getWatchTime.js";
  26. var SCRIPT_SET_WATCHTIME = BACKEND_PATH + "setWatchTime.js";
  27. var SCRIPT_GET_INDEX_STATS = BACKEND_PATH + "getIndexStats.js";
  28. var SCRIPT_CLEAR_INDEX = BACKEND_PATH + "clearIndex.js";
  29. // ── Streaming mode ───────────────────────────────────────────────────────────
  30. // Formats the browser cannot decode are transcoded on the fly, and there are
  31. // two ways to deliver that transcode:
  32. //
  33. // mp4 a single fragmented MP4 streamed down one response. The long-standing
  34. // default: it starts fastest and costs the server nothing but the ffmpeg
  35. // process. It cannot answer byte-range requests, which WebKit clients
  36. // (Safari, and every browser on iOS) require before they will play
  37. // anything, so on those it fails outright.
  38. // hls the same transcode cut into segments behind a playlist. Every segment
  39. // is a finite, seekable file, so WebKit plays it and seeking inside the
  40. // transcoded window no longer restarts the stream.
  41. //
  42. // "auto" picks hls on WebKit and mp4 everywhere else (Firefox, Chrome, Edge on
  43. // Windows and Linux). HLS exists for WebKit's sake and is not the better choice
  44. // where MP4 works: the MP4 transcode writes into the response, so the client's
  45. // reading pace holds ffmpeg back and closing the player ends it, while an HLS
  46. // session writes the whole film to temp disk as fast as the CPU allows and
  47. // outlives the player until it is reaped. Other browsers can still choose HLS
  48. // in settings; they play it through Media Source (see nativeHLSSupported).
  49. var STREAM_MODE_KEY = "movie_stream_mode";
  50. // Fired on the <video> element when a Media Source HLS player loses a stream
  51. // it had already bound (session reaped, segments failing, playback stuck),
  52. // with event.detail.reason saying why. Pages treat it like the element's own
  53. // 'error' event, which is how native HLS reports the same thing, and reopen
  54. // the stream where it stopped.
  55. var STREAM_LOST_EVENT = "transcodestreamlost";
  56. // Identifies this player to the HLS endpoint. Seeking outside the transcoded
  57. // window restarts the transcode at a new offset, and the server has no other
  58. // way to tell that the previous one is finished with: the MP4 stream dies with
  59. // its HTTP response, an HLS session does not. Without this every seek leaves
  60. // another ffmpeg racing through the rest of the film, and after a couple of
  61. // jumps the host is too busy to produce the segment the player is waiting for.
  62. //
  63. // One id per page load, so two tabs never retire each other's transcode.
  64. // Restricted to characters the server accepts for this parameter.
  65. var MOVIE_CLIENT_ID = "c" + Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
  66. function isWebKitClient() {
  67. var ua = navigator.userAgent;
  68. // On iOS every browser is WebKit underneath, whatever it calls itself.
  69. if (/CriOS|FxiOS/.test(ua)) { return true; }
  70. // Chrome, Edge and Opera all carry "Safari" in their desktop UA.
  71. if (/Chrome\/|Chromium|Edg\/|OPR\/|Firefox\//.test(ua)) { return false; }
  72. return /Safari/.test(ua);
  73. }
  74. function getStreamMode() {
  75. var mode = localStorage.getItem(STREAM_MODE_KEY);
  76. return (mode === "mp4" || mode === "hls") ? mode : "auto";
  77. }
  78. function setStreamMode(mode) {
  79. if (mode !== "mp4" && mode !== "hls") { mode = "auto"; }
  80. localStorage.setItem(STREAM_MODE_KEY, mode);
  81. }
  82. // Whether the current preference resolves to HLS for this browser.
  83. function usingHLS() {
  84. var mode = getStreamMode();
  85. if (mode === "hls") { return true; }
  86. if (mode === "mp4") { return false; }
  87. return isWebKitClient();
  88. }
  89. // ── Streaming quality ────────────────────────────────────────────────────────
  90. // The resolution a transcode is scaled to, on the familiar 360p–1080p ladder.
  91. // Each step also caps the bitrate on the server (kbps below mirrors the
  92. // ceilings in mod/media/transcoder/quality.go), so a lower step is what to pick
  93. // on a slow link. "original" keeps the source resolution and plays the file
  94. // directly whenever the browser can; any other step always transcodes. "auto"
  95. // moves between those on its own, see AutoQualityController below.
  96. //
  97. // Steps are boxes (long × short side) rather than heights so that a portrait
  98. // clip or a 2.4:1 film is judged the way the server will scale it. A step
  99. // larger than the source is not offered: the server never enlarges, so it
  100. // would only cost a transcode for the same picture.
  101. var STREAM_QUALITY_KEY = "movie_stream_quality";
  102. var STREAM_QUALITIES = [
  103. { id: "auto", label: "Auto" },
  104. { id: "original", label: "Original" },
  105. { id: "1080p", label: "1080p", long: 1920, short: 1080, kbps: 5000 },
  106. { id: "720p", label: "720p", long: 1280, short: 720, kbps: 2800 },
  107. { id: "480p", label: "480p", long: 854, short: 480, kbps: 1400 },
  108. { id: "360p", label: "360p", long: 640, short: 360, kbps: 800 }
  109. ];
  110. function streamQualityStep(id) {
  111. for (var i = 0; i < STREAM_QUALITIES.length; i++) {
  112. if (STREAM_QUALITIES[i].id === id) { return STREAM_QUALITIES[i]; }
  113. }
  114. return null;
  115. }
  116. function getStreamQuality() {
  117. var quality = localStorage.getItem(STREAM_QUALITY_KEY);
  118. return streamQualityStep(quality) ? quality : "original";
  119. }
  120. function setStreamQuality(quality) {
  121. if (!streamQualityStep(quality)) { quality = "original"; }
  122. localStorage.setItem(STREAM_QUALITY_KEY, quality);
  123. }
  124. // Whether a step is worth offering for a source described by a probe result.
  125. // Without one (no ffmpeg, a remote file system, probe still running) every step
  126. // is offered; the server will not enlarge the picture whichever is chosen.
  127. function streamQualityAvailable(id, info) {
  128. var step = streamQualityStep(id);
  129. if (!step) { return false; }
  130. if (!step.long || !info || !(info.width > 0) || !(info.height > 0)) { return true; }
  131. var long = Math.max(info.width, info.height);
  132. var short = Math.min(info.width, info.height);
  133. return long >= step.long || short >= step.short;
  134. }
  135. // The step a given file actually plays at: the viewer's choice, the step Auto
  136. // is on, or the source resolution when the choice is larger than the file.
  137. function effectiveStreamQuality(filepath) {
  138. var quality = getStreamQuality();
  139. if (quality === "auto") { return autoQualityStep(filepath); }
  140. if (!streamQualityAvailable(quality, cachedMediaInfo(filepath))) { return "original"; }
  141. return quality;
  142. }
  143. // The &res= parameter for a transcode of this file, or "" at source resolution.
  144. function streamQualityParam(filepath) {
  145. var quality = effectiveStreamQuality(filepath);
  146. return quality === "original" ? "" : "&res=" + quality;
  147. }
  148. // ── Auto quality ─────────────────────────────────────────────────────────────
  149. // Auto judges the connection from the video buffer alone; nothing is
  150. // downloaded just to measure it. While the browser is still filling its buffer
  151. // it is downloading as fast as it can, so how many seconds of video arrive per
  152. // second of wall time (the fill rate) says how much faster than real time the
  153. // current step can be delivered. Multiplied by that step's bitrate it gives an
  154. // estimate of what the link carries. That covers a slow server too: an HLS
  155. // transcode that cannot keep up fills slowly, and a smaller step is also
  156. // cheaper to encode.
  157. //
  158. // It only holds while the browser really is downloading. Playing a file
  159. // directly, Chrome keeps a fixed number of bytes ahead and rests in between,
  160. // which it announces with a 'suspend' event, so any measurement spanning a rest
  161. // is thrown away and a resting browser is never taken for one running dry. (The
  162. // Media Source player never rests below 30 seconds ahead, and the element does
  163. // not report suspends for it.)
  164. //
  165. // Once the buffer is full the browser only tops it up, so there is nothing
  166. // left to measure and an old estimate says nothing about a link that has since
  167. // got faster. A buffer that stays full is then the evidence instead: after a
  168. // long stall-free stretch Auto tries the next step up, and the fresh stream's
  169. // own fill rate shows straight away whether it holds.
  170. //
  171. // Every change of step restarts the stream, so Auto is deliberately slow to
  172. // move: down at once on real rebuffering or a buffer running dry, up only one
  173. // step at a time, and a step that did not hold is left alone twice as long as
  174. // the last time before it is tried again. Bitrates are the server's ceilings,
  175. // so estimates are comparative rather than an exact measure of the line.
  176. var AUTO_QUALITY_ESTIMATE_KEY = "movie_auto_quality_kbps";
  177. var AUTO_QUALITY_LADDER = ["original", "1080p", "720p", "480p", "360p"]; // best first
  178. var AUTO_TICK_MS = 1000;
  179. var AUTO_FILL_CEILING = 15; // seconds ahead below which every browser keeps downloading
  180. var AUTO_SAMPLE_SECONDS = 8; // window a fill rate is measured over: two HLS segments, which arrive whole
  181. var AUTO_LOW_BUFFER = 6; // seconds ahead that count as running dry
  182. var AUTO_STALL_MS = 2000; // a rebuffer at least this long steps down
  183. var AUTO_SEEK_GRACE_MS = 3000; // waiting right after a seek is the seek, not the link
  184. var AUTO_SETTLE_MS = 8000; // start-up of a fresh stream is not judged
  185. var AUTO_COOLDOWN_MS = 10000; // least time between two changes
  186. var AUTO_UP_HOLD_MS = 45000; // stall-free time before trying a better step
  187. var AUTO_PROBE_MS = 60000; // a step up undone within this did not hold
  188. var AUTO_RETRY_MAX_MS = 600000; // longest a step that did not hold is left alone
  189. var AUTO_ESTIMATE_FRESH_MS = 60000; // an estimate older than this no longer vetoes a step up
  190. var AUTO_UP_MARGIN = 1.5; // headroom wanted over the next step's bitrate
  191. var AUTO_START_MARGIN = 1.3; // headroom wanted when choosing where a file starts
  192. var AUTO_DOWN_MARGIN = 0.8; // share of the estimate a lower step may use
  193. var _autoQuality = { filepath: null, step: "original" };
  194. function autoQualityEstimate() {
  195. var kbps = parseFloat(localStorage.getItem(AUTO_QUALITY_ESTIMATE_KEY));
  196. return kbps > 0 ? kbps : 0;
  197. }
  198. // Steps Auto may use for a file, best first.
  199. function autoQualityLadder(info) {
  200. return AUTO_QUALITY_LADDER.filter(function (id) { return streamQualityAvailable(id, info); });
  201. }
  202. // Bitrate of a step in kbit/s. The scaled steps have the server's ceiling; the
  203. // source resolution costs what the file does when played as it is, and has no
  204. // ceiling at all when transcoded, where superfast x264 runs above the scaled
  205. // step of the same size.
  206. function streamStepKbps(id, info, transcoded) {
  207. var step = streamQualityStep(id);
  208. if (step && step.kbps) { return step.kbps; }
  209. if (!transcoded && info && info.bitRate > 0) { return info.bitRate / 1000; }
  210. var ladder = autoQualityLadder(info);
  211. var sameSize = ladder.length > 1 ? streamQualityStep(ladder[1]) : null;
  212. return sameSize ? sameSize.kbps * 1.5 : 8000;
  213. }
  214. // The step Auto plays a file at. A new file starts at the best step the last
  215. // estimate can carry, or at Original when there is no estimate yet. The choice
  216. // is only fixed once the file's probe is in, since the steps depend on its size.
  217. function autoQualityStep(filepath) {
  218. if (_autoQuality.filepath === filepath) { return _autoQuality.step; }
  219. var info = cachedMediaInfo(filepath);
  220. var ladder = autoQualityLadder(info);
  221. var estimate = autoQualityEstimate();
  222. var step = ladder[0];
  223. if (estimate > 0) {
  224. var transcoded = !(info && info.directPlay);
  225. step = ladder[ladder.length - 1];
  226. for (var i = 0; i < ladder.length; i++) {
  227. if (streamStepKbps(ladder[i], info, transcoded) * AUTO_START_MARGIN <= estimate) {
  228. step = ladder[i];
  229. break;
  230. }
  231. }
  232. }
  233. if (mediaInfoProbed(filepath)) { _autoQuality = { filepath: filepath, step: step }; }
  234. return step;
  235. }
  236. function setAutoQualityStep(filepath, step) {
  237. _autoQuality = { filepath: filepath, step: step };
  238. }
  239. // Watches one <video> element and moves Auto between steps. hooks:
  240. // filepath() the file playing, or null when Auto should keep still
  241. // (nothing playing, or the picture is on a cast receiver)
  242. // isTranscoded() whether the element is playing a transcode
  243. // onSwitch(step) re-open the current file at the step just chosen
  244. function AutoQualityController(videoEl, hooks) {
  245. this.video = videoEl;
  246. this.hooks = hooks;
  247. this.window = null; // fill-rate measurement in progress
  248. this.rate = null; // fill rate of the current stream, averaged
  249. this.estimateAt = 0; // when this player last measured the link
  250. this.streamStartedAt = Date.now();
  251. this.lastSwitchAt = 0;
  252. this.lastSeekAt = 0;
  253. this.lastStallAt = 0;
  254. this.stallStart = 0;
  255. this.hasPlayed = false;
  256. this.lastProgressAt = 0;
  257. this.lastSuspendAt = 0;
  258. this.file = null;
  259. this.probe = null; // the last step up, while it has yet to hold
  260. this.blocked = {}; // step -> { until, hold } for steps that did not hold
  261. var self = this;
  262. videoEl.addEventListener("loadstart", function () {
  263. // A new stream: a seek-by-reload, a new episode or a change of step
  264. self.streamStartedAt = Date.now();
  265. self.window = null;
  266. self.rate = null;
  267. self.stallStart = 0;
  268. self.hasPlayed = false;
  269. });
  270. videoEl.addEventListener("progress", function () { self.lastProgressAt = Date.now(); });
  271. videoEl.addEventListener("suspend", function () { self.lastSuspendAt = Date.now(); });
  272. videoEl.addEventListener("seeking", function () {
  273. self.lastSeekAt = Date.now();
  274. self.window = null;
  275. });
  276. videoEl.addEventListener("waiting", function () {
  277. if (!self.hasPlayed || videoEl.paused) { return; }
  278. if (Date.now() - self.lastSeekAt < AUTO_SEEK_GRACE_MS) { return; }
  279. if (!self.stallStart) { self.stallStart = Date.now(); }
  280. });
  281. videoEl.addEventListener("playing", function () {
  282. self.hasPlayed = true;
  283. if (self.stallStart && Date.now() - self.stallStart >= AUTO_STALL_MS) {
  284. self.lastStallAt = Date.now();
  285. }
  286. self.stallStart = 0;
  287. });
  288. this.timer = setInterval(function () { self.tick(); }, AUTO_TICK_MS);
  289. }
  290. // End of the buffered range under the playhead, and how far ahead it reaches.
  291. AutoQualityController.prototype._bufferAhead = function () {
  292. var buffered = this.video.buffered;
  293. var time = this.video.currentTime;
  294. for (var i = 0; i < buffered.length; i++) {
  295. if (buffered.start(i) <= time + 0.25 && time < buffered.end(i)) {
  296. return { end: buffered.end(i), ahead: buffered.end(i) - time };
  297. }
  298. }
  299. return { end: time, ahead: 0 };
  300. };
  301. AutoQualityController.prototype._currentKbps = function (filepath) {
  302. return streamStepKbps(autoQualityStep(filepath), cachedMediaInfo(filepath), this.hooks.isTranscoded());
  303. };
  304. AutoQualityController.prototype._recordRate = function (rate, filepath) {
  305. rate = Math.max(0, Math.min(rate, 50));
  306. // Averaged within a stream: a window still catches one segment more or
  307. // less than the link really delivered
  308. this.rate = this.rate === null ? rate : (this.rate + rate) / 2;
  309. this.estimateAt = Date.now();
  310. var sample = this.rate * this._currentKbps(filepath);
  311. var previous = autoQualityEstimate();
  312. var estimate = previous > 0 ? previous * 0.7 + sample * 0.3 : sample;
  313. try { localStorage.setItem(AUTO_QUALITY_ESTIMATE_KEY, String(Math.round(estimate))); } catch (e) {}
  314. };
  315. // Whether the browser has stopped downloading because it has enough. It fires
  316. // 'progress' and then 'suspend' at the end of each burst, hence the >=.
  317. AutoQualityController.prototype._resting = function () {
  318. return this.lastSuspendAt > 0 && this.lastSuspendAt >= this.lastProgressAt;
  319. };
  320. // Measure the fill rate, but only while the browser is certainly downloading:
  321. // the buffer is short and it has not rested since the window opened. A window
  322. // spanning a rest would read as a slow link.
  323. AutoQualityController.prototype._sampleFill = function (now, buffer, filepath) {
  324. var w = this.window;
  325. if (w && this.lastSuspendAt >= w.t) {
  326. w = this.window = null;
  327. }
  328. if (buffer.ahead >= AUTO_FILL_CEILING) {
  329. // The browser may rest from here on. A window cut short by getting
  330. // here is not used either: over a second or two, whether the last
  331. // segment happened to land inside it decides the reading. A link that
  332. // fills this fast is not what holds Auto back anyway.
  333. this.window = null;
  334. return;
  335. }
  336. if (!w || buffer.end < w.end - 0.5) {
  337. this.window = this._resting() ? null : { t: now, end: buffer.end };
  338. return;
  339. }
  340. var seconds = (now - w.t) / 1000;
  341. if (seconds >= AUTO_SAMPLE_SECONDS) {
  342. this._recordRate((buffer.end - w.end) / seconds, filepath);
  343. this.window = { t: now, end: buffer.end };
  344. }
  345. };
  346. AutoQualityController.prototype._switch = function (filepath, step, now) {
  347. var up = AUTO_QUALITY_LADDER.indexOf(step) < AUTO_QUALITY_LADDER.indexOf(autoQualityStep(filepath));
  348. if (!up && this.probe && now - this.probe.at < AUTO_PROBE_MS) {
  349. // The last step up did not hold: leave it alone twice as long as before
  350. var last = this.blocked[this.probe.step];
  351. var hold = last ? Math.min(last.hold * 2, AUTO_RETRY_MAX_MS) : 2 * AUTO_UP_HOLD_MS;
  352. this.blocked[this.probe.step] = { until: now + hold, hold: hold };
  353. }
  354. this.probe = up ? { step: step, from: autoQualityStep(filepath), at: now } : null;
  355. this.lastSwitchAt = now;
  356. setAutoQualityStep(filepath, step);
  357. if (typeof this.hooks.onSwitch === "function") { this.hooks.onSwitch(step); }
  358. };
  359. AutoQualityController.prototype.tick = function () {
  360. var video = this.video;
  361. var filepath = this.hooks.filepath();
  362. if (getStreamQuality() !== "auto" || !filepath || !mediaInfoProbed(filepath)) {
  363. this.window = null;
  364. return;
  365. }
  366. // A paused element may stop downloading, which says nothing about the link
  367. if (video.paused || video.seeking || video.ended) {
  368. this.window = null;
  369. return;
  370. }
  371. // What a step costs depends on the file, so what failed on the last one
  372. // says nothing about this one
  373. if (this.file !== filepath) {
  374. this.file = filepath;
  375. this.probe = null;
  376. this.blocked = {};
  377. }
  378. var now = Date.now();
  379. var buffer = this._bufferAhead();
  380. this._sampleFill(now, buffer, filepath);
  381. if (now - this.streamStartedAt < AUTO_SETTLE_MS || now - this.lastSwitchAt < AUTO_COOLDOWN_MS) { return; }
  382. var info = cachedMediaInfo(filepath);
  383. var ladder = autoQualityLadder(info);
  384. var current = Math.max(0, ladder.indexOf(autoQualityStep(filepath)));
  385. var stalled = this.stallStart && now - this.stallStart >= AUTO_STALL_MS;
  386. // Running dry: little left, a recent reading below real time, and the
  387. // browser still trying rather than resting on what it has
  388. var draining = buffer.ahead < AUTO_LOW_BUFFER && this.rate !== null && this.rate < 0.9 &&
  389. now - this.estimateAt < 2 * AUTO_SAMPLE_SECONDS * 1000 && !this._resting();
  390. if ((stalled || draining) && current < ladder.length - 1) {
  391. // A step up that did not hold goes back to where it came from, as long
  392. // as the link has not dropped below that too. Otherwise, with a rate
  393. // measured on this stream, go straight to a step it can carry; without
  394. // one, a single step is the safe guess.
  395. var throughput = this.rate !== null ? this.rate * this._currentKbps(filepath) : null;
  396. var from = this.probe && now - this.probe.at < AUTO_PROBE_MS ? ladder.indexOf(this.probe.from) : -1;
  397. var target = current + 1;
  398. if (from > current && (throughput === null || throughput >= streamStepKbps(ladder[from], info, true))) {
  399. target = from;
  400. } else if (throughput !== null) {
  401. var budget = throughput * AUTO_DOWN_MARGIN;
  402. while (target < ladder.length - 1 && streamStepKbps(ladder[target], info, true) > budget) { target++; }
  403. }
  404. if (stalled) { this.lastStallAt = now; }
  405. this.stallStart = 0;
  406. this._switch(filepath, ladder[target], now);
  407. return;
  408. }
  409. if (current > 0 && !this.stallStart &&
  410. now - Math.max(this.lastStallAt, this.lastSwitchAt, this.streamStartedAt) >= AUTO_UP_HOLD_MS &&
  411. buffer.ahead >= AUTO_FILL_CEILING) {
  412. // A full buffer kept full shows headroom. A recent measurement of this
  413. // stream says whether it is enough for the next step; without one, try
  414. // it. Original played as it is costs the file's own bitrate, otherwise
  415. // it is another transcode.
  416. var next = ladder[current - 1];
  417. var retry = this.blocked[next];
  418. if (retry && now < retry.until) { return; }
  419. var nextKbps = streamStepKbps(next, info, !(info && info.directPlay));
  420. var fresh = this.rate !== null && now - this.estimateAt < AUTO_ESTIMATE_FRESH_MS;
  421. if (!fresh || this.rate * this._currentKbps(filepath) >= nextKbps * AUTO_UP_MARGIN) {
  422. this._switch(filepath, next, now);
  423. }
  424. }
  425. };
  426. // WebKit plays HLS natively. Everywhere else it is played through Media Source
  427. // Extensions: hls.js if someone has vendored it into web/script/, otherwise the
  428. // built-in MSE player in web/script/hlsmse.js, which is enough because the
  429. // server emits single-variant fragmented-MP4 playlists.
  430. function nativeHLSSupported(videoEl) {
  431. if (!videoEl || !videoEl.canPlayType) { return false; }
  432. if (videoEl.canPlayType("application/vnd.apple.mpegurl") === "") { return false; }
  433. // canPlayType alone cannot be trusted here: Chrome answers "maybe" for the
  434. // HLS MIME type and then fails to play the playlist. WebKit is the only
  435. // engine with a real native HLS pipeline, so the answer only counts there —
  436. // everyone else goes through Media Source instead.
  437. return isWebKitClient();
  438. }
  439. function hlsPlaybackSupported(videoEl) {
  440. if (nativeHLSSupported(videoEl)) { return true; }
  441. if (window.Hls && window.Hls.isSupported()) { return true; }
  442. return !!(window.MovieHLS && window.MovieHLS.isSupported());
  443. }
  444. // ── Direct play vs transcode ─────────────────────────────────────────────────
  445. // The container extension is only a hint. An .mp4 may hold HEVC, AV1 or 10-bit
  446. // H.264, none of which most browsers decode — playing those directly fails with
  447. // a bare decode error (NS_ERROR_DOM_MEDIA_METADATA_ERR on Firefox) instead of
  448. // being transcoded. So the server is asked what the file really contains.
  449. var WEB_PLAYABLE_EXTENSIONS = ["mp4", "webm", "ogg", "m4v"];
  450. var _mediaInfoCache = {};
  451. function isWebPlayableExtension(ext) {
  452. return WEB_PLAYABLE_EXTENSIONS.indexOf(String(ext || "").toLowerCase()) !== -1;
  453. }
  454. // Ask the server what a file contains (codecs, picture size). Calls back with
  455. // the probe result, or null when there is none to be had (no ffmpeg, a remote
  456. // file system). Answers are cached per file, making repeat plays and episode
  457. // changes free.
  458. function probeMediaInfo(filepath, callback) {
  459. if (mediaInfoProbed(filepath)) {
  460. callback(_mediaInfoCache[filepath]);
  461. return;
  462. }
  463. // Without ffmpeg the probe route does not exist and the request falls
  464. // through to the plain media endpoint, which would start sending the whole
  465. // film. Anything that is not JSON is cut off at the headers.
  466. var controller = window.AbortController ? new AbortController() : null;
  467. fetch(PROBE_API + "?file=" + encodeURIComponent(filepath),
  468. { credentials: "same-origin", signal: controller ? controller.signal : undefined })
  469. .then(function (r) {
  470. if ((r.headers.get("Content-Type") || "").indexOf("json") === -1) {
  471. if (controller) { controller.abort(); }
  472. return null;
  473. }
  474. return r.json();
  475. })
  476. .then(function (info) {
  477. info = (info && !info.error) ? info : null;
  478. _mediaInfoCache[filepath] = info;
  479. callback(info);
  480. })
  481. .catch(function () {
  482. // Settled as "nothing known", like a probe error, so Auto can fix
  483. // the file's starting step instead of re-deciding it on every call.
  484. _mediaInfoCache[filepath] = null;
  485. callback(null);
  486. });
  487. }
  488. function cachedMediaInfo(filepath) {
  489. return _mediaInfoCache[filepath] || null;
  490. }
  491. // Whether the probe for a file has answered (with a result or with nothing).
  492. function mediaInfoProbed(filepath) {
  493. return Object.prototype.hasOwnProperty.call(_mediaInfoCache, filepath);
  494. }
  495. // Decide whether a file can be handed to the browser as-is. Calls back with
  496. // true for direct play, false to transcode.
  497. //
  498. // Every file is probed, not only web-native containers: the picture size is
  499. // what decides which quality steps apply, and a step below the source always
  500. // means a transcode, however playable the file is.
  501. function resolveDirectPlay(filepath, ext, callback) {
  502. probeMediaInfo(filepath, function (info) {
  503. if (effectiveStreamQuality(filepath) !== "original") { callback(false); return; }
  504. if (!isWebPlayableExtension(ext)) { callback(false); return; }
  505. // A probe error (no ffmpeg, remote file system) leaves the old
  506. // extension-based behaviour in place rather than blocking playback.
  507. callback(info ? !!info.directPlay : true);
  508. });
  509. }
  510. // Safety net for direct playback: the probe can still be wrong for a browser
  511. // missing a platform decoder, so a decode failure retries as a transcode rather
  512. // than leaving the viewer on a dead player.
  513. function onDirectPlaybackFailure(videoEl, onFallback) {
  514. clearDirectPlaybackWatch(videoEl);
  515. var handler = function () {
  516. clearDirectPlaybackWatch(videoEl);
  517. var err = videoEl.error;
  518. // 3 = MEDIA_ERR_DECODE, 4 = MEDIA_ERR_SRC_NOT_SUPPORTED. A network
  519. // abort is not a codec problem and must not trigger a transcode.
  520. if (!err || (err.code !== 3 && err.code !== 4)) { return; }
  521. if (typeof onFallback === "function") { onFallback(); }
  522. };
  523. videoEl._directFallback = handler;
  524. videoEl.addEventListener("error", handler);
  525. }
  526. function clearDirectPlaybackWatch(videoEl) {
  527. if (videoEl && videoEl._directFallback) {
  528. videoEl.removeEventListener("error", videoEl._directFallback);
  529. videoEl._directFallback = null;
  530. }
  531. }
  532. // Build the streaming URL for a transcoded file, honouring the current mode
  533. // and quality.
  534. // startSeconds restarts the transcode at an offset; the resulting stream always
  535. // begins at zero, so callers track the offset separately.
  536. function transcodeStreamURL(filepath, startSeconds) {
  537. var hls = usingHLS();
  538. var base = hls ? HLS_API : TRANSCODE_API;
  539. var url = base + "?file=" + encodeURIComponent(filepath);
  540. if (startSeconds && startSeconds > 0.001) {
  541. url += "&start=" + startSeconds.toFixed(3);
  542. }
  543. url += streamQualityParam(filepath);
  544. // Only HLS needs it, and the MP4 response is cacheable — a per-load
  545. // parameter would defeat that cache for nothing.
  546. if (hls) { url += "&client=" + MOVIE_CLIENT_ID; }
  547. return url;
  548. }
  549. // Fetch a playlist before handing it to the player.
  550. //
  551. // Answering a playlist request means starting (or joining) a transcode and
  552. // waiting for its first segment, so it can fail long after the player has
  553. // committed to the URL: a seek past the end of the file, a host too busy to
  554. // produce a segment in time, a session that has already been reaped. A <video>
  555. // element cannot tell any of that from a stream it simply cannot decode — it
  556. // reports NotSupportedError and the reason is lost. Asking first keeps the real
  557. // message, and hands the player a playlist that is already ready.
  558. function preflightPlaylist(url, callback) {
  559. fetch(url, { credentials: "same-origin", cache: "no-store" })
  560. .then(function (response) {
  561. return response.text().then(function (body) {
  562. if (response.ok && String(body).trim().indexOf("#EXTM3U") === 0) {
  563. callback(true);
  564. return;
  565. }
  566. callback(false, playlistErrorMessage(body, response.status));
  567. });
  568. })
  569. .catch(function () {
  570. callback(false, "Transcode failed: could not reach the server");
  571. });
  572. }
  573. // Turn whatever arrived instead of a playlist into a line worth showing.
  574. function playlistErrorMessage(body, status) {
  575. var text = String(body || "").trim();
  576. // Some endpoints still report failure as a 200 carrying a JSON error object
  577. if (text.charAt(0) === "{") {
  578. try {
  579. var parsed = JSON.parse(text);
  580. if (parsed && parsed.error) { text = String(parsed.error); }
  581. } catch (e) { /* not JSON after all — show it as it came */ }
  582. }
  583. if (!text) { text = "the transcode did not start (HTTP " + status + ")"; }
  584. if (text.length > 120) { text = text.substring(0, 119) + "…"; }
  585. return "Transcode failed: " + text;
  586. }
  587. // Point a <video> at a stream URL. HLS on a browser without native support is
  588. // routed through hls.js when it is available. Returns false when the stream
  589. // cannot be played at all, so the caller can say so rather than hang.
  590. //
  591. // A playlist is checked before the player is pointed at it, which makes the
  592. // attachment asynchronous: onReady fires once the stream is actually bound, and
  593. // is where the caller should call play(). onError reports a stream that never
  594. // became playable, with the server's own explanation. A stream that fails after
  595. // it was bound is reported on the element instead: its 'error' event for native
  596. // playback, STREAM_LOST_EVENT for the Media Source player.
  597. function attachTranscodeStream(videoEl, url, onError, onReady) {
  598. detachTranscodeStream(videoEl);
  599. var ready = function () { if (typeof onReady === "function") { onReady(); } };
  600. var fail = function (reason, err) { if (typeof onError === "function") { onError(reason, err); } };
  601. if (url.indexOf(HLS_API) !== 0) {
  602. videoEl.src = url;
  603. videoEl.load();
  604. ready();
  605. return true;
  606. }
  607. // Choose the player before making a request, so a browser that cannot play
  608. // HLS at all is reported without waiting on a transcode it will not use.
  609. var bind;
  610. if (nativeHLSSupported(videoEl)) {
  611. bind = function () { videoEl.src = url; videoEl.load(); ready(); };
  612. } else if (window.Hls && window.Hls.isSupported()) {
  613. bind = function () {
  614. var hls = new window.Hls({ enableWorker: true });
  615. videoEl._hlsInstance = hls;
  616. hls.loadSource(url);
  617. hls.attachMedia(videoEl);
  618. ready();
  619. };
  620. } else if (window.MovieHLS && window.MovieHLS.isSupported()) {
  621. bind = function () {
  622. var instance = window.MovieHLS.attach(videoEl, url, {
  623. onError: function (reason, err) {
  624. // A player already replaced by a newer stream is not news
  625. if (videoEl._mseInstance !== instance) { return; }
  626. videoEl.dispatchEvent(new CustomEvent(STREAM_LOST_EVENT, {
  627. detail: { reason: reason, error: err }
  628. }));
  629. }
  630. });
  631. videoEl._mseInstance = instance;
  632. ready();
  633. };
  634. } else {
  635. return false;
  636. }
  637. // Stop the stream being replaced now, not when the new one binds. Tearing
  638. // down its player does not stop the element: it plays on through whatever
  639. // it had buffered while the page already counts time from the new offset,
  640. // so after a jump to 2:20 the clock runs 2:20, 2:21, 2:22 over the old
  641. // picture, then snaps back to 2:20 when the new stream arrives. The gap is
  642. // the preflight below, which waits for the server to start ffmpeg at the
  643. // new offset - seconds, not milliseconds. An emptied element shows nothing
  644. // (the page keeps its freeze frame over it) and holds its clock at zero,
  645. // which is exactly the new offset.
  646. stopElementMedia(videoEl);
  647. // A seek made while the previous playlist is still being fetched must not
  648. // be overtaken by that older answer.
  649. var generation = (videoEl._streamGeneration || 0) + 1;
  650. videoEl._streamGeneration = generation;
  651. preflightPlaylist(url, function (ok, reason) {
  652. if (videoEl._streamGeneration !== generation) { return; }
  653. if (!ok) { fail(reason); return; }
  654. bind();
  655. });
  656. return true;
  657. }
  658. // Empty the element so nothing keeps playing from its old source. Removing the
  659. // attribute (rather than setting src to "") matters: an empty src is an invalid
  660. // source and fires 'error', which the pages would treat as a lost stream. The
  661. // load() rejects a pending play() with AbortError, which playVideo ignores.
  662. function stopElementMedia(videoEl) {
  663. if (!videoEl.hasAttribute("src")) { return; }
  664. videoEl.removeAttribute("src");
  665. videoEl.load();
  666. }
  667. // Release whichever player is currently bound to the element. Always call this
  668. // before pointing a <video> somewhere new, or an MSE attachment keeps feeding
  669. // segments into an element that has moved on.
  670. function detachTranscodeStream(videoEl) {
  671. if (!videoEl) { return; }
  672. // Retires any playlist request still in flight for the old stream
  673. videoEl._streamGeneration = (videoEl._streamGeneration || 0) + 1;
  674. if (videoEl._hlsInstance) {
  675. try { videoEl._hlsInstance.destroy(); } catch (e) {}
  676. videoEl._hlsInstance = null;
  677. }
  678. if (videoEl._mseInstance) {
  679. try { videoEl._mseInstance.destroy(); } catch (e) {}
  680. videoEl._mseInstance = null;
  681. }
  682. }
  683. // ── Scanner settings ─────────────────────────────────────────────────────────
  684. var VALID_VIDEO_FORMATS = ["mp4", "webm", "ogg", "mkv", "avi", "mov", "m4v", "wmv", "flv", "rmvb", "ts"];
  685. var SKIP_ROOT_PREFIXES = ["tmp:/", "trash:/"]; // roots to skip entirely
  686. var VIDEO_FOLDER_NAME = "Video"; // expected folder inside each root
  687. var MOVIE_FOLDER_NAMES = ["movie", "movies"]; // folder names (case-insensitive) treated as movie containers
  688. var ANIME_FOLDER_NAMES = ["anime"]; // folder names (case-insensitive) treated as anime containers