Greasy Fork is available in English.

bilibili merged flv+mp4+ass+enhance

bilibili/哔哩哔哩:超清FLV下载,FLV合并,原生MP4下载,弹幕ASS下载,MKV打包,播放体验增强,原生appsecret,不借助其他网站

  1. // ==UserScript==
  2. // @name bilibili merged flv+mp4+ass+enhance
  3. // @namespace http://qli5.tk/
  4. // @homepageURL https://github.com/liqi0816/bilitwin/
  5. // @description bilibili/哔哩哔哩:超清FLV下载,FLV合并,原生MP4下载,弹幕ASS下载,MKV打包,播放体验增强,原生appsecret,不借助其他网站
  6. // @match *://www.bilibili.com/video/av*
  7. // @match *://bangumi.bilibili.com/anime/*/play*
  8. // @match *://www.bilibili.com/bangumi/play/ep*
  9. // @match *://www.bilibili.com/bangumi/play/ss*
  10. // @match *://www.bilibili.com/watchlater/
  11. // @version 1.14
  12. // @author qli5
  13. // @copyright qli5, 2014+, 田生, grepmusic, zheng qian, ryiwamoto
  14. // @license Mozilla Public License 2.0; http://www.mozilla.org/MPL/2.0/
  15. // @grant none
  16. // @run-at document-start
  17. // ==/UserScript==
  18.  
  19. /***
  20. *
  21. * @author qli5 <goodlq11[at](163|gmail).com>
  22. *
  23. * BiliTwin consists of two parts - BiliMonkey and BiliPolyfill.
  24. * They are bundled because I am too lazy to write two user interfaces.
  25. *
  26. * So what is the difference between BiliMonkey and BiliPolyfill?
  27. *
  28. * BiliMonkey deals with network. It is a (naIve) Service Worker.
  29. * This is also why it uses IndexedDB instead of localStorage.
  30. * BiliPolyfill deals with experience. It is more a "user script".
  31. * Everything it can do can be done by hand.
  32. *
  33. * BiliPolyfill will be pointless in the long run - I believe bilibili
  34. * will finally provide these functions themselves.
  35. *
  36. * This Source Code Form is subject to the terms of the Mozilla Public
  37. * License, v. 2.0. If a copy of the MPL was not distributed with this
  38. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  39. *
  40. * Covered Software is provided under this License on an “as is” basis,
  41. * without warranty of any kind, either expressed, implied, or statutory,
  42. * including, without limitation, warranties that the Covered Software
  43. * is free of defects, merchantable, fit for a particular purpose or
  44. * non-infringing. The entire risk as to the quality and performance of
  45. * the Covered Software is with You. Should any Covered Software prove
  46. * defective in any respect, You (not any Contributor) assume the cost
  47. * of any necessary servicing, repair, or correction. This disclaimer
  48. * of warranty constitutes an essential part of this License. No use of
  49. * any Covered Software is authorized under this License except under
  50. * this disclaimer.
  51. *
  52. * Under no circumstances and under no legal theory, whether tort
  53. * (including negligence), contract, or otherwise, shall any Contributor,
  54. * or anyone who distributes Covered Software as permitted above, be
  55. * liable to You for any direct, indirect, special, incidental, or
  56. * consequential damages of any character including, without limitation,
  57. * damages for lost profits, loss of goodwill, work stoppage, computer
  58. * failure or malfunction, or any and all other commercial damages or
  59. * losses, even if such party shall have been informed of the possibility
  60. * of such damages. This limitation of liability shall not apply to
  61. * liability for death or personal injury resulting from such party’s
  62. * negligence to the extent applicable law prohibits such limitation.
  63. * Some jurisdictions do not allow the exclusion or limitation of
  64. * incidental or consequential damages, so this exclusion and limitation
  65. * may not apply to You.
  66. */
  67.  
  68. /***
  69. * This is a bundled code. While it is not uglified, it may still be too
  70. * complex for reviewing. Please refer to
  71. * https://github.com/liqi0816/bilitwin/
  72. * for source code.
  73. */
  74.  
  75. /***
  76. * Copyright (C) 2018 Qli5. All Rights Reserved.
  77. *
  78. * @author qli5 <goodlq11[at](163|gmail).com>
  79. *
  80. * This Source Code Form is subject to the terms of the Mozilla Public
  81. * License, v. 2.0. If a copy of the MPL was not distributed with this
  82. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  83. */
  84.  
  85. /**
  86. * Basically a Promise that exposes its resolve and reject callbacks
  87. */
  88. class AsyncContainer {
  89. /***
  90. * The thing is, if we cannot cancel a promise, we should at least be able to
  91. * explicitly mark a promise as garbage collectible.
  92. *
  93. * Yes, this is something like cancelable Promise. But I insist they are different.
  94. */
  95. constructor(callback) {
  96. // 1. primary promise
  97. this.primaryPromise = new Promise((s, j) => {
  98. this.resolve = arg => { s(arg); return arg; };
  99. this.reject = arg => { j(arg); return arg; };
  100. });
  101.  
  102. // 2. hang promise
  103. this.hangReturn = Symbol();
  104. this.hangPromise = new Promise(s => this.hang = () => s(this.hangReturn));
  105. this.destroiedThen = this.hangPromise.then.bind(this.hangPromise);
  106. this.primaryPromise.then(() => this.state = 'fulfilled');
  107. this.primaryPromise.catch(() => this.state = 'rejected');
  108. this.hangPromise.then(() => this.state = 'hanged');
  109.  
  110. // 4. race
  111. this.promise = Promise
  112. .race([this.primaryPromise, this.hangPromise])
  113. .then(s => s == this.hangReturn ? new Promise(() => { }) : s);
  114.  
  115. // 5. inherit
  116. this.then = this.promise.then.bind(this.promise);
  117. this.catch = this.promise.catch.bind(this.promise);
  118. this.finally = this.promise.finally.bind(this.promise);
  119.  
  120. // 6. optional callback
  121. if (typeof callback == 'function') callback(this.resolve, this.reject);
  122. }
  123.  
  124. /***
  125. * Memory leak notice:
  126. *
  127. * The V8 implementation of Promise requires
  128. * 1. the resolve handler of a Promise
  129. * 2. the reject handler of a Promise
  130. * 3. !! the Promise object itself !!
  131. * to be garbage collectible to correctly free Promise runtime contextes
  132. *
  133. * This piece of code will work
  134. * void (async () => {
  135. * const buf = new Uint8Array(1024 * 1024 * 1024);
  136. * for (let i = 0; i < buf.length; i++) buf[i] = i;
  137. * await new Promise(() => { });
  138. * return buf;
  139. * })();
  140. * if (typeof gc == 'function') gc();
  141. *
  142. * This piece of code will cause a Promise context mem leak
  143. * const deadPromise = new Promise(() => { });
  144. * void (async () => {
  145. * const buf = new Uint8Array(1024 * 1024 * 1024);
  146. * for (let i = 0; i < buf.length; i++) buf[i] = i;
  147. * await deadPromise;
  148. * return buf;
  149. * })();
  150. * if (typeof gc == 'function') gc();
  151. *
  152. * In other words, do NOT directly inherit from promise. You will need to
  153. * dereference it on destroying.
  154. */
  155. destroy() {
  156. this.hang();
  157. this.resolve = () => { };
  158. this.reject = this.resolve;
  159. this.hang = this.resolve;
  160. this.primaryPromise = null;
  161. this.hangPromise = null;
  162. this.promise = null;
  163. this.then = this.resolve;
  164. this.catch = this.resolve;
  165. this.finally = this.resolve;
  166. this.destroiedThen = f => f();
  167. /***
  168. * For ease of debug, do not dereference hangReturn
  169. *
  170. * If run from console, mysteriously this tiny symbol will help correct gc
  171. * before a console.clear
  172. */
  173. //this.hangReturn = null;
  174. }
  175.  
  176. static _UNIT_TEST() {
  177. const containers = [];
  178. async function foo() {
  179. const buf = new Uint8Array(600 * 1024 * 1024);
  180. for (let i = 0; i < buf.length; i++) buf[i] = i;
  181. const ac = new AsyncContainer();
  182. ac.destroiedThen(() => console.log('asyncContainer destroied'));
  183. containers.push(ac);
  184. await ac;
  185. return buf;
  186. }
  187. const foos = [foo(), foo(), foo()];
  188. containers.forEach(e => e.destroy());
  189. console.warn('Check your RAM usage. I allocated 1.8GB in three dead-end promises.');
  190. return [foos, containers];
  191. }
  192. }
  193.  
  194. /***
  195. * Copyright (C) 2018 Qli5. All Rights Reserved.
  196. *
  197. * @author qli5 <goodlq11[at](163|gmail).com>
  198. *
  199. * This Source Code Form is subject to the terms of the Mozilla Public
  200. * License, v. 2.0. If a copy of the MPL was not distributed with this
  201. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  202. */
  203.  
  204. /**
  205. * Provides common util for all bilibili user scripts
  206. */
  207. class BiliUserJS {
  208. static async getIframeWin() {
  209. if (document.querySelector('#bofqi > iframe').contentDocument.getElementById('bilibiliPlayer')) {
  210. return document.querySelector('#bofqi > iframe').contentWindow;
  211. }
  212. else {
  213. return new Promise(resolve => {
  214. document.querySelector('#bofqi > iframe').addEventListener('load', () => {
  215. resolve(document.querySelector('#bofqi > iframe').contentWindow);
  216. }, { once: true });
  217. });
  218. }
  219. }
  220.  
  221. static async getPlayerWin() {
  222. if (location.href.includes('/watchlater/#/list')) {
  223. await new Promise(resolve => {
  224. window.addEventListener('hashchange', () => resolve(location.href), { once: true });
  225. });
  226. }
  227. if (location.href.includes('/watchlater/#/')) {
  228. if (!document.getElementById('bofqi')) {
  229. await new Promise(resolve => {
  230. const observer = new MutationObserver(() => {
  231. if (document.getElementById('bofqi')) {
  232. resolve(document.getElementById('bofqi'));
  233. observer.disconnect();
  234. }
  235. });
  236. observer.observe(document, { childList: true, subtree: true });
  237. });
  238. }
  239. }
  240. if (document.getElementById('bilibiliPlayer')) {
  241. return window;
  242. }
  243. else if (document.querySelector('#bofqi > iframe')) {
  244. return BiliUserJS.getIframeWin();
  245. }
  246. else if (document.querySelector('#bofqi > object')) {
  247. throw 'Need H5 Player';
  248. }
  249. else {
  250. return new Promise(resolve => {
  251. const observer = new MutationObserver(() => {
  252. if (document.getElementById('bilibiliPlayer')) {
  253. observer.disconnect();
  254. resolve(window);
  255. }
  256. else if (document.querySelector('#bofqi > iframe')) {
  257. observer.disconnect();
  258. resolve(BiliUserJS.getIframeWin());
  259. }
  260. else if (document.querySelector('#bofqi > object')) {
  261. observer.disconnect();
  262. throw 'Need H5 Player';
  263. }
  264. });
  265. observer.observe(document.getElementById('bofqi'), { childList: true });
  266. });
  267. }
  268. }
  269.  
  270. static tryGetPlayerWinSync() {
  271. if (document.getElementById('bilibiliPlayer')) {
  272. return window;
  273. }
  274. else if (document.querySelector('#bofqi > object')) {
  275. throw 'Need H5 Player';
  276. }
  277. }
  278.  
  279. static getCidRefreshPromise(playerWin) {
  280. /***********
  281. * !!!Race condition!!!
  282. * We must finish everything within one microtask queue!
  283. *
  284. * bilibili script:
  285. * videoElement.remove() -> setTimeout(0) -> [[microtask]] -> load playurl
  286. * \- synchronous macrotask -/ || \- synchronous
  287. * ||
  288. * the only position to inject monkey.sniffDefaultFormat
  289. */
  290. const cidRefresh = new AsyncContainer();
  291.  
  292. // 1. no active video element in document => cid refresh
  293. const observer = new MutationObserver(() => {
  294. if (!playerWin.document.getElementsByTagName('video')[0]) {
  295. observer.disconnect();
  296. cidRefresh.resolve();
  297. }
  298. });
  299. observer.observe(playerWin.document.getElementsByClassName('bilibili-player-video')[0], { childList: true });
  300.  
  301. // 2. playerWin unload => cid refresh
  302. playerWin.addEventListener('unload', () => Promise.resolve().then(() => cidRefresh.resolve()));
  303.  
  304. return cidRefresh;
  305. }
  306.  
  307. static async domContentLoadedThen(func) {
  308. if (document.readyState == 'loading') {
  309. return new Promise(resolve => {
  310. document.addEventListener('DOMContentLoaded', () => resolve(func()), { once: true });
  311. })
  312. }
  313. else {
  314. return func();
  315. }
  316. }
  317. }
  318.  
  319. /***
  320. * Copyright (C) 2018 Qli5. All Rights Reserved.
  321. *
  322. * @author qli5 <goodlq11[at](163|gmail).com>
  323. *
  324. * This Source Code Form is subject to the terms of the Mozilla Public
  325. * License, v. 2.0. If a copy of the MPL was not distributed with this
  326. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  327. */
  328.  
  329. /**
  330. * A promisified indexedDB with large file(>100MB) support
  331. */
  332. class CacheDB {
  333. constructor(dbName = 'biliMonkey', osName = 'flv', keyPath = 'name', maxItemSize = 100 * 1024 * 1024) {
  334. // Neither Chrome or Firefox can handle item size > 100M
  335. this.dbName = dbName;
  336. this.osName = osName;
  337. this.keyPath = keyPath;
  338. this.maxItemSize = maxItemSize;
  339. this.db = null;
  340. }
  341.  
  342. async getDB() {
  343. if (this.db) return this.db;
  344. this.db = new Promise((resolve, reject) => {
  345. const openRequest = indexedDB.open(this.dbName);
  346. openRequest.onupgradeneeded = e => {
  347. const db = e.target.result;
  348. if (!db.objectStoreNames.contains(this.osName)) {
  349. db.createObjectStore(this.osName, { keyPath: this.keyPath });
  350. }
  351. };
  352. openRequest.onsuccess = e => {
  353. return resolve(this.db = e.target.result);
  354. };
  355. openRequest.onerror = reject;
  356. });
  357. return this.db;
  358. }
  359.  
  360. async addData(item, name = item.name, data = item.data || item) {
  361. if (!data instanceof Blob) throw 'CacheDB: data must be a Blob';
  362. const itemChunks = [];
  363. const numChunks = Math.ceil(data.size / this.maxItemSize);
  364. for (let i = 0; i < numChunks; i++) {
  365. itemChunks.push({
  366. name: `${name}/part_${i}`,
  367. numChunks,
  368. data: data.slice(i * this.maxItemSize, (i + 1) * this.maxItemSize)
  369. });
  370. }
  371.  
  372. const reqCascade = new Promise(async (resolve, reject) => {
  373. const db = await this.getDB();
  374. const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
  375. const onsuccess = e => {
  376. const chunk = itemChunks.pop();
  377. if (!chunk) return resolve(e);
  378. const req = objectStore.add(chunk);
  379. req.onerror = reject;
  380. req.onsuccess = onsuccess;
  381. };
  382. onsuccess();
  383. });
  384.  
  385. return reqCascade;
  386. }
  387.  
  388. async putData(item, name = item.name, data = item.data || item) {
  389. if (!data instanceof Blob) throw 'CacheDB: data must be a Blob';
  390. const itemChunks = [];
  391. const numChunks = Math.ceil(data.size / this.maxItemSize);
  392. for (let i = 0; i < numChunks; i++) {
  393. itemChunks.push({
  394. name: `${name}/part_${i}`,
  395. numChunks,
  396. data: data.slice(i * this.maxItemSize, (i + 1) * this.maxItemSize)
  397. });
  398. }
  399.  
  400. const reqCascade = new Promise(async (resolve, reject) => {
  401. const db = await this.getDB();
  402. const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
  403. const onsuccess = e => {
  404. const chunk = itemChunks.pop();
  405. if (!chunk) return resolve(e);
  406. const req = objectStore.put(chunk);
  407. req.onerror = reject;
  408. req.onsuccess = onsuccess;
  409. };
  410. onsuccess();
  411. });
  412.  
  413. return reqCascade;
  414. }
  415.  
  416. async getData(name) {
  417. const reqCascade = new Promise(async (resolve, reject) => {
  418. const dataChunks = [];
  419. const db = await this.getDB();
  420. const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
  421. const probe = objectStore.get(`${name}/part_0`);
  422. probe.onerror = reject;
  423. probe.onsuccess = e => {
  424. // 1. Probe fails => key does not exist
  425. if (!probe.result) return resolve(null);
  426.  
  427. // 2. How many chunks to retrieve?
  428. const { numChunks } = probe.result;
  429.  
  430. // 3. Cascade on the remaining chunks
  431. const onsuccess = e => {
  432. dataChunks.push(e.target.result.data);
  433. if (dataChunks.length == numChunks) return resolve(dataChunks);
  434. const req = objectStore.get(`${name}/part_${dataChunks.length}`);
  435. req.onerror = reject;
  436. req.onsuccess = onsuccess;
  437. };
  438. onsuccess(e);
  439. };
  440. });
  441.  
  442. const dataChunks = await reqCascade;
  443.  
  444. return dataChunks ? { name, data: new Blob(dataChunks) } : null;
  445. }
  446.  
  447. async deleteData(name) {
  448. const reqCascade = new Promise(async (resolve, reject) => {
  449. let currentChunkNum = 0;
  450. const db = await this.getDB();
  451. const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
  452. const probe = objectStore.get(`${name}/part_0`);
  453. probe.onerror = reject;
  454. probe.onsuccess = e => {
  455. // 1. Probe fails => key does not exist
  456. if (!probe.result) return resolve(null);
  457.  
  458. // 2. How many chunks to delete?
  459. const { numChunks } = probe.result;
  460.  
  461. // 3. Cascade on the remaining chunks
  462. const onsuccess = e => {
  463. const req = objectStore.delete(`${name}/part_${currentChunkNum}`);
  464. req.onerror = reject;
  465. req.onsuccess = onsuccess;
  466. currentChunkNum++;
  467. if (currentChunkNum == numChunks) return resolve(e);
  468. };
  469. onsuccess();
  470. };
  471. });
  472.  
  473. return reqCascade;
  474. }
  475.  
  476. async deleteEntireDB() {
  477. const req = indexedDB.deleteDatabase(this.dbName);
  478. return new Promise((resolve, reject) => {
  479. req.onsuccess = () => resolve(this.db = null);
  480. req.onerror = reject;
  481. });
  482. }
  483.  
  484. static async _UNIT_TEST() {
  485. let db = new CacheDB();
  486. console.warn('Storing 201MB...');
  487. console.log(await db.putData(new Blob([new ArrayBuffer(201 * 1024 * 1024)]), 'test'));
  488. console.warn('Deleting 201MB...');
  489. console.log(await db.deleteData('test'));
  490. }
  491. }
  492.  
  493. /***
  494. * Copyright (C) 2018 Qli5. All Rights Reserved.
  495. *
  496. * @author qli5 <goodlq11[at](163|gmail).com>
  497. *
  498. * This Source Code Form is subject to the terms of the Mozilla Public
  499. * License, v. 2.0. If a copy of the MPL was not distributed with this
  500. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  501. */
  502.  
  503. /**
  504. * A more powerful fetch with
  505. * 1. onprogress handler
  506. * 2. partial response getter
  507. */
  508. class DetailedFetchBlob {
  509. constructor(input, init = {}, onprogress = init.onprogress, onabort = init.onabort, onerror = init.onerror, fetch = init.fetch || top.fetch) {
  510. // Fire in the Fox fix
  511. if (this.firefoxConstructor(input, init, onprogress, onabort, onerror)) return;
  512. // Now I know why standardizing cancelable Promise is that difficult
  513. // PLEASE refactor me!
  514. this.onprogress = onprogress;
  515. this.onabort = onabort;
  516. this.onerror = onerror;
  517. this.abort = null;
  518. this.loaded = init.cacheLoaded || 0;
  519. this.total = init.cacheLoaded || 0;
  520. this.lengthComputable = false;
  521. this.buffer = [];
  522. this.blob = null;
  523. this.reader = null;
  524. this.blobPromise = fetch(input, init).then(res => {
  525. if (this.reader == 'abort') return res.body.getReader().cancel().then(() => null);
  526. if (!res.ok) throw `HTTP Error ${res.status}: ${res.statusText}`;
  527. this.lengthComputable = res.headers.has('Content-Length');
  528. this.total += parseInt(res.headers.get('Content-Length')) || Infinity;
  529. if (this.lengthComputable) {
  530. this.reader = res.body.getReader();
  531. return this.blob = this.consume();
  532. }
  533. else {
  534. if (this.onprogress) this.onprogress(this.loaded, this.total, this.lengthComputable);
  535. return this.blob = res.blob();
  536. }
  537. });
  538. this.blobPromise.then(() => this.abort = () => { });
  539. this.blobPromise.catch(e => this.onerror({ target: this, type: e }));
  540. this.promise = Promise.race([
  541. this.blobPromise,
  542. new Promise(resolve => this.abort = () => {
  543. this.onabort({ target: this, type: 'abort' });
  544. resolve('abort');
  545. this.buffer = [];
  546. this.blob = null;
  547. if (this.reader) this.reader.cancel();
  548. else this.reader = 'abort';
  549. })
  550. ]).then(s => s == 'abort' ? new Promise(() => { }) : s);
  551. this.then = this.promise.then.bind(this.promise);
  552. this.catch = this.promise.catch.bind(this.promise);
  553. }
  554.  
  555. getPartialBlob() {
  556. return new Blob(this.buffer);
  557. }
  558.  
  559. async getBlob() {
  560. return this.promise;
  561. }
  562.  
  563. async pump() {
  564. while (true) {
  565. let { done, value } = await this.reader.read();
  566. if (done) return this.loaded;
  567. this.loaded += value.byteLength;
  568. this.buffer.push(new Blob([value]));
  569. if (this.onprogress) this.onprogress(this.loaded, this.total, this.lengthComputable);
  570. }
  571. }
  572.  
  573. async consume() {
  574. await this.pump();
  575. this.blob = new Blob(this.buffer);
  576. this.buffer = null;
  577. return this.blob;
  578. }
  579.  
  580. firefoxConstructor(input, init = {}, onprogress = init.onprogress, onabort = init.onabort, onerror = init.onerror) {
  581. if (!top.navigator.userAgent.includes('Firefox')) return false;
  582. this.onprogress = onprogress;
  583. this.onabort = onabort;
  584. this.onerror = onerror;
  585. this.abort = null;
  586. this.loaded = init.cacheLoaded || 0;
  587. this.total = init.cacheLoaded || 0;
  588. this.lengthComputable = false;
  589. this.buffer = [];
  590. this.blob = null;
  591. this.reader = undefined;
  592. this.blobPromise = new Promise((resolve, reject) => {
  593. let xhr = new XMLHttpRequest();
  594. xhr.responseType = 'moz-chunked-arraybuffer';
  595. xhr.onload = () => { resolve(this.blob = new Blob(this.buffer)); this.buffer = null; };
  596. let cacheLoaded = this.loaded;
  597. xhr.onprogress = e => {
  598. this.loaded = e.loaded + cacheLoaded;
  599. this.total = e.total + cacheLoaded;
  600. this.lengthComputable = e.lengthComputable;
  601. this.buffer.push(new Blob([xhr.response]));
  602. if (this.onprogress) this.onprogress(this.loaded, this.total, this.lengthComputable);
  603. };
  604. xhr.onabort = e => this.onabort({ target: this, type: 'abort' });
  605. xhr.onerror = e => { this.onerror({ target: this, type: e.type }); reject(e); };
  606. this.abort = xhr.abort.bind(xhr);
  607. xhr.open('get', input);
  608. xhr.send();
  609. });
  610. this.promise = this.blobPromise;
  611. this.then = this.promise.then.bind(this.promise);
  612. this.catch = this.promise.catch.bind(this.promise);
  613. return true;
  614. }
  615. }
  616.  
  617. /***
  618. * Copyright (C) 2018 Qli5. All Rights Reserved.
  619. *
  620. * @author qli5 <goodlq11[at](163|gmail).com>
  621. *
  622. * This Source Code Form is subject to the terms of the Mozilla Public
  623. * License, v. 2.0. If a copy of the MPL was not distributed with this
  624. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  625. */
  626.  
  627. /**
  628. * A simple emulation of pthread_mutex
  629. */
  630. class Mutex {
  631. constructor() {
  632. this.queueTail = Promise.resolve();
  633. this.resolveHead = null;
  634. }
  635.  
  636. /**
  637. * await mutex.lock = pthread_mutex_lock
  638. * @returns a promise to be resolved when the mutex is available
  639. */
  640. async lock() {
  641. let myResolve;
  642. let _queueTail = this.queueTail;
  643. this.queueTail = new Promise(resolve => myResolve = resolve);
  644. await _queueTail;
  645. this.resolveHead = myResolve;
  646. return;
  647. }
  648.  
  649. /**
  650. * mutex.unlock = pthread_mutex_unlock
  651. */
  652. unlock() {
  653. this.resolveHead();
  654. return;
  655. }
  656.  
  657. /**
  658. * lock, ret = await async, unlock, return ret
  659. * @param {(Function|Promise)} promise async thing to wait for
  660. */
  661. async lockAndAwait(promise) {
  662. await this.lock();
  663. let ret;
  664. try {
  665. if (typeof promise == 'function') promise = promise();
  666. ret = await promise;
  667. }
  668. finally {
  669. this.unlock();
  670. }
  671. return ret;
  672. }
  673.  
  674. static _UNIT_TEST() {
  675. let m = new Mutex();
  676. function sleep(time) {
  677. return new Promise(r => setTimeout(r, time));
  678. }
  679. m.lockAndAwait(() => {
  680. console.warn('Check message timestamps.');
  681. console.warn('Bad:');
  682. console.warn('1 1 1 1 1:5s');
  683. console.warn(' 1 1 1 1 1:10s');
  684. console.warn('Good:');
  685. console.warn('1 1 1 1 1:5s');
  686. console.warn(' 1 1 1 1 1:10s');
  687. });
  688. m.lockAndAwait(async () => {
  689. await sleep(1000);
  690. await sleep(1000);
  691. await sleep(1000);
  692. await sleep(1000);
  693. await sleep(1000);
  694. });
  695. m.lockAndAwait(async () => console.log('5s!'));
  696. m.lockAndAwait(async () => {
  697. await sleep(1000);
  698. await sleep(1000);
  699. await sleep(1000);
  700. await sleep(1000);
  701. await sleep(1000);
  702. });
  703. m.lockAndAwait(async () => console.log('10s!'));
  704. }
  705. }
  706.  
  707. /**
  708. * @typedef DanmakuColor
  709. * @property {number} r
  710. * @property {number} g
  711. * @property {number} b
  712. */
  713. /**
  714. * @typedef Danmaku
  715. * @property {string} text
  716. * @property {number} time
  717. * @property {string} mode
  718. * @property {number} size
  719. * @property {DanmakuColor} color
  720. * @property {boolean} bottom
  721. */
  722.  
  723. const parser = {};
  724.  
  725. /**
  726. * @param {Danmaku} danmaku
  727. * @returns {boolean}
  728. */
  729. const danmakuFilter = danmaku => {
  730. if (!danmaku) return false;
  731. if (!danmaku.text) return false;
  732. if (!danmaku.mode) return false;
  733. if (!danmaku.size) return false;
  734. if (danmaku.time < 0 || danmaku.time >= 360000) return false;
  735. return true;
  736. };
  737.  
  738. const parseRgb256IntegerColor = color => {
  739. const rgb = parseInt(color, 10);
  740. const r = (rgb >>> 4) & 0xff;
  741. const g = (rgb >>> 2) & 0xff;
  742. const b = (rgb >>> 0) & 0xff;
  743. return { r, g, b };
  744. };
  745.  
  746. const parseNiconicoColor = mail => {
  747. const colorTable = {
  748. red: { r: 255, g: 0, b: 0 },
  749. pink: { r: 255, g: 128, b: 128 },
  750. orange: { r: 255, g: 184, b: 0 },
  751. yellow: { r: 255, g: 255, b: 0 },
  752. green: { r: 0, g: 255, b: 0 },
  753. cyan: { r: 0, g: 255, b: 255 },
  754. blue: { r: 0, g: 0, b: 255 },
  755. purple: { r: 184, g: 0, b: 255 },
  756. black: { r: 0, g: 0, b: 0 },
  757. };
  758. const defaultColor = { r: 255, g: 255, b: 255 };
  759. const line = mail.toLowerCase().split(/\s+/);
  760. const color = Object.keys(colorTable).find(color => line.includes(color));
  761. return color ? colorTable[color] : defaultColor;
  762. };
  763.  
  764. const parseNiconicoMode = mail => {
  765. const line = mail.toLowerCase().split(/\s+/);
  766. if (line.includes('ue')) return 'TOP';
  767. if (line.includes('shita')) return 'BOTTOM';
  768. return 'RTL';
  769. };
  770.  
  771. const parseNiconicoSize = mail => {
  772. const line = mail.toLowerCase().split(/\s+/);
  773. if (line.includes('big')) return 36;
  774. if (line.includes('small')) return 16;
  775. return 25;
  776. };
  777.  
  778. /**
  779. * @param {string|ArrayBuffer} content
  780. * @return {{ cid: number, danmaku: Array<Danmaku> }}
  781. */
  782. parser.bilibili = function (content) {
  783. const text = typeof content === 'string' ? content : new TextDecoder('utf-8').decode(content);
  784. const clean = text.replace(/(?:[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g, '');
  785. const data = (new DOMParser()).parseFromString(clean, 'text/xml');
  786. const cid = +data.querySelector('chatid').textContent;
  787. /** @type {Array<Danmaku>} */
  788. const danmaku = Array.from(data.querySelectorAll('d')).map(d => {
  789. const p = d.getAttribute('p');
  790. const [time, mode, size, color, create, bottom, sender, id] = p.split(',');
  791. return {
  792. text: d.textContent,
  793. time: +time,
  794. // We do not support ltr mode
  795. mode: [null, 'RTL', 'RTL', 'RTL', 'BOTTOM', 'TOP'][+mode],
  796. size: +size,
  797. color: parseRgb256IntegerColor(color),
  798. bottom: bottom > 0,
  799. };
  800. }).filter(danmakuFilter);
  801. return { cid, danmaku };
  802. };
  803.  
  804. /**
  805. * @param {string|ArrayBuffer} content
  806. * @return {{ cid: number, danmaku: Array<Danmaku> }}
  807. */
  808. parser.acfun = function (content) {
  809. const text = typeof content === 'string' ? content : new TextDecoder('utf-8').decode(content);
  810. const data = JSON.parse(text);
  811. const list = data.reduce((x, y) => x.concat(y), []);
  812. const danmaku = list.map(line => {
  813. const [time, color, mode, size, sender, create, uuid] = line.c.split(','), text = line.m;
  814. return {
  815. text,
  816. time: +time,
  817. color: parseRgb256IntegerColor(+color),
  818. mode: [null, 'RTL', null, null, 'BOTTOM', 'TOP'][mode],
  819. size: +size,
  820. bottom: false,
  821. uuid,
  822. };
  823. }).filter(danmakuFilter);
  824. return { danmaku };
  825. };
  826.  
  827. /**
  828. * @param {string|ArrayBuffer} content
  829. * @return {{ cid: number, danmaku: Array<Danmaku> }}
  830. */
  831. parser.niconico = function (content) {
  832. const text = typeof content === 'string' ? content : new TextDecoder('utf-8').decode(content);
  833. const data = JSON.parse(text);
  834. const list = data.map(item => item.chat).filter(x => x);
  835. const { thread } = list.find(comment => comment.thread);
  836. const danmaku = list.map(comment => {
  837. if (!comment.content || !(comment.vpos >= 0) || !comment.no) return null;
  838. const { vpos, mail = '', content, no } = comment;
  839. return {
  840. text: content,
  841. time: vpos / 100,
  842. color: parseNiconicoColor(mail),
  843. mode: parseNiconicoMode(mail),
  844. size: parseNiconicoSize(mail),
  845. bottom: false,
  846. id: no,
  847. };
  848. }).filter(danmakuFilter);
  849. return { thread, danmaku };
  850. };
  851.  
  852. const font = {};
  853.  
  854. // Meansure using canvas
  855. font.textByCanvas = function () {
  856. const canvas = document.createElement('canvas');
  857. const context = canvas.getContext('2d');
  858. return function (fontname, text, fontsize) {
  859. context.font = `bold ${fontsize}px ${fontname}`;
  860. return Math.ceil(context.measureText(text).width);
  861. };
  862. };
  863.  
  864. // Meansure using <div>
  865. font.textByDom = function () {
  866. const container = document.createElement('div');
  867. container.setAttribute('style', 'all: initial !important');
  868. const content = document.createElement('div');
  869. content.setAttribute('style', [
  870. 'top: -10000px', 'left: -10000px',
  871. 'width: auto', 'height: auto', 'position: absolute',
  872. ].map(item => item + ' !important;').join(' '));
  873. const active = () => { document.body.parentNode.appendChild(content); };
  874. if (!document.body) document.addEventListener('DOMContentLoaded', active);
  875. else active();
  876. return (fontname, text, fontsize) => {
  877. content.textContent = text;
  878. content.style.font = `bold ${fontsize}px ${fontname}`;
  879. return content.clientWidth;
  880. };
  881. };
  882.  
  883. font.text = (function () {
  884. // https://bugzilla.mozilla.org/show_bug.cgi?id=561361
  885. if (/linux/i.test(navigator.platform)) {
  886. return font.textByDom();
  887. } else {
  888. return font.textByCanvas();
  889. }
  890. }());
  891.  
  892. font.valid = (function () {
  893. const cache = new Map();
  894. const textWidth = font.text;
  895. // Use following texts for checking
  896. const sampleText = [
  897. 'The quick brown fox jumps over the lazy dog',
  898. '7531902468', ',.!-', ',。:!',
  899. '天地玄黄', '則近道矣',
  900. 'あいうえお', 'アイウエオガパ', 'アイウエオガパ',
  901. ].join('');
  902. // Some given font family is avaliable iff we can meansure different width compared to other fonts
  903. const sampleFont = [
  904. 'monospace', 'sans-serif', 'sans',
  905. 'Symbol', 'Arial', 'Comic Sans MS', 'Fixed', 'Terminal',
  906. 'Times', 'Times New Roman',
  907. 'SimSum', 'Microsoft YaHei', 'PingFang SC', 'Heiti SC', 'WenQuanYi Micro Hei',
  908. 'Pmingliu', 'Microsoft JhengHei', 'PingFang TC', 'Heiti TC',
  909. 'MS Gothic', 'Meiryo', 'Hiragino Kaku Gothic Pro', 'Hiragino Mincho Pro',
  910. ];
  911. const diffFont = function (base, test) {
  912. const baseSize = textWidth(base, sampleText, 72);
  913. const testSize = textWidth(test + ',' + base, sampleText, 72);
  914. return baseSize !== testSize;
  915. };
  916. const validFont = function (test) {
  917. if (cache.has(test)) return cache.get(test);
  918. const result = sampleFont.some(base => diffFont(base, test));
  919. cache.set(test, result);
  920. return result;
  921. };
  922. return validFont;
  923. }());
  924.  
  925. const rtlCanvas = function (options) {
  926. const {
  927. resolutionX: wc, // width of canvas
  928. resolutionY: hc, // height of canvas
  929. bottomReserved: b, // reserved bottom height for subtitle
  930. rtlDuration: u, // duration appeared on screen
  931. maxDelay: maxr, // max allowed delay
  932. } = options;
  933.  
  934. // Initial canvas border
  935. let used = [
  936. // p: top
  937. // m: bottom
  938. // tf: time completely enter screen
  939. // td: time completely leave screen
  940. // b: allow conflict with subtitle
  941. // add a fake danmaku for describe top of screen
  942. { p: -Infinity, m: 0, tf: Infinity, td: Infinity, b: false },
  943. // add a fake danmaku for describe bottom of screen
  944. { p: hc, m: Infinity, tf: Infinity, td: Infinity, b: false },
  945. // add a fake danmaku for placeholder of subtitle
  946. { p: hc - b, m: hc, tf: Infinity, td: Infinity, b: true },
  947. ];
  948. // Find out some position is available
  949. const available = (hv, t0s, t0l, b) => {
  950. const suggestion = [];
  951. // Upper edge of candidate position should always be bottom of other danmaku (or top of screen)
  952. used.forEach(i => {
  953. if (i.m + hv >= hc) return;
  954. const p = i.m;
  955. const m = p + hv;
  956. let tas = t0s;
  957. let tal = t0l;
  958. // and left border should be right edge of others
  959. used.forEach(j => {
  960. if (j.p >= m) return;
  961. if (j.m <= p) return;
  962. if (j.b && b) return;
  963. tas = Math.max(tas, j.tf);
  964. tal = Math.max(tal, j.td);
  965. });
  966. const r = Math.max(tas - t0s, tal - t0l);
  967. if (r > maxr) return;
  968. // save a candidate position
  969. suggestion.push({ p, r });
  970. });
  971. // sorted by its vertical position
  972. suggestion.sort((x, y) => x.p - y.p);
  973. let mr = maxr;
  974. // the bottom and later choice should be ignored
  975. const filtered = suggestion.filter(i => {
  976. if (i.r >= mr) return false;
  977. mr = i.r;
  978. return true;
  979. });
  980. return filtered;
  981. };
  982. // mark some area as used
  983. let use = (p, m, tf, td) => {
  984. used.push({ p, m, tf, td, b: false });
  985. };
  986. // remove danmaku not needed anymore by its time
  987. const syn = (t0s, t0l) => {
  988. used = used.filter(i => i.tf > t0s || i.td > t0l);
  989. };
  990. // give a score in range [0, 1) for some position
  991. const score = i => {
  992. if (i.r > maxr) return -Infinity;
  993. return 1 - Math.hypot(i.r / maxr, i.p / hc) * Math.SQRT1_2;
  994. };
  995. // add some danmaku
  996. return line => {
  997. const {
  998. time: t0s, // time sent (start to appear if no delay)
  999. width: wv, // width of danmaku
  1000. height: hv, // height of danmaku
  1001. bottom: b, // is subtitle
  1002. } = line;
  1003. const t0l = wc / (wv + wc) * u + t0s; // time start to leave
  1004. syn(t0s, t0l);
  1005. const al = available(hv, t0s, t0l, b);
  1006. if (!al.length) return null;
  1007. const scored = al.map(i => [score(i), i]);
  1008. const best = scored.reduce((x, y) => {
  1009. return x[0] > y[0] ? x : y;
  1010. })[1];
  1011. const ts = t0s + best.r; // time start to enter
  1012. const tf = wv / (wv + wc) * u + ts; // time complete enter
  1013. const td = u + ts; // time complete leave
  1014. use(best.p, best.p + hv, tf, td);
  1015. return {
  1016. top: best.p,
  1017. time: ts,
  1018. };
  1019. };
  1020. };
  1021.  
  1022. const fixedCanvas = function (options) {
  1023. const {
  1024. resolutionY: hc,
  1025. bottomReserved: b,
  1026. fixDuration: u,
  1027. maxDelay: maxr,
  1028. } = options;
  1029. let used = [
  1030. { p: -Infinity, m: 0, td: Infinity, b: false },
  1031. { p: hc, m: Infinity, td: Infinity, b: false },
  1032. { p: hc - b, m: hc, td: Infinity, b: true },
  1033. ];
  1034. // Find out some available position
  1035. const fr = (p, m, t0s, b) => {
  1036. let tas = t0s;
  1037. used.forEach(j => {
  1038. if (j.p >= m) return;
  1039. if (j.m <= p) return;
  1040. if (j.b && b) return;
  1041. tas = Math.max(tas, j.td);
  1042. });
  1043. const r = tas - t0s;
  1044. if (r > maxr) return null;
  1045. return { r, p, m };
  1046. };
  1047. // layout for danmaku at top
  1048. const top = (hv, t0s, b) => {
  1049. const suggestion = [];
  1050. used.forEach(i => {
  1051. if (i.m + hv >= hc) return;
  1052. suggestion.push(fr(i.m, i.m + hv, t0s, b));
  1053. });
  1054. return suggestion.filter(x => x);
  1055. };
  1056. // layout for danmaku at bottom
  1057. const bottom = (hv, t0s, b) => {
  1058. const suggestion = [];
  1059. used.forEach(i => {
  1060. if (i.p - hv <= 0) return;
  1061. suggestion.push(fr(i.p - hv, i.p, t0s, b));
  1062. });
  1063. return suggestion.filter(x => x);
  1064. };
  1065. const use = (p, m, td) => {
  1066. used.push({ p, m, td, b: false });
  1067. };
  1068. const syn = t0s => {
  1069. used = used.filter(i => i.td > t0s);
  1070. };
  1071. // Score every position
  1072. const score = (i, is_top) => {
  1073. if (i.r > maxr) return -Infinity;
  1074. const f = p => is_top ? p : (hc - p);
  1075. return 1 - (i.r / maxr * (31 / 32) + f(i.p) / hc * (1 / 32));
  1076. };
  1077. return function (line) {
  1078. const { time: t0s, height: hv, bottom: b } = line;
  1079. const is_top = line.mode === 'TOP';
  1080. syn(t0s);
  1081. const al = (is_top ? top : bottom)(hv, t0s, b);
  1082. if (!al.length) return null;
  1083. const scored = al.map(function (i) { return [score(i, is_top), i]; });
  1084. const best = scored.reduce(function (x, y) {
  1085. return x[0] > y[0] ? x : y;
  1086. }, [-Infinity, null])[1];
  1087. if (!best) return null;
  1088. use(best.p, best.m, best.r + t0s + u);
  1089. return { top: best.p, time: best.r + t0s };
  1090. };
  1091. };
  1092.  
  1093. const placeDanmaku = function (options) {
  1094. const layers = options.maxOverlap;
  1095. const normal = Array(layers).fill(null).map(x => rtlCanvas(options));
  1096. const fixed = Array(layers).fill(null).map(x => fixedCanvas(options));
  1097. return function (line) {
  1098. line.fontSize = Math.round(line.size * options.fontSize);
  1099. line.height = line.fontSize;
  1100. line.width = line.width || font.text(options.fontFamily, line.text, line.fontSize) || 1;
  1101.  
  1102. if (line.mode === 'RTL') {
  1103. const pos = normal.reduce((pos, layer) => pos || layer(line), null);
  1104. if (!pos) return null;
  1105. const { top, time } = pos;
  1106. line.layout = {
  1107. type: 'Rtl',
  1108. start: {
  1109. x: options.resolutionX + line.width / 2,
  1110. y: top + line.height,
  1111. time,
  1112. },
  1113. end: {
  1114. x: -line.width / 2,
  1115. y: top + line.height,
  1116. time: options.rtlDuration + time,
  1117. },
  1118. };
  1119. } else if (['TOP', 'BOTTOM'].includes(line.mode)) {
  1120. const pos = fixed.reduce((pos, layer) => pos || layer(line), null);
  1121. if (!pos) return null;
  1122. const { top, time } = pos;
  1123. line.layout = {
  1124. type: 'Fix',
  1125. start: {
  1126. x: Math.round(options.resolutionX / 2),
  1127. y: top + line.height,
  1128. time,
  1129. },
  1130. end: {
  1131. time: options.fixDuration + time,
  1132. },
  1133. };
  1134. }
  1135. return line;
  1136. };
  1137. };
  1138.  
  1139. // main layout algorithm
  1140. const layout = async function (danmaku, optionGetter) {
  1141. const options = JSON.parse(JSON.stringify(optionGetter));
  1142. const sorted = danmaku.slice(0).sort(({ time: x }, { time: y }) => x - y);
  1143. const place = placeDanmaku(options);
  1144. const result = Array(sorted.length);
  1145. let length = 0;
  1146. for (let i = 0, l = sorted.length; i < l; i++) {
  1147. let placed = place(sorted[i]);
  1148. if (placed) result[length++] = placed;
  1149. if ((i + 1) % 1000 === 0) {
  1150. await new Promise(resolve => setTimeout(resolve, 0));
  1151. }
  1152. }
  1153. result.length = length;
  1154. result.sort((x, y) => x.layout.start.time - y.layout.start.time);
  1155. return result;
  1156. };
  1157.  
  1158. // escape string for ass
  1159. const textEscape = s => (
  1160. // VSFilter do not support escaped "{" or "}"; we use full-width version instead
  1161. s.replace(/{/g, '{').replace(/}/g, '}').replace(/\s/g, ' ')
  1162. );
  1163.  
  1164. const formatColorChannel = v => (v & 255).toString(16).toUpperCase().padStart(2, '0');
  1165.  
  1166. // format color
  1167. const formatColor = color => '&H' + (
  1168. [color.b, color.g, color.r].map(formatColorChannel).join('')
  1169. );
  1170.  
  1171. // format timestamp
  1172. const formatTimestamp = time => {
  1173. const value = Math.round(time * 100) * 10;
  1174. const rem = value % 3600000;
  1175. const hour = (value - rem) / 3600000;
  1176. const fHour = hour.toFixed(0).padStart(2, '0');
  1177. const fRem = new Date(rem).toISOString().slice(-11, -2);
  1178. return fHour + fRem;
  1179. };
  1180.  
  1181. // test is default color
  1182. const isDefaultColor = ({ r, g, b }) => r === 255 && g === 255 && b === 255;
  1183. // test is dark color
  1184. const isDarkColor = ({ r, g, b }) => r * 0.299 + g * 0.587 + b * 0.114 < 0x30;
  1185.  
  1186. // Ass header
  1187. const header = info => [
  1188. '[Script Info]',
  1189. `Title: ${info.title}`,
  1190. `Original Script: ${info.original}`,
  1191. 'ScriptType: v4.00+',
  1192. 'Collisions: Normal',
  1193. `PlayResX: ${info.playResX}`,
  1194. `PlayResY: ${info.playResY}`,
  1195. 'Timer: 100.0000',
  1196. '',
  1197. '[V4+ Styles]',
  1198. 'Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding',
  1199. `Style: Fix,${info.fontFamily},${info.fontSize},&H${info.alpha}FFFFFF,&H${info.alpha}FFFFFF,&H${info.alpha}000000,&H${info.alpha}000000,${info.bold},0,0,0,100,100,0,0,1,2,0,2,20,20,2,0`,
  1200. `Style: Rtl,${info.fontFamily},${info.fontSize},&H${info.alpha}FFFFFF,&H${info.alpha}FFFFFF,&H${info.alpha}000000,&H${info.alpha}000000,${info.bold},0,0,0,100,100,0,0,1,2,0,2,20,20,2,0`,
  1201. '',
  1202. '[Events]',
  1203. 'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
  1204. ];
  1205.  
  1206. // Set color of text
  1207. const lineColor = ({ color }) => {
  1208. let output = [];
  1209. if (!isDefaultColor(color)) output.push(`\\c${formatColor(color)}`);
  1210. if (isDarkColor(color)) output.push(`\\3c&HFFFFFF`);
  1211. return output.join('');
  1212. };
  1213.  
  1214. // Set fontsize
  1215. let defaultFontSize;
  1216. const lineFontSize = ({ size }) => {
  1217. if (size === defaultFontSize) return '';
  1218. return `\\fs${size}`;
  1219. };
  1220. const getCommonFontSize = list => {
  1221. const count = new Map();
  1222. let commonCount = 0, common = 1;
  1223. list.forEach(({ size }) => {
  1224. let value = 1;
  1225. if (count.has(size)) value = count.get(size) + 1;
  1226. count.set(size, value);
  1227. if (value > commonCount) {
  1228. commonCount = value;
  1229. common = size;
  1230. }
  1231. });
  1232. defaultFontSize = common;
  1233. return common;
  1234. };
  1235.  
  1236. // Add animation of danmaku
  1237. const lineMove = ({ layout: { type, start = null, end = null } }) => {
  1238. if (type === 'Rtl' && start && end) return `\\move(${start.x},${start.y},${end.x},${end.y})`;
  1239. if (type === 'Fix' && start) return `\\pos(${start.x},${start.y})`;
  1240. return '';
  1241. };
  1242.  
  1243. // format one line
  1244. const formatLine = line => {
  1245. const start = formatTimestamp(line.layout.start.time);
  1246. const end = formatTimestamp(line.layout.end.time);
  1247. const type = line.layout.type;
  1248. const color = lineColor(line);
  1249. const fontSize = lineFontSize(line);
  1250. const move = lineMove(line);
  1251. const format = `${color}${fontSize}${move}`;
  1252. const text = textEscape(line.text);
  1253. return `Dialogue: 0,${start},${end},${type},,20,20,2,,{${format}}${text}`;
  1254. };
  1255.  
  1256. const ass = (danmaku, options) => {
  1257. const info = {
  1258. title: danmaku.meta.name,
  1259. original: `Generated by tiansh/ass-danmaku (embedded in liqi0816/bilitwin) based on ${danmaku.meta.url}`,
  1260. playResX: options.resolutionX,
  1261. playResY: options.resolutionY,
  1262. fontFamily: options.fontFamily,
  1263. fontSize: getCommonFontSize(danmaku.layout),
  1264. alpha: formatColorChannel(0xFF * (100 - options.textOpacity) / 100),
  1265. bold: options.bold? -1 : 0,
  1266. };
  1267. return [
  1268. ...header(info),
  1269. ...danmaku.layout.map(formatLine).filter(x => x),
  1270. ].join('\r\n');
  1271. };
  1272.  
  1273. /**
  1274. * @file Common works for reading / writing optinos
  1275. */
  1276.  
  1277. /**
  1278. * @returns {string}
  1279. */
  1280. const predefFontFamily = () => {
  1281. // const sc = ['Microsoft YaHei', 'PingFang SC', 'Noto Sans CJK SC'];
  1282. // replaced with bilibili defaults
  1283. const sc = ["SimHei", "'Microsoft JhengHei'", "SimSun", "NSimSun", "FangSong", "'Microsoft YaHei'", "'Microsoft Yahei UI Light'", "'Noto Sans CJK SC Bold'", "'Noto Sans CJK SC DemiLight'", "'Noto Sans CJK SC Regular'"];
  1284. const tc = ['Microsoft JhengHei', 'PingFang TC', 'Noto Sans CJK TC'];
  1285. const ja = ['MS PGothic', 'Hiragino Kaku Gothic Pro', 'Noto Sans CJK JP'];
  1286. const lang = navigator.language;
  1287. const fonts = /^ja/.test(lang) ? ja : /^zh(?!.*Hans).*(?:TW|HK|MO)/.test(lang) ? tc : sc;
  1288. const chosed = fonts.find(font$$1 => font.valid(font$$1)) || fonts[0];
  1289. return chosed;
  1290. };
  1291.  
  1292. const attributes = [
  1293. { name: 'resolutionX', type: 'number', min: 480, predef: 560 },
  1294. { name: 'resolutionY', type: 'number', min: 360, predef: 420 },
  1295. { name: 'bottomReserved', type: 'number', min: 0, predef: 60 },
  1296. { name: 'fontFamily', type: 'string', predef: predefFontFamily(), valid: font$$1 => font.valid(font$$1) },
  1297. { name: 'fontSize', type: 'number', min: 0, predef: 1, step: 0.01 },
  1298. { name: 'textSpace', type: 'number', min: 0, predef: 0 },
  1299. { name: 'rtlDuration', type: 'number', min: 0.1, predef: 8, step: 0.1 },
  1300. { name: 'fixDuration', type: 'number', min: 0.1, predef: 4, step: 0.1 },
  1301. { name: 'maxDelay', type: 'number', min: 0, predef: 6, step: 0.1 },
  1302. { name: 'textOpacity', type: 'number', min: 10, max: 100, predef: 60 },
  1303. { name: 'maxOverlap', type: 'number', min: 1, max: 20, predef: 1 },
  1304. { name: 'bold', type: 'boolean', predef: true },
  1305. ];
  1306.  
  1307. const attrNormalize = (option, { name, type, min = -Infinity, max = Infinity, step = 1, predef, valid }) => {
  1308. let value = option;
  1309. if (type === 'number') value = +value;
  1310. else if (type === 'string') value = '' + value;
  1311. else if (type === 'boolean') value = !!value;
  1312. if (valid && !valid(value)) value = predef;
  1313. if (type === 'number') {
  1314. if (Number.isNaN(value)) value = predef;
  1315. if (value < min) value = min;
  1316. if (value > max) value = max;
  1317. value = Math.round((value - min) / step) * step + min;
  1318. }
  1319. return value;
  1320. };
  1321.  
  1322. /**
  1323. * @param {ExtOption} option
  1324. * @returns {ExtOption}
  1325. */
  1326. const normalize = function (option) {
  1327. return Object.assign({},
  1328. ...attributes.map(attr => ({ [attr.name]: attrNormalize(option[attr.name], attr) }))
  1329. );
  1330. };
  1331.  
  1332. /**
  1333. * Convert file content to Blob which describe the file
  1334. * @param {string} content
  1335. * @returns {Blob}
  1336. */
  1337. const convertToBlob = content => {
  1338. const encoder = new TextEncoder();
  1339. // Add a BOM to make some ass parser library happier
  1340. const bom = '\ufeff';
  1341. const encoded = encoder.encode(bom + content);
  1342. const blob = new Blob([encoded], { type: 'application/octet-stream' });
  1343. return blob;
  1344. };
  1345.  
  1346. /***
  1347. * Copyright (C) 2018 Qli5. All Rights Reserved.
  1348. *
  1349. * @author qli5 <goodlq11[at](163|gmail).com>
  1350. *
  1351. * This Source Code Form is subject to the terms of the Mozilla Public
  1352. * License, v. 2.0. If a copy of the MPL was not distributed with this
  1353. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  1354. */
  1355.  
  1356. /**
  1357. * An API wrapper of tiansh/ass-danmaku for liqi0816/bilitwin
  1358. */
  1359. class ASSConverter {
  1360. /**
  1361. * @typedef {ExtOption}
  1362. * @property {number} resolutionX canvas width for drawing danmaku (px)
  1363. * @property {number} resolutionY canvas height for drawing danmaku (px)
  1364. * @property {number} bottomReserved reserved height at bottom for drawing danmaku (px)
  1365. * @property {string} fontFamily danmaku font family
  1366. * @property {number} fontSize danmaku font size (ratio)
  1367. * @property {number} textSpace space between danmaku (px)
  1368. * @property {number} rtlDuration duration of right to left moving danmaku appeared on screen (s)
  1369. * @property {number} fixDuration duration of keep bottom / top danmaku appeared on screen (s)
  1370. * @property {number} maxDelay // maxinum amount of allowed delay (s)
  1371. * @property {number} textOpacity // opacity of text, in range of [0, 1]
  1372. * @property {number} maxOverlap // maxinum layers of danmaku
  1373. */
  1374.  
  1375. /**
  1376. * @param {ExtOption} option tiansh/ass-danmaku compatible option
  1377. */
  1378. constructor(option = {}) {
  1379. this.option = option;
  1380. }
  1381.  
  1382. get option() {
  1383. return this.normalizedOption;
  1384. }
  1385.  
  1386. set option(e) {
  1387. return this.normalizedOption = normalize(e);
  1388. }
  1389.  
  1390. /**
  1391. * @param {Danmaku[]} danmaku use ASSConverter.parseXML
  1392. * @param {string} title
  1393. * @param {string} originalURL
  1394. */
  1395. async genASS(danmaku, title = 'danmaku', originalURL = 'anonymous xml') {
  1396. const layout$$1 = await layout(danmaku, this.option);
  1397. const ass$$1 = ass({
  1398. content: danmaku,
  1399. layout: layout$$1,
  1400. meta: {
  1401. name: title,
  1402. url: originalURL
  1403. }
  1404. }, this.option);
  1405. return ass$$1;
  1406. }
  1407.  
  1408. async genASSBlob(danmaku, title = 'danmaku', originalURL = 'anonymous xml') {
  1409. return convertToBlob(await this.genASS(danmaku, title, originalURL));
  1410. }
  1411.  
  1412. /**
  1413. * @typedef DanmakuColor
  1414. * @property {number} r
  1415. * @property {number} g
  1416. * @property {number} b
  1417. */
  1418.  
  1419. /**
  1420. * @typedef Danmaku
  1421. * @property {string} text
  1422. * @property {number} time
  1423. * @property {string} mode
  1424. * @property {number} size
  1425. * @property {DanmakuColor} color
  1426. * @property {boolean} bottom
  1427. */
  1428.  
  1429. /**
  1430. * @param {string} xml bilibili danmaku xml
  1431. * @returns {Danmaku[]}
  1432. */
  1433. static parseXML(xml) {
  1434. return parser.bilibili(xml).danmaku;
  1435. }
  1436.  
  1437.  
  1438. static _UNIT_TEST() {
  1439. const e = new ASSConverter();
  1440. const xml = `<?xml version="1.0" encoding="UTF-8"?><i><chatserver>chat.bilibili.com</chatserver><chatid>32873758</chatid><mission>0</mission><maxlimit>6000</maxlimit><state>0</state><realname>0</realname><source>k-v</source><d p="0.00000,1,25,16777215,1519733589,0,d286a97b,4349604072">真第一</d><d p="7.29900,1,25,16777215,1519733812,0,3548796c,4349615908">五分钟前</d><d p="587.05100,1,25,16777215,1519734291,0,f2ed792f,4349641325">惊呆了!</d><d p="136.82200,1,25,16777215,1519734458,0,1e5784f,4349652071">神王代表虚空</d><d p="0.00000,1,25,16777215,1519736251,0,f16cbf44,4349751461">66666666666666666</d><d p="590.60400,1,25,16777215,1519736265,0,fbb3d1b3,4349752331">这要吹多长时间</d><d p="537.15500,1,25,16777215,1519736280,0,1e5784f,4349753170">反而不是,疾病是个恶魔,别人说她伪装成了精灵</d><d p="872.08200,1,25,16777215,1519736881,0,1e5784f,4349787709">精灵都会吃</d><d p="2648.42500,1,25,16777215,1519737840,0,e9e6b2b4,4349844463">就不能大部分都是铜币么?</d><d p="2115.09400,1,25,16777215,1519738271,0,3548796c,4349870808">吓死我了。。。</d><d p="11.45400,1,25,16777215,1519739974,0,9937b428,4349974512">???</d><d p="1285.73900,1,25,16777215,1519748274,0,3bb4c9ee,4350512859">儿砸</d><d p="595.48600,1,25,16777215,1519757148,0,f3ed26b6,4350787048">怕是要吹到缺氧哦</d><d p="1206.31500,1,25,16777215,1519767204,0,62a9186a,4350882680">233333333333333</d><d p="638.68700,1,25,16777215,1519769219,0,de0a99ae,4350893310">菜鸡的借口</d><d p="655.76500,1,25,16777215,1519769236,0,de0a99ae,4350893397">竟然吹蜡烛打医生</d><d p="2235.89600,1,25,16777215,1519769418,0,de0a99ae,4350894325">这暴击率太高了</d><d p="389.88700,1,25,16777215,1519780435,0,8879732c,4351021740">医生好想进10万,血,上万甲</d><d p="2322.47900,1,25,16777215,1519780901,0,e509a801,4351032321">前一个命都没了</d><d p="2408.93600,1,25,16777215,1519801350,0,1a692eb6,4351826484">23333333333333</d><d p="1290.62000,1,25,16777215,1519809649,0,af8f12dc,4352159267">儿砸~</d><d p="917.96300,1,25,16777215,1519816770,0,fef64b6a,4352474878">应该姆西自己控制洛斯 七杀点太快了差评</d><d p="2328.03100,1,25,16777215,1519825291,0,8549205d,4352919003">现在前一个连命都没了啊喂</d><d p="1246.16700,1,25,16777215,1519827514,0,fef64b6a,4353052309">不如走到面前用扫射 基本全中 伤害爆表</d><d p="592.38100,1,25,16777215,1519912489,0,edc3f0a9,4355960085">这是这个游戏最震撼的几幕之一</d></i>`;
  1441. console.log(window.ass = e.genASSBlob(ASSConverter.parseXML(xml)));
  1442. }
  1443. }
  1444.  
  1445. /***
  1446. * Copyright (C) 2018 Qli5. All Rights Reserved.
  1447. *
  1448. * @author qli5 <goodlq11[at](163|gmail).com>
  1449. *
  1450. * This Source Code Form is subject to the terms of the Mozilla Public
  1451. * License, v. 2.0. If a copy of the MPL was not distributed with this
  1452. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  1453. */
  1454.  
  1455. /**
  1456. * A util to hook a function
  1457. */
  1458. class HookedFunction extends Function {
  1459. constructor(...init) {
  1460. // 1. init parameter
  1461. const { raw, pre, post } = HookedFunction.parseParameter(...init);
  1462.  
  1463. // 2. build bundle
  1464. const self = function (...args) {
  1465. const { raw, pre, post } = self;
  1466. const context = { args, target: raw, ret: undefined, hook: self };
  1467. pre.forEach(e => e.call(this, context));
  1468. if (context.target) context.ret = context.target.apply(this, context.args);
  1469. post.forEach(e => e.call(this, context));
  1470. return context.ret;
  1471. };
  1472. Object.setPrototypeOf(self, HookedFunction.prototype);
  1473. self.raw = raw;
  1474. self.pre = pre;
  1475. self.post = post;
  1476.  
  1477. // 3. cheat babel - it complains about missing super(), even if it is actual valid
  1478. try {
  1479. return self;
  1480. } catch (e) {
  1481. super();
  1482. return self;
  1483. }
  1484. }
  1485.  
  1486. addPre(...func) {
  1487. this.pre.push(...func);
  1488. }
  1489.  
  1490. addPost(...func) {
  1491. this.post.push(...func);
  1492. }
  1493.  
  1494. addCallback(...func) {
  1495. this.addPost(...func);
  1496. }
  1497.  
  1498. removePre(func) {
  1499. this.pre = this.pre.filter(e => e != func);
  1500. }
  1501.  
  1502. removePost(func) {
  1503. this.post = this.post.filter(e => e != func);
  1504. }
  1505.  
  1506. removeCallback(func) {
  1507. this.removePost(func);
  1508. }
  1509.  
  1510. static parseParameter(...init) {
  1511. // 1. clone init
  1512. init = init.slice();
  1513.  
  1514. // 2. default
  1515. let raw = null;
  1516. let pre = [];
  1517. let post = [];
  1518.  
  1519. // 3. (raw, ...others)
  1520. if (typeof init[0] === 'function') raw = init.shift();
  1521.  
  1522. // 4. iterate through parameters
  1523. for (const e of init) {
  1524. if (!e) {
  1525. continue;
  1526. }
  1527. else if (Array.isArray(e)) {
  1528. pre = post;
  1529. post = e;
  1530. }
  1531. else if (typeof e == 'object') {
  1532. if (typeof e.raw == 'function') raw = e.raw;
  1533. if (typeof e.pre == 'function') pre.push(e.pre);
  1534. if (typeof e.post == 'function') post.push(e.post);
  1535. if (Array.isArray(e.pre)) pre = e.pre;
  1536. if (Array.isArray(e.post)) post = e.post;
  1537. }
  1538. else if (typeof e == 'function') {
  1539. post.push(e);
  1540. }
  1541. else {
  1542. throw new TypeError(`HookedFunction: cannot recognize paramter ${e} of type ${typeof e}`);
  1543. }
  1544. }
  1545. return { raw, pre, post };
  1546. }
  1547.  
  1548. static hook(...init) {
  1549. // 1. init parameter
  1550. const { raw, pre, post } = HookedFunction.parseParameter(...init);
  1551.  
  1552. // 2 wrap
  1553. // 2.1 already wrapped => concat
  1554. if (raw instanceof HookedFunction) {
  1555. raw.pre.push(...pre);
  1556. raw.post.push(...post);
  1557. return raw;
  1558. }
  1559.  
  1560. // 2.2 otherwise => new
  1561. else {
  1562. return new HookedFunction({ raw, pre, post });
  1563. }
  1564. }
  1565.  
  1566. static hookDebugger(raw, pre = true, post = false) {
  1567. // 1. init hook
  1568. if (!HookedFunction.hookDebugger.hook) HookedFunction.hookDebugger.hook = function (ctx) { debugger };
  1569.  
  1570. // 2 wrap
  1571. // 2.1 already wrapped => concat
  1572. if (raw instanceof HookedFunction) {
  1573. if (pre && !raw.pre.includes(HookedFunction.hookDebugger.hook)) {
  1574. raw.pre.push(HookedFunction.hookDebugger.hook);
  1575. }
  1576. if (post && !raw.post.includes(HookedFunction.hookDebugger.hook)) {
  1577. raw.post.push(HookedFunction.hookDebugger.hook);
  1578. }
  1579. return raw;
  1580. }
  1581.  
  1582. // 2.2 otherwise => new
  1583. else {
  1584. return new HookedFunction({
  1585. raw,
  1586. pre: pre && HookedFunction.hookDebugger.hook || undefined,
  1587. post: post && HookedFunction.hookDebugger.hook || undefined,
  1588. });
  1589. }
  1590. }
  1591. }
  1592.  
  1593. /***
  1594. * BiliMonkey
  1595. * A bilibili user script
  1596. * Copyright (C) 2018 Qli5. All Rights Reserved.
  1597. *
  1598. * @author qli5 <goodlq11[at](163|gmail).com>
  1599. *
  1600. * This Source Code Form is subject to the terms of the Mozilla Public
  1601. * License, v. 2.0. If a copy of the MPL was not distributed with this
  1602. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  1603. *
  1604. * The FLV merge utility is a Javascript translation of
  1605. * https://github.com/grepmusic/flvmerge
  1606. * by grepmusic
  1607. *
  1608. * The ASS convert utility is a fork of
  1609. * https://github.com/tiansh/ass-danmaku
  1610. * by tiansh
  1611. *
  1612. * The FLV demuxer is from
  1613. * https://github.com/Bilibili/flv.js/
  1614. * by zheng qian
  1615. *
  1616. * The EMBL builder is from
  1617. * <https://www.npmjs.com/package/simple-ebml-builder>
  1618. * by ryiwamoto
  1619. */
  1620.  
  1621. class BiliMonkey {
  1622. constructor(playerWin, option = BiliMonkey.optionDefaults) {
  1623. this.playerWin = playerWin;
  1624. this.protocol = playerWin.location.protocol;
  1625. this.cid = null;
  1626. this.flvs = null;
  1627. this.mp4 = null;
  1628. this.ass = null;
  1629. this.flvFormatName = null;
  1630. this.mp4FormatName = null;
  1631. this.fallbackFormatName = null;
  1632. this.cidAsyncContainer = new AsyncContainer();
  1633. this.cidAsyncContainer.then(cid => { this.cid = cid; this.ass = this.getASS(); });
  1634. if (typeof top.cid === 'string') this.cidAsyncContainer.resolve(top.cid);
  1635.  
  1636. /***
  1637. * cache + proxy = Service Worker
  1638. * Hope bilibili will have a SW as soon as possible.
  1639. * partial = Stream
  1640. * Hope the fetch API will be stabilized as soon as possible.
  1641. * If you are using your grandpa's browser, do not enable these functions.
  1642. */
  1643. this.cache = option.cache;
  1644. this.partial = option.partial;
  1645. this.proxy = option.proxy;
  1646. this.blocker = option.blocker;
  1647. this.font = option.font;
  1648. this.option = option;
  1649. if (this.cache && (!(this.cache instanceof CacheDB))) this.cache = new CacheDB('biliMonkey', 'flv', 'name');
  1650.  
  1651. this.flvsDetailedFetch = [];
  1652. this.flvsBlob = [];
  1653.  
  1654. this.defaultFormatPromise = null;
  1655. this.queryInfoMutex = new Mutex();
  1656. this.queryInfoMutex.lockAndAwait(() => this.getPlayerButtons());
  1657. this.queryInfoMutex.lockAndAwait(() => this.getAvailableFormatName());
  1658.  
  1659. this.destroy = new HookedFunction();
  1660. }
  1661.  
  1662. /***
  1663. * Guide: for ease of debug, please use format name(flv720) instead of format value(64) unless necessary
  1664. * Guide: for ease of html concat, please use string format value('64') instead of number(parseInt('64'))
  1665. */
  1666. lockFormat(format) {
  1667. // null => uninitialized
  1668. // async pending => another one is working on it
  1669. // async resolve => that guy just finished work
  1670. // sync value => someone already finished work
  1671. const toast = this.playerWin.document.getElementsByClassName('bilibili-player-video-toast-top')[0];
  1672. if (toast) toast.style.visibility = 'hidden';
  1673. if (format == this.fallbackFormatName) return null;
  1674. switch (format) {
  1675. // Single writer is not a must.
  1676. // Plus, if one writer fail, others should be able to overwrite its garbage.
  1677. case 'flv_p60':
  1678. case 'flv720_p60':
  1679. case 'hdflv2':
  1680. case 'flv':
  1681. case 'flv720':
  1682. case 'flv480':
  1683. case 'flv360':
  1684. //if (this.flvs) return this.flvs;
  1685. return this.flvs = new AsyncContainer();
  1686. case 'hdmp4':
  1687. case 'mp4':
  1688. //if (this.mp4) return this.mp4;
  1689. return this.mp4 = new AsyncContainer();
  1690. default:
  1691. throw `lockFormat error: ${format} is a unrecognizable format`;
  1692. }
  1693. }
  1694.  
  1695. resolveFormat(res, shouldBe) {
  1696. const toast = this.playerWin.document.getElementsByClassName('bilibili-player-video-toast-top')[0];
  1697. if (toast) {
  1698. toast.style.visibility = '';
  1699. if (toast.children.length) toast.children[0].style.visibility = 'hidden';
  1700. const video = this.playerWin.document.getElementsByTagName('video')[0];
  1701. if (video) {
  1702. const h = () => {
  1703. if (toast.children.length) toast.children[0].style.visibility = 'hidden';
  1704. };
  1705. video.addEventListener('emptied', h, { once: true });
  1706. setTimeout(() => video.removeEventListener('emptied', h), 500);
  1707. }
  1708.  
  1709. }
  1710. if (res.format == this.fallbackFormatName) return null;
  1711. switch (res.format) {
  1712. case 'flv_p60':
  1713. case 'flv720_p60':
  1714. case 'hdflv2':
  1715. case 'flv':
  1716. case 'flv720':
  1717. case 'flv480':
  1718. case 'flv360':
  1719. if (shouldBe && shouldBe != res.format) {
  1720. this.flvs = null;
  1721. throw `URL interface error: response is not ${shouldBe}`;
  1722. }
  1723. return this.flvs = this.flvs.resolve(res.durl.map(e => e.url.replace('http:', this.protocol)));
  1724. case 'hdmp4':
  1725. case 'mp4':
  1726. if (shouldBe && shouldBe != res.format) {
  1727. this.mp4 = null;
  1728. throw `URL interface error: response is not ${shouldBe}`;
  1729. }
  1730. return this.mp4 = this.mp4.resolve(res.durl[0].url.replace('http:', this.protocol));
  1731. default:
  1732. throw `resolveFormat error: ${res.format} is a unrecognizable format`;
  1733. }
  1734. }
  1735.  
  1736. getVIPStatus() {
  1737. const data = this.playerWin.sessionStorage.getItem('bili_login_status');
  1738. try {
  1739. return JSON.parse(data).some(e => e instanceof Object && e.vipStatus);
  1740. }
  1741. catch (e) {
  1742. return false;
  1743. }
  1744. }
  1745.  
  1746. getAvailableFormatName(accept_quality) {
  1747. if (!Array.isArray(accept_quality)) accept_quality = Array.from(this.playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul').getElementsByTagName('li')).map(e => e.getAttribute('data-value'));
  1748.  
  1749. const accept_format = accept_quality.map(e => BiliMonkey.valueToFormat(e));
  1750.  
  1751. const vipExclusiveFormatSet = new Set(['flv_p60', 'hdflv2', 'flv720_p60']);
  1752. const candidateFormatSet = new Set(this.getVIPStatus() ? accept_format : accept_format.filter(e => !vipExclusiveFormatSet.has(e)));
  1753.  
  1754. this.flvFormatName = ['flv_p60', 'hdflv2', 'flv', 'flv720_p60', 'flv720', 'flv480', 'flv360']
  1755. .find(e => candidateFormatSet.has(e))
  1756. || 'does_not_exist';
  1757.  
  1758. this.mp4FormatName = ['hdmp4', 'mp4']
  1759. .find(e => candidateFormatSet.has(e))
  1760. || 'does_not_exist';
  1761.  
  1762. if (this.flvFormatName == 'does_not_exist' || this.mp4FormatName == 'does_not_exist') {
  1763. this.fallbackFormatName = ['mp4', 'flv360'].find(e => candidateFormatSet.has(e));
  1764. if (!this.fallbackFormatName) throw 'BiliMonkey: cannot get available format names (this video has only one available quality?)';
  1765. }
  1766. }
  1767.  
  1768. async execOptions() {
  1769. if (this.option.autoDefault) await this.sniffDefaultFormat();
  1770. if (this.option.autoFLV) this.queryInfo('flv');
  1771. if (this.option.autoMP4) this.queryInfo('mp4');
  1772. }
  1773.  
  1774. async sniffDefaultFormat() {
  1775. if (this.defaultFormatPromise) return this.defaultFormatPromise;
  1776. if (this.playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul li')) return this.defaultFormatPromise = Promise.resolve();
  1777.  
  1778. const jq = this.playerWin.jQuery;
  1779. const _ajax = jq.ajax;
  1780.  
  1781. this.defaultFormatPromise = new Promise(resolve => {
  1782. let timeout = setTimeout(() => { jq.ajax = _ajax; resolve(); }, 3000);
  1783. let self = this;
  1784. jq.ajax = function (a, c) {
  1785. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  1786. clearTimeout(timeout);
  1787. self.cidAsyncContainer.resolve(a.url.match(/cid=\d+/)[0].slice(4));
  1788. let _success = a.success;
  1789. a.success = res => {
  1790. // 1. determine available format names
  1791. self.getAvailableFormatName(res.accept_quality);
  1792.  
  1793. // 2. determine if we should take this response
  1794. const format = res.format;
  1795. if (format == self.mp4FormatName || format == self.flvFormatName) {
  1796. self.lockFormat(format);
  1797. self.resolveFormat(res, format);
  1798. }
  1799.  
  1800. // 3. callback
  1801. if (self.proxy && self.flvs) {
  1802. self.setupProxy(res, _success);
  1803. }
  1804. else {
  1805. _success(res);
  1806. }
  1807.  
  1808. // 4. return to await
  1809. resolve(res);
  1810. };
  1811. jq.ajax = _ajax;
  1812. }
  1813. return _ajax.call(jq, a, c);
  1814. };
  1815. });
  1816. return this.defaultFormatPromise;
  1817. }
  1818.  
  1819. async getBackgroundFormat(format) {
  1820. if (format == 'hdmp4' || format == 'mp4') {
  1821. let src = this.playerWin.document.getElementsByTagName('video')[0].src;
  1822. if ((src.includes('hd') || format == 'mp4') && src.includes('.mp4')) {
  1823. let pendingFormat = this.lockFormat(format);
  1824. this.resolveFormat({ durl: [{ url: src }] }, format);
  1825. return pendingFormat;
  1826. }
  1827. }
  1828.  
  1829. const jq = this.playerWin.jQuery;
  1830. const _ajax = jq.ajax;
  1831.  
  1832. let pendingFormat = this.lockFormat(format);
  1833. let self = this;
  1834. jq.ajax = function (a, c) {
  1835. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  1836. self.cidAsyncContainer.resolve(a.url.match(/cid=\d+/)[0].slice(4));
  1837. let _success = a.success;
  1838. a.success = res => {
  1839. if (format == 'hdmp4') res.durl = [res.durl[0].backup_url.find(e => e.includes('hd') && e.includes('.mp4'))];
  1840. if (format == 'mp4') res.durl = [res.durl[0].backup_url.find(e => !e.includes('hd') && e.includes('.mp4'))];
  1841. self.resolveFormat(res, format);
  1842. };
  1843. jq.ajax = _ajax;
  1844. }
  1845. return _ajax.call(jq, a, c);
  1846. };
  1847. this.playerWin.player.reloadAccess();
  1848.  
  1849. return pendingFormat;
  1850. }
  1851.  
  1852. async getCurrentFormat(format) {
  1853. const jq = this.playerWin.jQuery;
  1854. const _ajax = jq.ajax;
  1855. const _setItem = this.playerWin.localStorage.setItem;
  1856. const siblingFormat = this.fallbackFormatName || (format == this.flvFormatName ? this.mp4FormatName : this.flvFormatName);
  1857. const fakedRes = { 'from': 'local', 'result': 'suee', 'format': 'faked_mp4', 'timelength': 10, 'accept_format': 'hdflv2,flv,hdmp4,faked_mp4,mp4', 'accept_quality': [112, 80, 64, 32, 16], 'seek_param': 'start', 'seek_type': 'second', 'durl': [{ 'order': 1, 'length': 1000, 'size': 30000, 'url': 'https://static.hdslb.com/encoding.mp4', 'backup_url': ['https://static.hdslb.com/encoding.mp4'] }] };
  1858.  
  1859. let pendingFormat = this.lockFormat(format);
  1860. let self = this;
  1861. let blockedRequest = await new Promise(resolve => {
  1862. jq.ajax = function (a, c) {
  1863. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  1864. // Send back a fake response to enable the change-format button.
  1865. self.cidAsyncContainer.resolve(a.url.match(/cid=\d+/)[0].slice(4));
  1866. a.success(fakedRes);
  1867. self.playerWin.document.getElementsByTagName('video')[1].loop = true;
  1868. self.playerWin.document.getElementsByTagName('video')[0].addEventListener('emptied', () => resolve([a, c]), { once: true });
  1869. }
  1870. else {
  1871. return _ajax.call(jq, a, c);
  1872. }
  1873. };
  1874. this.playerWin.localStorage.setItem = () => this.playerWin.localStorage.setItem = _setItem;
  1875. this.playerWin.document.querySelector(`div.bilibili-player-video-btn-quality > div ul li[data-value="${BiliMonkey.formatToValue(siblingFormat)}"]`).click();
  1876. });
  1877.  
  1878. let siblingOK = siblingFormat == this.fallbackFormatName ? true : siblingFormat == this.flvFormatName ? this.flvs : this.mp4;
  1879. if (!siblingOK) {
  1880. this.lockFormat(siblingFormat);
  1881. blockedRequest[0].success = res => this.resolveFormat(res, siblingFormat);
  1882. _ajax.call(jq, ...blockedRequest);
  1883. }
  1884.  
  1885. jq.ajax = function (a, c) {
  1886. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  1887. let _success = a.success;
  1888. a.success = res => {
  1889. if (self.proxy) {
  1890. self.resolveFormat(res, format);
  1891. if (self.flvs) self.setupProxy(res, _success);
  1892. }
  1893. else {
  1894. _success(res);
  1895. self.resolveFormat(res, format);
  1896. }
  1897. };
  1898. jq.ajax = _ajax;
  1899. }
  1900. return _ajax.call(jq, a, c);
  1901. };
  1902. this.playerWin.localStorage.setItem = () => this.playerWin.localStorage.setItem = _setItem;
  1903. this.playerWin.document.querySelector(`div.bilibili-player-video-btn-quality > div ul li[data-value="${BiliMonkey.formatToValue(format)}"]`).click();
  1904.  
  1905. return pendingFormat;
  1906. }
  1907.  
  1908. async getNonCurrentFormat(format) {
  1909. const jq = this.playerWin.jQuery;
  1910. const _ajax = jq.ajax;
  1911. const _setItem = this.playerWin.localStorage.setItem;
  1912.  
  1913. let pendingFormat = this.lockFormat(format);
  1914. let self = this;
  1915. jq.ajax = function (a, c) {
  1916. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  1917. self.cidAsyncContainer.resolve(a.url.match(/cid=\d+/)[0].slice(4));
  1918. let _success = a.success;
  1919. _success({});
  1920. a.success = res => self.resolveFormat(res, format);
  1921. jq.ajax = _ajax;
  1922. }
  1923. return _ajax.call(jq, a, c);
  1924. };
  1925. this.playerWin.localStorage.setItem = () => this.playerWin.localStorage.setItem = _setItem;
  1926. this.playerWin.document.querySelector(`div.bilibili-player-video-btn-quality > div ul li[data-value="${BiliMonkey.formatToValue(format)}"]`).click();
  1927. return pendingFormat;
  1928. }
  1929.  
  1930. async getASS(clickableFormat) {
  1931. if (this.ass) return this.ass;
  1932. this.ass = new Promise(async resolve => {
  1933. // 1. cid
  1934. if (!this.cid) this.cid = await new Promise((resolve, reject) => {
  1935. clickableFormat = this.fallbackFormatName || clickableFormat;
  1936. if (!clickableFormat) reject('get ASS Error: cid unavailable, nor clickable format given.');
  1937. const jq = this.playerWin.jQuery;
  1938. const _ajax = jq.ajax;
  1939. const _setItem = this.playerWin.localStorage.setItem;
  1940.  
  1941. if (!this.fallbackFormatName) this.lockFormat(clickableFormat);
  1942. let self = this;
  1943. jq.ajax = function (a, c) {
  1944. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  1945. resolve(self.cid = a.url.match(/cid=\d+/)[0].slice(4));
  1946. let _success = a.success;
  1947. _success({});
  1948. a.success = res => {
  1949. if (!this.fallbackFormatName) self.resolveFormat(res, clickableFormat);
  1950. };
  1951. jq.ajax = _ajax;
  1952. }
  1953. return _ajax.call(jq, a, c);
  1954. };
  1955. this.playerWin.localStorage.setItem = () => this.playerWin.localStorage.setItem = _setItem;
  1956. this.playerWin.document.querySelector(`div.bilibili-player-video-btn-quality > div ul li[data-value="${BiliMonkey.formatToValue(clickableFormat)}"]`).click();
  1957. });
  1958.  
  1959. // 2. options
  1960. const bilibili_player_settings = this.playerWin.localStorage.bilibili_player_settings && JSON.parse(this.playerWin.localStorage.bilibili_player_settings);
  1961.  
  1962. // 2.1 blocker
  1963. let danmaku = await BiliMonkey.fetchDanmaku(this.cid);
  1964. if (bilibili_player_settings && this.blocker) {
  1965. const i = bilibili_player_settings.block.list.map(e => e.v).join('|');
  1966. if (i) {
  1967. const regexp = new RegExp(i);
  1968. danmaku = danmaku.filter(e => !regexp.test(e.text));
  1969. }
  1970. }
  1971.  
  1972. // 2.2 font
  1973. const option = bilibili_player_settings && this.font && {
  1974. 'fontFamily': bilibili_player_settings.setting_config['fontfamily'] != 'custom' ? bilibili_player_settings.setting_config['fontfamily'].split(/, ?/) : bilibili_player_settings.setting_config['fontfamilycustom'].split(/, ?/),
  1975. 'fontSize': parseFloat(bilibili_player_settings.setting_config['fontsize']),
  1976. 'textOpacity': parseFloat(bilibili_player_settings.setting_config['opacity']),
  1977. 'bold': bilibili_player_settings.setting_config['bold'] ? 1 : 0,
  1978. } || undefined;
  1979.  
  1980. // 3. generate
  1981. resolve(this.ass = top.URL.createObjectURL(await new ASSConverter(option).genASSBlob(
  1982. danmaku, top.document.title, top.location.href
  1983. )));
  1984. });
  1985. return this.ass;
  1986. }
  1987.  
  1988. async queryInfo(format) {
  1989. return this.queryInfoMutex.lockAndAwait(async () => {
  1990. switch (format) {
  1991. case 'flv':
  1992. if (this.flvs)
  1993. return this.flvs;
  1994. else if (this.flvFormatName == 'does_not_exist')
  1995. return this.flvFormatName;
  1996. else if (this.playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul li[data-selected]').getAttribute('data-value') == BiliMonkey.formatToValue(this.flvFormatName))
  1997. return this.getCurrentFormat(this.flvFormatName);
  1998. else
  1999. return this.getNonCurrentFormat(this.flvFormatName);
  2000. case 'mp4':
  2001. if (this.mp4)
  2002. return this.mp4;
  2003. else if (this.mp4FormatName == 'does_not_exist')
  2004. return this.mp4FormatName;
  2005. else if (this.playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul li[data-selected]').getAttribute('data-value') == BiliMonkey.formatToValue(this.mp4FormatName))
  2006. return this.getCurrentFormat(this.mp4FormatName);
  2007. else
  2008. return this.getNonCurrentFormat(this.mp4FormatName);
  2009. case 'ass':
  2010. if (this.ass)
  2011. return this.ass;
  2012. else if (this.playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul li[data-selected]').getAttribute('data-value') == BiliMonkey.formatToValue(this.flvFormatName))
  2013. return this.getASS(this.mp4FormatName);
  2014. else
  2015. return this.getASS(this.flvFormatName);
  2016. default:
  2017. throw `Bilimonkey: What is format ${format}?`;
  2018. }
  2019. });
  2020. }
  2021.  
  2022. async getPlayerButtons() {
  2023. if (this.playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul li')) {
  2024. return this.playerWin;
  2025. }
  2026. else {
  2027. return new Promise(resolve => {
  2028. let observer = new MutationObserver(() => {
  2029. if (this.playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul li')) {
  2030. observer.disconnect();
  2031. resolve(this.playerWin);
  2032. }
  2033. });
  2034. observer.observe(this.playerWin.document.getElementById('bilibiliPlayer'), { childList: true });
  2035. });
  2036. }
  2037. }
  2038.  
  2039. async hangPlayer() {
  2040. const fakedRes = { 'from': 'local', 'result': 'suee', 'format': 'faked_mp4', 'timelength': 10, 'accept_format': 'hdflv2,flv,hdmp4,faked_mp4,mp4', 'accept_quality': [112, 80, 64, 32, 16], 'seek_param': 'start', 'seek_type': 'second', 'durl': [{ 'order': 1, 'length': 1000, 'size': 30000, 'url': '' }] };
  2041. const jq = this.playerWin.jQuery;
  2042. const _ajax = jq.ajax;
  2043. const _setItem = this.playerWin.localStorage.setItem;
  2044.  
  2045. return this.queryInfoMutex.lockAndAwait(() => new Promise(async resolve => {
  2046. let blockerTimeout;
  2047. jq.ajax = function (a, c) {
  2048. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  2049. clearTimeout(blockerTimeout);
  2050. a.success(fakedRes);
  2051. blockerTimeout = setTimeout(() => {
  2052. jq.ajax = _ajax;
  2053. resolve();
  2054. }, 2500);
  2055. }
  2056. else {
  2057. return _ajax.call(jq, a, c);
  2058. }
  2059. };
  2060. this.playerWin.localStorage.setItem = () => this.playerWin.localStorage.setItem = _setItem;
  2061. let button = Array.from(this.playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul').getElementsByTagName('li'))
  2062. .find(e => !e.getAttribute('data-selected') && e.children.length == 2);
  2063. button.click();
  2064. }));
  2065. }
  2066.  
  2067. async loadFLVFromCache(index) {
  2068. if (!this.cache) return;
  2069. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2070. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.flv/)[0];
  2071. let item = await this.cache.getData(name);
  2072. if (!item) return;
  2073. return this.flvsBlob[index] = item.data;
  2074. }
  2075.  
  2076. async loadPartialFLVFromCache(index) {
  2077. if (!this.cache) return;
  2078. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2079. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.flv/)[0];
  2080. name = 'PC_' + name;
  2081. let item = await this.cache.getData(name);
  2082. if (!item) return;
  2083. return item.data;
  2084. }
  2085.  
  2086. async loadAllFLVFromCache() {
  2087. if (!this.cache) return;
  2088. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2089.  
  2090. let promises = [];
  2091. for (let i = 0; i < this.flvs.length; i++) promises.push(this.loadFLVFromCache(i));
  2092.  
  2093. return Promise.all(promises);
  2094. }
  2095.  
  2096. async saveFLVToCache(index, blob) {
  2097. if (!this.cache) return;
  2098. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2099. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.flv/)[0];
  2100. return this.cache.addData({ name, data: blob });
  2101. }
  2102.  
  2103. async savePartialFLVToCache(index, blob) {
  2104. if (!this.cache) return;
  2105. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2106. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.flv/)[0];
  2107. name = 'PC_' + name;
  2108. return this.cache.putData({ name, data: blob });
  2109. }
  2110.  
  2111. async cleanPartialFLVInCache(index) {
  2112. if (!this.cache) return;
  2113. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2114. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.flv/)[0];
  2115. name = 'PC_' + name;
  2116. return this.cache.deleteData(name);
  2117. }
  2118.  
  2119. async getFLV(index, progressHandler) {
  2120. if (this.flvsBlob[index]) return this.flvsBlob[index];
  2121.  
  2122. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2123. this.flvsBlob[index] = (async () => {
  2124. let cache = await this.loadFLVFromCache(index);
  2125. if (cache) return this.flvsBlob[index] = cache;
  2126. let partialFLVFromCache = await this.loadPartialFLVFromCache(index);
  2127.  
  2128. let burl = this.flvs[index];
  2129. if (partialFLVFromCache) burl += `&bstart=${partialFLVFromCache.size}`;
  2130. let opt = {
  2131. fetch: this.playerWin.fetch,
  2132. method: 'GET',
  2133. mode: 'cors',
  2134. cache: 'default',
  2135. referrerPolicy: 'no-referrer-when-downgrade',
  2136. cacheLoaded: partialFLVFromCache ? partialFLVFromCache.size : 0,
  2137. headers: partialFLVFromCache && (!burl.includes('wsTime')) ? { Range: `bytes=${partialFLVFromCache.size}-` } : undefined
  2138. };
  2139. opt.onprogress = progressHandler;
  2140. opt.onerror = opt.onabort = ({ target, type }) => {
  2141. let partialFLV = target.getPartialBlob();
  2142. if (partialFLVFromCache) partialFLV = new Blob([partialFLVFromCache, partialFLV]);
  2143. this.savePartialFLVToCache(index, partialFLV);
  2144. };
  2145.  
  2146. let fch = new DetailedFetchBlob(burl, opt);
  2147. this.flvsDetailedFetch[index] = fch;
  2148. let fullFLV = await fch.getBlob();
  2149. this.flvsDetailedFetch[index] = undefined;
  2150. if (partialFLVFromCache) {
  2151. fullFLV = new Blob([partialFLVFromCache, fullFLV]);
  2152. this.cleanPartialFLVInCache(index);
  2153. }
  2154. this.saveFLVToCache(index, fullFLV);
  2155. return (this.flvsBlob[index] = fullFLV);
  2156. })();
  2157. return this.flvsBlob[index];
  2158. }
  2159.  
  2160. async abortFLV(index) {
  2161. if (this.flvsDetailedFetch[index]) return this.flvsDetailedFetch[index].abort();
  2162. }
  2163.  
  2164. async getAllFLVs(progressHandler) {
  2165. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2166. let promises = [];
  2167. for (let i = 0; i < this.flvs.length; i++) promises.push(this.getFLV(i, progressHandler));
  2168. return Promise.all(promises);
  2169. }
  2170.  
  2171. async cleanAllFLVsInCache() {
  2172. if (!this.cache) return;
  2173. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2174.  
  2175. let ret = [];
  2176. for (let flv of this.flvs) {
  2177. let name = flv.match(/\d+-\d+(?:\d|-|hd)*\.flv/)[0];
  2178. ret.push(await this.cache.deleteData(name));
  2179. ret.push(await this.cache.deleteData('PC_' + name));
  2180. }
  2181.  
  2182. return ret;
  2183. }
  2184.  
  2185. async setupProxy(res, onsuccess) {
  2186. if (!this.setupProxy._fetch) {
  2187. const _fetch = this.setupProxy._fetch = this.playerWin.fetch;
  2188. this.playerWin.fetch = function (input, init) {
  2189. if (!input.slice || input.slice(0, 5) != 'blob:') {
  2190. return _fetch(input, init);
  2191. }
  2192. let bstart = input.indexOf('?bstart=');
  2193. if (bstart < 0) {
  2194. return _fetch(input, init);
  2195. }
  2196. if (!init.headers instanceof Headers) init.headers = new Headers(init.headers || {});
  2197. init.headers.set('Range', `bytes=${input.slice(bstart + 8)}-`);
  2198. return _fetch(input.slice(0, bstart), init)
  2199. };
  2200. this.destroy.addCallback(() => this.playerWin.fetch = _fetch);
  2201. }
  2202.  
  2203. await this.loadAllFLVFromCache();
  2204. let resProxy = Object.assign({}, res);
  2205. for (let i = 0; i < this.flvsBlob.length; i++) {
  2206. if (this.flvsBlob[i]) resProxy.durl[i].url = this.playerWin.URL.createObjectURL(this.flvsBlob[i]);
  2207. }
  2208. return onsuccess(resProxy);
  2209. }
  2210.  
  2211. static async fetchDanmaku(cid) {
  2212. return ASSConverter.parseXML(
  2213. await new Promise((resolve, reject) => {
  2214. const e = new XMLHttpRequest();
  2215. e.onload = () => resolve(e.responseText);
  2216. e.onerror = reject;
  2217. e.open('get', `https://comment.bilibili.com/${cid}.xml`, );
  2218. e.send();
  2219. })
  2220. );
  2221. }
  2222.  
  2223. static async getAllPageDefaultFormats(playerWin = top) {
  2224. const jq = playerWin.jQuery;
  2225. const _ajax = jq.ajax;
  2226.  
  2227. // 1. mutex => you must send requests one by one
  2228. const queryInfoMutex = new Mutex();
  2229.  
  2230. // 2. bilibili has a misconfigured lazy loading => keep trying
  2231. const list = await new Promise(resolve => {
  2232. const i = setInterval(() => {
  2233. const ret = playerWin.player.getPlaylist();
  2234. if (ret) {
  2235. clearInterval(i);
  2236. resolve(ret);
  2237. }
  2238. }, 500);
  2239. });
  2240.  
  2241. // 3. build {cid: information} dict
  2242. const index = list.reduce((acc, cur) => { acc[cur.cid] = cur; return acc }, {});
  2243.  
  2244. // 4. find where to stop
  2245. const end = list[list.length - 1].cid.toString();
  2246.  
  2247. // 5. collect information
  2248. const ret = [];
  2249. jq.ajax = function (a, c) {
  2250. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('comment.bilibili.com') || a.url.includes('interface.bilibili.com/player?') || a.url.includes('api.bilibili.com/x/player/playurl/token')) return _ajax.call(jq, a, c);
  2251. if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  2252. (async () => {
  2253. // 5.1 suppress success handler
  2254. a.success = undefined;
  2255.  
  2256. // 5.2 find cid
  2257. const cid = a.url.match(/cid=\d+/)[0].slice(4);
  2258.  
  2259. // 5.3 grab information
  2260. const [danmuku, res] = await Promise.all([
  2261. // 5.3.1 grab danmuku
  2262. (async () => top.URL.createObjectURL(await new ASSConverter().genASSBlob(
  2263. await BiliMonkey.fetchDanmaku(cid), top.document.title, top.location.href
  2264. )))(),
  2265.  
  2266. // 5.3.2 grab download res
  2267. _ajax.call(jq, a, c)
  2268. ]);
  2269.  
  2270. // 5.4 save information
  2271. ret.push({
  2272. durl: res.durl.map(({ url }) => url.replace('http:', playerWin.location.protocol)),
  2273. danmuku,
  2274. name: index[cid].part || index[cid].index,
  2275. outputName: res.durl[0].url.match(/\d+-\d+(?:\d|-|hd)*(?=\.flv)/) ?
  2276. /***
  2277. * see #28
  2278. * Firefox lookbehind assertion not implemented https://bugzilla.mozilla.org/show_bug.cgi?id=1225665
  2279. * try replace /-\d+(?=(?:\d|-|hd)*\.flv)/ => /(?<=\d+)-\d+(?=(?:\d|-|hd)*\.flv)/ in the future
  2280. */
  2281. res.durl[0].url.match(/\d+-\d+(?:\d|-|hd)*(?=\.flv)/)[0].replace(/-\d+(?=(?:\d|-|hd)*\.flv)/, '')
  2282. : res.durl[0].url.match(/\d(?:\d|-|hd)*(?=\.mp4)/) ?
  2283. res.durl[0].url.match(/\d(?:\d|-|hd)*(?=\.mp4)/)[0]
  2284. : cid,
  2285. cid,
  2286. res,
  2287. });
  2288.  
  2289. // 5.5 finish job
  2290. queryInfoMutex.unlock();
  2291. })();
  2292. }
  2293. return _ajax.call(jq, { url: '//0.0.0.0' });
  2294. };
  2295.  
  2296. // 6.1 from the first page
  2297. await queryInfoMutex.lock();
  2298. playerWin.player.next(1);
  2299. while (1) {
  2300. // 6.2 to the last page
  2301. await queryInfoMutex.lock();
  2302. if (ret[ret.length - 1].cid == end) break;
  2303. playerWin.player.next();
  2304. }
  2305.  
  2306. return ret;
  2307. }
  2308.  
  2309. static formatToValue(format) {
  2310. if (format == 'does_not_exist') throw `formatToValue: cannot lookup does_not_exist`;
  2311. if (typeof BiliMonkey.formatToValue.dict == 'undefined') BiliMonkey.formatToValue.dict = {
  2312. 'flv_p60': '116',
  2313. 'flv720_p60': '74',
  2314. 'flv': '80',
  2315. 'flv720': '64',
  2316. 'flv480': '32',
  2317. 'flv360': '15',
  2318.  
  2319. // legacy - late 2017
  2320. 'hdflv2': '112',
  2321. 'hdmp4': '64', // data-value is still '64' instead of '48'. '48',
  2322. 'mp4': '16',
  2323. };
  2324. return BiliMonkey.formatToValue.dict[format] || null;
  2325. }
  2326.  
  2327. static valueToFormat(value) {
  2328. if (typeof BiliMonkey.valueToFormat.dict == 'undefined') BiliMonkey.valueToFormat.dict = {
  2329. '116': 'flv_p60',
  2330. '74': 'flv720_p60',
  2331. '80': 'flv',
  2332. '64': 'flv720',
  2333. '32': 'flv480',
  2334. '15': 'flv360',
  2335.  
  2336. // legacy - late 2017
  2337. '112': 'hdflv2',
  2338. '48': 'hdmp4',
  2339. '16': 'mp4',
  2340.  
  2341. // legacy - early 2017
  2342. '3': 'flv',
  2343. '2': 'hdmp4',
  2344. '1': 'mp4',
  2345. };
  2346. return BiliMonkey.valueToFormat.dict[value] || null;
  2347. }
  2348.  
  2349. static get optionDescriptions() {
  2350. return [
  2351. // 1. automation
  2352. ['autoDefault', '尝试自动抓取:不会拖慢页面,抓取默认清晰度,但可能抓不到。'],
  2353. ['autoFLV', '强制自动抓取FLV:会拖慢页面,如果默认清晰度也是超清会更慢,但保证抓到。'],
  2354. ['autoMP4', '强制自动抓取MP4:会拖慢页面,如果默认清晰度也是高清会更慢,但保证抓到。'],
  2355.  
  2356. // 2. cache
  2357. ['cache', '关标签页不清缓存:保留完全下载好的分段到缓存,忘记另存为也没关系。'],
  2358. ['partial', '断点续传:点击“取消”保留部分下载的分段到缓存,忘记点击会弹窗确认。'],
  2359. ['proxy', '用缓存加速播放器:如果缓存里有完全下载好的分段,直接喂给网页播放器,不重新访问网络。小水管利器,播放只需500k流量。如果实在搞不清怎么播放ASS弹幕,也可以就这样用。'],
  2360.  
  2361. // 3. customizing
  2362. ['blocker', '弹幕过滤:在网页播放器里设置的屏蔽词也对下载的弹幕生效。'],
  2363. ['font', '自定义字体:在网页播放器里设置的字体、大小、加粗、透明度也对下载的弹幕生效。']
  2364. ];
  2365. }
  2366.  
  2367. static get optionDefaults() {
  2368. return {
  2369. // 1. automation
  2370. autoDefault: true,
  2371. autoFLV: false,
  2372. autoMP4: false,
  2373.  
  2374. // 2. cache
  2375. cache: true,
  2376. partial: true,
  2377. proxy: true,
  2378.  
  2379. // 3. customizing
  2380. blocker: true,
  2381. font: true,
  2382. }
  2383. }
  2384.  
  2385. static _UNIT_TEST() {
  2386. return (async () => {
  2387. let playerWin = await BiliUserJS.getPlayerWin();
  2388. window.m = new BiliMonkey(playerWin);
  2389.  
  2390. console.warn('sniffDefaultFormat test');
  2391. await m.sniffDefaultFormat();
  2392. console.log(m);
  2393.  
  2394. console.warn('data race test');
  2395. m.queryInfo('mp4');
  2396. console.log(m.queryInfo('mp4'));
  2397.  
  2398. console.warn('getNonCurrentFormat test');
  2399. console.log(await m.queryInfo('mp4'));
  2400.  
  2401. console.warn('getCurrentFormat test');
  2402. console.log(await m.queryInfo('flv'));
  2403.  
  2404. //location.reload();
  2405. })();
  2406. }
  2407. }
  2408.  
  2409. /***
  2410. * BiliPolyfill
  2411. * A bilibili user script
  2412. * Copyright (C) 2018 Qli5. All Rights Reserved.
  2413. *
  2414. * @author qli5 <goodlq11[at](163|gmail).com>
  2415. *
  2416. * This Source Code Form is subject to the terms of the Mozilla Public
  2417. * License, v. 2.0. If a copy of the MPL was not distributed with this
  2418. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  2419. */
  2420.  
  2421. class BiliPolyfill {
  2422. /***
  2423. * Assumption: aid, cid, pageno does not change during lifecycle
  2424. * Create a new BiliPolyfill if assumption breaks
  2425. */
  2426. constructor(playerWin, option = BiliPolyfill.optionDefaults, hintInfo = () => { }) {
  2427. this.playerWin = playerWin;
  2428. this.option = option;
  2429. this.hintInfo = hintInfo;
  2430.  
  2431. this.video = null;
  2432.  
  2433. this.series = [];
  2434. this.userdata = { oped: {}, restore: {} };
  2435.  
  2436. this.destroy = new HookedFunction();
  2437. this.playerWin.addEventListener('beforeunload', this.destroy);
  2438. this.destroy.addCallback(() => this.playerWin.removeEventListener('beforeunload', this.destroy));
  2439. }
  2440.  
  2441. saveUserdata() {
  2442. this.option.setStorage('biliPolyfill', JSON.stringify(this.userdata));
  2443. }
  2444.  
  2445. retrieveUserdata() {
  2446. try {
  2447. this.userdata = this.option.getStorage('biliPolyfill');
  2448. if (this.userdata.length > 1073741824) top.alert('BiliPolyfill脚本数据已经快满了,在播放器上右键->BiliPolyfill->片头片尾->检视数据,删掉一些吧。');
  2449. this.userdata = JSON.parse(this.userdata);
  2450. }
  2451. catch (e) { }
  2452. finally {
  2453. if (!this.userdata) this.userdata = {};
  2454. if (!(this.userdata.oped instanceof Object)) this.userdata.oped = {};
  2455. if (!(this.userdata.restore instanceof Object)) this.userdata.restore = {};
  2456. }
  2457. }
  2458.  
  2459. async setFunctions({ videoRefresh = false } = {}) {
  2460. // 1. initialize
  2461. this.video = await this.getPlayerVideo();
  2462.  
  2463. // 2. if not enabled, run the process without real actions
  2464. if (!this.option.betabeta) return this.getPlayerMenu();
  2465.  
  2466. // 3. set up functions that are cid static
  2467. if (!videoRefresh) {
  2468. this.retrieveUserdata();
  2469. if (this.option.badgeWatchLater) this.badgeWatchLater();
  2470. if (this.option.scroll) this.scrollToPlayer();
  2471.  
  2472. if (this.option.series) this.inferNextInSeries();
  2473.  
  2474. if (this.option.recommend) this.showRecommendTab();
  2475. if (this.option.focus) this.focusOnPlayer();
  2476. if (this.option.restorePrevent) this.restorePreventShade();
  2477. if (this.option.restoreDanmuku) this.restoreDanmukuSwitch();
  2478. if (this.option.restoreSpeed) this.restoreSpeed();
  2479. if (this.option.restoreWide) this.restoreWideScreen();
  2480. if (this.option.autoResume) this.autoResume();
  2481. if (this.option.autoPlay) this.autoPlay();
  2482. if (this.option.autoFullScreen) this.autoFullScreen();
  2483. if (this.option.limitedKeydown) this.limitedKeydownFullScreenPlay();
  2484. this.destroy.addCallback(() => this.saveUserdata());
  2485. }
  2486.  
  2487. // 4. set up functions that are binded to the video DOM
  2488. if (this.option.dblclick) this.dblclickFullScreen();
  2489. if (this.option.electric) this.reallocateElectricPanel();
  2490. if (this.option.oped) this.skipOPED();
  2491. this.video.addEventListener('emptied', () => this.setFunctions({ videoRefresh: true }), { once: true });
  2492.  
  2493. // 5. set up functions that require everything to be ready
  2494. await this.getPlayerMenu();
  2495. if (this.option.menuFocus) this.menuFocusOnPlayer();
  2496.  
  2497. // 6. set up experimental functions
  2498. if (this.option.speech) top.document.body.addEventListener('click', e => e.detail > 2 && this.speechRecognition());
  2499. }
  2500.  
  2501. async inferNextInSeries() {
  2502. // 1. find current title
  2503. const title = top.document.getElementsByTagName('h1')[0].textContent.replace(/\(\d+\)$/, '').trim();
  2504.  
  2505. // 2. find current ep number
  2506. const ep = title.match(/\d+(?=[^\d]*$)/);
  2507. if (!ep) return this.series = [];
  2508.  
  2509. // 3. current title - current ep number => series common title
  2510. const seriesTitle = title.slice(0, title.lastIndexOf(ep)).trim();
  2511.  
  2512. // 4. find sibling ep number
  2513. const epNumber = parseInt(ep);
  2514. const epSibling = ep[0] == '0' ?
  2515. [(epNumber - 1).toString().padStart(ep.length, '0'), (epNumber + 1).toString().padStart(ep.length, '0')] :
  2516. [(epNumber - 1).toString(), (epNumber + 1).toString()];
  2517.  
  2518. // 5. build search keywords
  2519. // [self, seriesTitle + epSibling, epSibling]
  2520. const keywords = [title, ...epSibling.map(e => seriesTitle + e), ...epSibling];
  2521.  
  2522. // 6. find mid
  2523. const midParent = top.document.getElementById('r-info-rank') || top.document.querySelector('.user');
  2524. if (!midParent) return this.series = [];
  2525. const mid = midParent.children[0].href.match(/\d+/)[0];
  2526.  
  2527. // 7. fetch query
  2528. const vlist = await Promise.all(keywords.map(keyword => new Promise((resolve, reject) => {
  2529. const req = new XMLHttpRequest();
  2530. req.onload = () => resolve((req.response.status && req.response.data.vlist) || []);
  2531. req.onerror = reject;
  2532. req.open('get', `https://space.bilibili.com/ajax/member/getSubmitVideos?mid=${mid}&keyword=${keyword}`);
  2533. req.responseType = 'json';
  2534. req.send();
  2535. })));
  2536.  
  2537. // 8. verify current video exists
  2538. vlist[0] = vlist[0].filter(e => e.title == title);
  2539. if (!vlist[0][0]) { console && console.warn('BiliPolyfill: inferNextInSeries: cannot find current video in mid space'); return this.series = []; }
  2540.  
  2541. // 9. if seriesTitle + epSibling qurey has reasonable results => pick
  2542. this.series = [vlist[1].find(e => e.created < vlist[0][0].created), vlist[2].reverse().find(e => e.created > vlist[0][0].created)];
  2543.  
  2544. // 10. fallback: if epSibling qurey has reasonable results => pick
  2545. if (!this.series[0]) this.series[0] = vlist[3].find(e => e.created < vlist[0][0].created);
  2546. if (!this.series[1]) this.series[1] = vlist[4].reverse().find(e => e.created > vlist[0][0].created);
  2547.  
  2548. return this.series;
  2549. }
  2550.  
  2551. badgeWatchLater() {
  2552. // 1. find watchlater button
  2553. const li = top.document.getElementById('i_menu_watchLater_btn') || top.document.getElementById('i_menu_later_btn') || top.document.querySelector('li.nav-item[report-id=playpage_watchlater]');
  2554. if (!li) return;
  2555.  
  2556. // 2. initialize watchlater panel
  2557. const observer = new MutationObserver(() => {
  2558.  
  2559. // 3. hide watchlater panel
  2560. observer.disconnect();
  2561. li.children[1].style.visibility = 'hidden';
  2562.  
  2563. // 4. loading => wait
  2564. if (li.children[1].children[0].children[0].className == 'm-w-loading') {
  2565. const observer = new MutationObserver(() => {
  2566.  
  2567. // 5. clean up watchlater panel
  2568. observer.disconnect();
  2569. li.dispatchEvent(new Event('mouseleave'));
  2570. setTimeout(() => li.children[1].style.visibility = '', 700);
  2571.  
  2572. // 6.1 empty list => do nothing
  2573. if (li.children[1].children[0].children[0].className == 'no-data') return;
  2574.  
  2575. // 6.2 otherwise => append div
  2576. const div = top.document.createElement('div');
  2577. div.className = 'num';
  2578. if (li.children[1].children[0].children[0].children.length > 5) {
  2579. div.textContent = '5+';
  2580. }
  2581. else {
  2582. div.textContent = li.children[1].children[0].children[0].children.length;
  2583. }
  2584. li.children[0].append(div);
  2585. this.destroy.addCallback(() => div.remove());
  2586. });
  2587. observer.observe(li.children[1].children[0], { childList: true });
  2588. }
  2589.  
  2590. // 4.2 otherwise => error
  2591. else {
  2592. throw 'badgeWatchLater: cannot find m-w-loading panel';
  2593. }
  2594. });
  2595. observer.observe(li, { childList: true });
  2596. li.dispatchEvent(new Event('mouseenter'));
  2597. }
  2598.  
  2599. dblclickFullScreen() {
  2600. this.video.addEventListener('dblclick', () =>
  2601. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click()
  2602. );
  2603. }
  2604.  
  2605. scrollToPlayer() {
  2606. if (top.scrollY < 200) top.document.getElementById('bofqi').scrollIntoView();
  2607. }
  2608.  
  2609. showRecommendTab() {
  2610. const h = this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-filter-btn-recommend');
  2611. if (h) h.click();
  2612. }
  2613.  
  2614. getCoverImage() {
  2615. // 1. search for img tag
  2616. const img = top.document.querySelector('.cover_image')
  2617. || top.document.querySelector('div.info-cover > a > img')
  2618. || top.document.querySelector('[data-state-play="true"] img');
  2619.  
  2620. // 2. search for ld+jason
  2621. const script = top.document.querySelector('script[type="application/ld+json"]');
  2622.  
  2623. // 3. find src
  2624. let ret = (img && img.src) || (script && JSON.parse(script.textContent).images[0]);
  2625. if (!ret) return null;
  2626.  
  2627. // 4. trim parameters
  2628. let i;
  2629. i = ret.indexOf('.jpg');
  2630. if (i != -1) ret = ret.slice(0, i + 4);
  2631. i = ret.indexOf('.png');
  2632. if (i != -1) ret = ret.slice(0, i + 4);
  2633. return ret;
  2634. }
  2635.  
  2636. reallocateElectricPanel() {
  2637. // 1. autopart == wait => ok
  2638. if (!this.playerWin.localStorage.bilibili_player_settings) return;
  2639. if (!this.playerWin.localStorage.bilibili_player_settings.includes('"autopart":1') && !this.option.electricSkippable) return;
  2640.  
  2641. // 2. wait for electric panel
  2642. this.video.addEventListener('ended', () => {
  2643. setTimeout(() => {
  2644. // 3. click skip
  2645. const electricPanel = this.playerWin.document.getElementsByClassName('bilibili-player-electric-panel')[0];
  2646. if (!electricPanel) return;
  2647. electricPanel.children[2].click();
  2648.  
  2649. // 4. but display a fake electric panel
  2650. electricPanel.style.display = 'block';
  2651. electricPanel.style.zIndex = 233;
  2652.  
  2653. // 5. and perform a fake countdown
  2654. let countdown = 5;
  2655. const h = setInterval(() => {
  2656. // 5.1 yield to next part hint
  2657. if (this.playerWin.document.getElementsByClassName('bilibili-player-video-toast-item-jump')[0]) electricPanel.style.zIndex = '';
  2658.  
  2659. // 5.2 countdown > 0 => update textContent
  2660. if (countdown > 0) {
  2661. electricPanel.children[2].children[0].textContent = `0${countdown}`;
  2662. countdown--;
  2663. }
  2664.  
  2665. // 5.3 countdown == 0 => clean up
  2666. else {
  2667. clearInterval(h);
  2668. electricPanel.remove();
  2669. }
  2670. }, 1000);
  2671. }, 0);
  2672. }, { once: true });
  2673. }
  2674.  
  2675. /**
  2676. * As of March 2018:
  2677. * opacity:
  2678. * bilibili_player_settings.setting_config.opacity
  2679. * persist :)
  2680. * preventshade:
  2681. * bilibili_player_settings.setting_config.preventshade
  2682. * will be overwritten
  2683. * bilibili has a broken setting roaming scheme where the preventshade default is always used
  2684. * type_bottom, type_scroll, type_top:
  2685. * bilibili_player_settings.setting_config.type_(bottom|scroll|top)
  2686. * sessionStorage ONLY
  2687. * not sure if it is a feature or a bug
  2688. * danmaku switch:
  2689. * not stored
  2690. * videospeed:
  2691. * bilibili_player_settings.video_status.videospeed
  2692. * sessionStorage ONLY
  2693. * same as above
  2694. * widescreen:
  2695. * same as above
  2696. */
  2697. restorePreventShade() {
  2698. // 1. restore option should be an array
  2699. if (!Array.isArray(this.userdata.restore.preventShade)) this.userdata.restore.preventShade = [];
  2700.  
  2701. // 2. find corresponding option index
  2702. const index = top.location.href.includes('bangumi') ? 0 : 1;
  2703.  
  2704. // 3. MUST initialize setting panel before click
  2705. this.playerWin.document.getElementsByClassName('bilibili-player-video-btn-danmaku')[0].dispatchEvent(new Event('mouseover'));
  2706.  
  2707. // 4. restore if true
  2708. const input = this.playerWin.document.getElementsByName('ctlbar_danmuku_prevent')[0];
  2709. if (this.userdata.restore.preventShade[index] && !input.nextElementSibling.classList.contains('bpui-state-active')) {
  2710. input.click();
  2711. }
  2712.  
  2713. // 5. clean up setting panel
  2714. this.playerWin.document.getElementsByClassName('bilibili-player-video-btn-danmaku')[0].dispatchEvent(new Event('mouseout'));
  2715.  
  2716. // 6. memorize option
  2717. this.destroy.addCallback(() => {
  2718. this.userdata.restore.preventShade[index] = input.nextElementSibling.classList.contains('bpui-state-active');
  2719. });
  2720. }
  2721.  
  2722. restoreDanmukuSwitch() {
  2723. // 1. restore option should be an array
  2724. if (!Array.isArray(this.userdata.restore.danmukuSwitch)) this.userdata.restore.danmukuSwitch = [];
  2725. if (!Array.isArray(this.userdata.restore.danmukuTopSwitch)) this.userdata.restore.danmukuTopSwitch = [];
  2726. if (!Array.isArray(this.userdata.restore.danmukuBottomSwitch)) this.userdata.restore.danmukuBottomSwitch = [];
  2727. if (!Array.isArray(this.userdata.restore.danmukuScrollSwitch)) this.userdata.restore.danmukuScrollSwitch = [];
  2728.  
  2729. // 2. find corresponding option index
  2730. const index = top.location.href.includes('bangumi') ? 0 : 1;
  2731.  
  2732. // 3. MUST initialize setting panel before click
  2733. this.playerWin.document.getElementsByClassName('bilibili-player-video-btn-danmaku')[0].dispatchEvent(new Event('mouseover'));
  2734.  
  2735. // 4. restore if true
  2736. // 4.1 danmukuSwitch
  2737. const danmukuSwitchDiv = this.playerWin.document.getElementsByClassName('bilibili-player-video-btn-danmaku')[0];
  2738. if (this.userdata.restore.danmukuSwitch[index] && !danmukuSwitchDiv.classList.contains('video-state-danmaku-off')) {
  2739. danmukuSwitchDiv.click();
  2740. }
  2741.  
  2742. // 4.2 danmukuTopSwitch danmukuBottomSwitch danmukuScrollSwitch
  2743. const [danmukuTopSwitchDiv, danmukuBottomSwitchDiv, danmukuScrollSwitchDiv] = this.playerWin.document.getElementsByClassName('bilibili-player-danmaku-setting-lite-type-list')[0].children;
  2744. if (this.userdata.restore.danmukuTopSwitch[index] && !danmukuTopSwitchDiv.classList.contains('disabled')) {
  2745. danmukuTopSwitchDiv.click();
  2746. }
  2747. if (this.userdata.restore.danmukuBottomSwitch[index] && !danmukuBottomSwitchDiv.classList.contains('disabled')) {
  2748. danmukuBottomSwitchDiv.click();
  2749. }
  2750. if (this.userdata.restore.danmukuScrollSwitch[index] && !danmukuScrollSwitchDiv.classList.contains('disabled')) {
  2751. danmukuScrollSwitchDiv.click();
  2752. }
  2753.  
  2754. // 5. clean up setting panel
  2755. this.playerWin.document.getElementsByClassName('bilibili-player-video-btn-danmaku')[0].dispatchEvent(new Event('mouseout'));
  2756.  
  2757. // 6. memorize final option
  2758. this.destroy.addCallback(() => {
  2759. this.userdata.restore.danmukuSwitch[index] = danmukuSwitchDiv.classList.contains('video-state-danmaku-off');
  2760. this.userdata.restore.danmukuTopSwitch[index] = danmukuTopSwitchDiv.classList.contains('disabled');
  2761. this.userdata.restore.danmukuBottomSwitch[index] = danmukuBottomSwitchDiv.classList.contains('disabled');
  2762. this.userdata.restore.danmukuScrollSwitch[index] = danmukuScrollSwitchDiv.classList.contains('disabled');
  2763. });
  2764. }
  2765.  
  2766. restoreSpeed() {
  2767. // 1. restore option should be an array
  2768. if (!Array.isArray(this.userdata.restore.speed)) this.userdata.restore.speed = [];
  2769.  
  2770. // 2. find corresponding option index
  2771. const index = top.location.href.includes('bangumi') ? 0 : 1;
  2772.  
  2773. // 3. restore if different
  2774. if (this.userdata.restore.speed[index] && this.userdata.restore.speed[index] != this.video.playbackRate) {
  2775. this.video.playbackRate = this.userdata.restore.speed[index];
  2776. }
  2777.  
  2778. // 4. memorize option
  2779. this.destroy.addCallback(() => {
  2780. this.userdata.restore.speed[index] = this.video.playbackRate;
  2781. });
  2782. }
  2783.  
  2784. restoreWideScreen() {
  2785. // 1. restore option should be an array
  2786. if (!Array.isArray(this.userdata.restore.wideScreen)) this.userdata.restore.wideScreen = [];
  2787.  
  2788. // 2. find corresponding option index
  2789. const index = top.location.href.includes('bangumi') ? 0 : 1;
  2790.  
  2791. // 3. restore if different
  2792. const i = this.playerWin.document.getElementsByClassName('bilibili-player-iconfont-widescreen')[0];
  2793. if (this.userdata.restore.wideScreen[index] && !i.classList.contains('icon-24wideon')) {
  2794. i.click();
  2795. }
  2796.  
  2797. // 4. memorize option
  2798. this.destroy.addCallback(() => {
  2799. this.userdata.restore.wideScreen[index] = i.classList.contains('icon-24wideon');
  2800. });
  2801. }
  2802.  
  2803. loadOffineSubtitles() {
  2804. // NO. NOBODY WILL NEED THIS。
  2805. // Hint: https://github.com/jamiees2/ass-to-vtt
  2806. throw 'Not implemented';
  2807. }
  2808.  
  2809. autoResume() {
  2810. // 1. wait for canplay => wait for resume popup
  2811. const h = () => {
  2812. // 2. parse resume popup
  2813. const span = this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom div.bilibili-player-video-toast-item-text span:nth-child(2)');
  2814. if (!span) return;
  2815. const [min, sec] = span.textContent.split(':');
  2816. if (!min || !sec) return;
  2817.  
  2818. // 3. parse last playback progress
  2819. const time = parseInt(min) * 60 + parseInt(sec);
  2820.  
  2821. // 3.1 still far from end => reasonable to resume => click
  2822. if (time < this.video.duration - 10) {
  2823. // 3.1.1 already playing => no need to pause => simply jump
  2824. if (!this.video.paused || this.video.autoplay) {
  2825. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom div.bilibili-player-video-toast-item-jump').click();
  2826. }
  2827.  
  2828. // 3.1.2 paused => should remain paused after jump => hook video.play
  2829. else {
  2830. const play = this.video.play;
  2831. this.video.play = () => setTimeout(() => {
  2832. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2833. this.video.play = play;
  2834. }, 0);
  2835. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom div.bilibili-player-video-toast-item-jump').click();
  2836. }
  2837. }
  2838.  
  2839. // 3.2 near end => silent popup
  2840. else {
  2841. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom div.bilibili-player-video-toast-item-close').click();
  2842. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom').children[0].style.visibility = 'hidden';
  2843. }
  2844. };
  2845. this.video.addEventListener('canplay', h, { once: true });
  2846. setTimeout(() => this.video && this.video.removeEventListener && this.video.removeEventListener('canplay', h), 3000);
  2847. }
  2848.  
  2849. autoPlay() {
  2850. this.video.autoplay = true;
  2851. setTimeout(() => {
  2852. if (this.video.paused) this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2853. }, 0);
  2854. }
  2855.  
  2856. autoFullScreen() {
  2857. if (this.playerWin.document.querySelector('#bilibiliPlayer div.video-state-fullscreen-off'))
  2858. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click();
  2859. }
  2860.  
  2861. getCollectionId() {
  2862. return (top.location.pathname.match(/av\d+/) || top.location.hash.match(/av\d+/) || top.document.querySelector('div.bangumi-info a').href).toString();
  2863. }
  2864.  
  2865. markOPEDPosition(index) {
  2866. const collectionId = this.getCollectionId();
  2867. if (!Array.isArray(this.userdata.oped[collectionId])) this.userdata.oped[collectionId] = [];
  2868. this.userdata.oped[collectionId][index] = this.video.currentTime;
  2869. }
  2870.  
  2871. clearOPEDPosition() {
  2872. const collectionId = this.getCollectionId();
  2873. this.userdata.oped[collectionId] = undefined;
  2874. }
  2875.  
  2876. skipOPED() {
  2877. // 1. find corresponding userdata
  2878. const collectionId = this.getCollectionId();
  2879. if (!Array.isArray(this.userdata.oped[collectionId]) || !this.userdata.oped[collectionId].length) return;
  2880.  
  2881. /**
  2882. * structure:
  2883. * listen for time update -> || <- skip -> || <- remove event listenner
  2884. */
  2885.  
  2886. // 2. | 0 <- opening -> oped[collectionId][1] | <- play --
  2887. if (!this.userdata.oped[collectionId][0] && this.userdata.oped[collectionId][1]) {
  2888. const h = () => {
  2889. if (this.video.currentTime >= this.userdata.oped[collectionId][1] - 1) {
  2890. this.video.removeEventListener('timeupdate', h);
  2891. }
  2892. else {
  2893. this.video.currentTime = this.userdata.oped[collectionId][1];
  2894. this.hintInfo('BiliPolyfill: 已跳过片头');
  2895. }
  2896. };
  2897. this.video.addEventListener('timeupdate', h);
  2898. }
  2899.  
  2900. // 3. | <- play -> | oped[collectionId][0] <- opening -> oped[collectionId][1] | <- play --
  2901. if (this.userdata.oped[collectionId][0] && this.userdata.oped[collectionId][1]) {
  2902. const h = () => {
  2903. if (this.video.currentTime >= this.userdata.oped[collectionId][1] - 1) {
  2904. this.video.removeEventListener('timeupdate', h);
  2905. }
  2906. else if (this.video.currentTime > this.userdata.oped[collectionId][0]) {
  2907. this.video.currentTime = this.userdata.oped[collectionId][1];
  2908. this.hintInfo('BiliPolyfill: 已跳过片头');
  2909. }
  2910. };
  2911. this.video.addEventListener('timeupdate', h);
  2912. }
  2913.  
  2914. // 4. -- play -> | oped[collectionId][2] <- ending -> end |
  2915. if (this.userdata.oped[collectionId][2] && !this.userdata.oped[collectionId][3]) {
  2916. const h = () => {
  2917. if (this.video.currentTime >= this.video.duration - 1) {
  2918. this.video.removeEventListener('timeupdate', h);
  2919. }
  2920. else if (this.video.currentTime > this.userdata.oped[collectionId][2]) {
  2921. this.video.currentTime = this.video.duration;
  2922. this.hintInfo('BiliPolyfill: 已跳过片尾');
  2923. }
  2924. };
  2925. this.video.addEventListener('timeupdate', h);
  2926. }
  2927.  
  2928. // 5.-- play -> | oped[collectionId][2] <- ending -> oped[collectionId][3] | <- play -> end |
  2929. if (this.userdata.oped[collectionId][2] && this.userdata.oped[collectionId][3]) {
  2930. const h = () => {
  2931. if (this.video.currentTime >= this.userdata.oped[collectionId][3] - 1) {
  2932. this.video.removeEventListener('timeupdate', h);
  2933. }
  2934. else if (this.video.currentTime > this.userdata.oped[collectionId][2]) {
  2935. this.video.currentTime = this.userdata.oped[collectionId][3];
  2936. this.hintInfo('BiliPolyfill: 已跳过片尾');
  2937. }
  2938. };
  2939. this.video.addEventListener('timeupdate', h);
  2940. }
  2941. }
  2942.  
  2943. setVideoSpeed(speed) {
  2944. if (speed < 0 || speed > 10) return;
  2945. this.video.playbackRate = speed;
  2946. }
  2947.  
  2948. focusOnPlayer() {
  2949. this.playerWin.document.getElementsByClassName('bilibili-player-video-progress')[0].click();
  2950. }
  2951.  
  2952. menuFocusOnPlayer() {
  2953. this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black')[0].addEventListener('click', () =>
  2954. setTimeout(() => this.focusOnPlayer(), 0)
  2955. );
  2956. }
  2957.  
  2958. limitedKeydownFullScreenPlay() {
  2959. // 1. listen for any user guesture
  2960. const h = e => {
  2961. // 2. not real user guesture => do nothing
  2962. if (!e.isTrusted) return;
  2963.  
  2964. // 3. key down is Enter => full screen play
  2965. if (e.key == 'Enter') {
  2966. // 3.1 full screen
  2967. if (this.playerWin.document.querySelector('#bilibiliPlayer div.video-state-fullscreen-off')) {
  2968. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click();
  2969. }
  2970.  
  2971. // 3.2 play
  2972. if (this.video.paused) {
  2973. if (this.video.readyState) {
  2974. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2975. }
  2976. else {
  2977. this.video.addEventListener('canplay', () => {
  2978. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2979. }, { once: true });
  2980. }
  2981. }
  2982. }
  2983.  
  2984. // 4. clean up listener
  2985. top.document.removeEventListener('keydown', h);
  2986. top.document.removeEventListener('click', h);
  2987. };
  2988. top.document.addEventListener('keydown', h);
  2989. top.document.addEventListener('click', h);
  2990. }
  2991.  
  2992. speechRecognition() {
  2993. // 1. polyfill
  2994. const SpeechRecognition = top.SpeechRecognition || top.webkitSpeechRecognition;
  2995. const SpeechGrammarList = top.SpeechGrammarList || top.webkitSpeechGrammarList;
  2996.  
  2997. // 2. give hint
  2998. alert('Yahaha! You found me!\nBiliTwin支持的语音命令: 播放 暂停 全屏 关闭 加速 减速 下一集\nChrome may support Cantonese or Hakka as well. See BiliPolyfill::speechRecognition.');
  2999. if (!SpeechRecognition || !SpeechGrammarList) alert('浏览器太旧啦~彩蛋没法运行~');
  3000.  
  3001. // 3. setup recognition
  3002. const player = ['播放', '暂停', '全屏', '关闭', '加速', '减速', '下一集'];
  3003. const grammar = '#JSGF V1.0; grammar player; public <player> = ' + player.join(' | ') + ' ;';
  3004. const recognition = new SpeechRecognition();
  3005. const speechRecognitionList = new SpeechGrammarList();
  3006. speechRecognitionList.addFromString(grammar, 1);
  3007. recognition.grammars = speechRecognitionList;
  3008. // cmn: Mandarin(Putonghua), yue: Cantonese, hak: Hakka
  3009. // See https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
  3010. recognition.lang = 'cmn';
  3011. recognition.continuous = true;
  3012. recognition.interimResults = false;
  3013. recognition.maxAlternatives = 1;
  3014. recognition.start();
  3015. recognition.onresult = e => {
  3016. const last = e.results.length - 1;
  3017. const transcript = e.results[last][0].transcript;
  3018. switch (transcript) {
  3019. case '播放':
  3020. if (this.video.paused) this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  3021. this.hintInfo(`BiliPolyfill: 语音:播放`);
  3022. break;
  3023. case '暂停':
  3024. if (!this.video.paused) this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  3025. this.hintInfo(`BiliPolyfill: 语音:暂停`);
  3026. break;
  3027. case '全屏':
  3028. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click();
  3029. this.hintInfo(`BiliPolyfill: 语音:全屏`);
  3030. break;
  3031. case '关闭':
  3032. top.close();
  3033. break;
  3034. case '加速':
  3035. this.setVideoSpeed(2);
  3036. this.hintInfo(`BiliPolyfill: 语音:加速`);
  3037. break;
  3038. case '减速':
  3039. this.setVideoSpeed(0.5);
  3040. this.hintInfo(`BiliPolyfill: 语音:减速`);
  3041. break;
  3042. case '下一集':
  3043. this.video.dispatchEvent(new Event('ended'));
  3044. default:
  3045. this.hintInfo(`BiliPolyfill: 语音:"${transcript}"?`);
  3046. break;
  3047. }
  3048. typeof console == "object" && console.log(e.results);
  3049. typeof console == "object" && console.log(`transcript:${transcript} confidence:${e.results[0][0].confidence}`);
  3050. };
  3051. }
  3052.  
  3053. substitudeFullscreenPlayer(option) {
  3054. // 1. check param
  3055. if (!option) throw 'usage: substitudeFullscreenPlayer({cid, aid[, p][, ...otherOptions]})';
  3056. if (!option.cid) throw 'player init: cid missing';
  3057. if (!option.aid) throw 'player init: aid missing';
  3058.  
  3059. // 2. hook exitFullscreen
  3060. const playerDoc = this.playerWin.document;
  3061. const hook = [playerDoc.webkitExitFullscreen, playerDoc.mozExitFullScreen, playerDoc.msExitFullscreen, playerDoc.exitFullscreen];
  3062. playerDoc.webkitExitFullscreen = playerDoc.mozExitFullScreen = playerDoc.msExitFullscreen = playerDoc.exitFullscreen = () => { };
  3063.  
  3064. // 3. substitude player
  3065. this.playerWin.player.destroy();
  3066. this.playerWin.player = new bilibiliPlayer(option);
  3067. if (option.p) this.playerWin.callAppointPart(option.p);
  3068.  
  3069. // 4. restore exitFullscreen
  3070. [playerDoc.webkitExitFullscreen, playerDoc.mozExitFullScreen, playerDoc.msExitFullscreen, playerDoc.exitFullscreen] = hook;
  3071. }
  3072.  
  3073. async getPlayerVideo() {
  3074. if (this.playerWin.document.getElementsByTagName('video').length) {
  3075. return this.video = this.playerWin.document.getElementsByTagName('video')[0];
  3076. }
  3077. else {
  3078. return new Promise(resolve => {
  3079. const observer = new MutationObserver(() => {
  3080. if (this.playerWin.document.getElementsByTagName('video').length) {
  3081. observer.disconnect();
  3082. resolve(this.video = this.playerWin.document.getElementsByTagName('video')[0]);
  3083. }
  3084. });
  3085. observer.observe(this.playerWin.document.getElementById('bilibiliPlayer'), { childList: true });
  3086. });
  3087. }
  3088. }
  3089.  
  3090. async getPlayerMenu() {
  3091. if (this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black').length) {
  3092. return this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black')[0];
  3093. }
  3094. else {
  3095. return new Promise(resolve => {
  3096. const observer = new MutationObserver(() => {
  3097. if (this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black').length) {
  3098. observer.disconnect();
  3099. resolve(this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black')[0]);
  3100. }
  3101. });
  3102. observer.observe(this.playerWin.document.getElementById('bilibiliPlayer'), { childList: true });
  3103. });
  3104. }
  3105. }
  3106.  
  3107. static async openMinimizedPlayer(option = { cid: top.cid, aid: top.aid, playerWin: top }) {
  3108. // 1. check param
  3109. if (!option) throw 'usage: openMinimizedPlayer({cid[, aid]})';
  3110. if (!option.cid) throw 'player init: cid missing';
  3111. if (!option.aid) option.aid = top.aid;
  3112. if (!option.playerWin) option.playerWin = top;
  3113.  
  3114. // 2. open a new window
  3115. const miniPlayerWin = top.open(`//www.bilibili.com/blackboard/html5player.html?cid=${option.cid}&aid=${option.aid}&crossDomain=${top.document.domain != 'www.bilibili.com' ? 'true' : ''}`, undefined, ' ');
  3116.  
  3117. // 3. bangumi => request referrer must match => hook response of current page
  3118. const res = top.location.href.includes('bangumi') && await new Promise(resolve => {
  3119. const jq = option.playerWin.jQuery;
  3120. const _ajax = jq.ajax;
  3121.  
  3122. jq.ajax = function (a, c) {
  3123. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  3124. a.success = resolve;
  3125. jq.ajax = _ajax;
  3126. }
  3127. return _ajax.call(jq, a, c);
  3128. };
  3129. option.playerWin.player.reloadAccess();
  3130. });
  3131.  
  3132. // 4. wait for miniPlayerWin load
  3133. await new Promise(resolve => {
  3134. // 4.1 check for every500ms
  3135. const i = setInterval(() => miniPlayerWin.document.getElementById('bilibiliPlayer') && resolve(), 500);
  3136.  
  3137. // 4.2 explict event listener
  3138. miniPlayerWin.addEventListener('load', resolve, { once: true });
  3139.  
  3140. // 4.3 timeout after 6s
  3141. setTimeout(() => {
  3142. clearInterval(i);
  3143. miniPlayerWin.removeEventListener('load', resolve);
  3144. resolve();
  3145. }, 6000);
  3146. });
  3147. // 4.4 cannot find bilibiliPlayer => load timeout
  3148. const playerDiv = miniPlayerWin.document.getElementById('bilibiliPlayer');
  3149. if (!playerDiv) { console.warn('openMinimizedPlayer: document load timeout'); return; }
  3150.  
  3151. // 5. need to inject response => new bilibiliPlayer
  3152. if (res) {
  3153. await new Promise(resolve => {
  3154. const jq = miniPlayerWin.jQuery;
  3155. const _ajax = jq.ajax;
  3156.  
  3157. jq.ajax = function (a, c) {
  3158. if (typeof c === 'object') { if (typeof a === 'string') c.url = a; a = c; c = undefined; } if (a.url.includes('interface.bilibili.com/v2/playurl?') || a.url.includes('bangumi.bilibili.com/player/web_api/v2/playurl?')) {
  3159. a.success(res);
  3160. jq.ajax = _ajax;
  3161. resolve();
  3162. }
  3163. else {
  3164. return _ajax.call(jq, a, c);
  3165. }
  3166. };
  3167. miniPlayerWin.player = new miniPlayerWin.bilibiliPlayer({ cid: option.cid, aid: option.aid });
  3168. // miniPlayerWin.eval(`player = new bilibiliPlayer({ cid: ${option.cid}, aid: ${option.aid} })`);
  3169. // console.log(`player = new bilibiliPlayer({ cid: ${option.cid}, aid: ${option.aid} })`);
  3170. });
  3171. }
  3172.  
  3173. // 6. wait for bilibiliPlayer load
  3174. await new Promise(resolve => {
  3175. if (miniPlayerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen')) resolve();
  3176. else {
  3177. const observer = new MutationObserver(() => {
  3178. if (miniPlayerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen')) {
  3179. observer.disconnect();
  3180. resolve();
  3181. }
  3182. });
  3183. observer.observe(playerDiv, { childList: true });
  3184. }
  3185. });
  3186.  
  3187. // 7. adopt full screen player style withour really trigger full screen
  3188. // 7.1 hook requestFullscreen
  3189. const hook = [playerDiv.webkitRequestFullscreen, playerDiv.mozRequestFullScreen, playerDiv.msRequestFullscreen, playerDiv.requestFullscreen];
  3190. playerDiv.webkitRequestFullscreen = playerDiv.mozRequestFullScreen = playerDiv.msRequestFullscreen = playerDiv.requestFullscreen = () => { };
  3191.  
  3192. // 7.2 adopt full screen player style
  3193. if (miniPlayerWin.document.querySelector('#bilibiliPlayer div.video-state-fullscreen-off'))
  3194. miniPlayerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click();
  3195.  
  3196. // 7.3 restore requestFullscreen
  3197. [playerDiv.webkitRequestFullscreen, playerDiv.mozRequestFullScreen, playerDiv.msRequestFullscreen, playerDiv.requestFullscreen] = hook;
  3198. }
  3199.  
  3200. static secondToReadable(s) {
  3201. if (s > 60) return `${parseInt(s / 60)}分${parseInt(s % 60)}秒`;
  3202. else return `${parseInt(s % 60)}秒`;
  3203. }
  3204.  
  3205. static clearAllUserdata(playerWin = top) {
  3206. if (playerWin.GM_setValue) return GM_setValue('biliPolyfill', '');
  3207. if (playerWin.GM.setValue) return GM.setValue('biliPolyfill', '');
  3208. playerWin.localStorage.removeItem('biliPolyfill');
  3209. }
  3210.  
  3211. static get optionDescriptions() {
  3212. return [
  3213. ['betabeta', '增强组件总开关 <---------更加懒得测试了,反正以后B站也会自己提供这些功能。也许吧。'],
  3214.  
  3215. // 1. user interface
  3216. ['badgeWatchLater', '稍后再看添加数字角标'],
  3217. ['recommend', '弹幕列表换成相关视频'],
  3218. ['electric', '整合充电榜与换P倒计时'],
  3219. ['electricSkippable', '跳过充电榜', 'disabled'],
  3220.  
  3221. // 2. automation
  3222. ['scroll', '自动滚动到播放器'],
  3223. ['focus', '自动聚焦到播放器(新页面直接按空格会播放而不是向下滚动)'],
  3224. ['menuFocus', '关闭菜单后聚焦到播放器'],
  3225. ['restorePrevent', '记住防挡字幕'],
  3226. ['restoreDanmuku', '记住弹幕开关(顶端/底端/滚动/全部)'],
  3227. ['restoreSpeed', '记住播放速度'],
  3228. ['restoreWide', '记住宽屏'],
  3229. ['autoResume', '自动跳转上次看到'],
  3230. ['autoPlay', '自动播放'],
  3231. ['autoFullScreen', '自动全屏'],
  3232. ['oped', '标记后自动跳OP/ED'],
  3233. ['series', '尝试自动找上下集'],
  3234.  
  3235. // 3. interaction
  3236. ['limitedKeydown', '首次回车键可全屏自动播放'],
  3237. ['dblclick', '双击全屏'],
  3238.  
  3239. // 4. easter eggs
  3240. ['speech', '(彩蛋)(需墙外)任意三击鼠标左键开启语音识别'],
  3241. ];
  3242. }
  3243.  
  3244. static get optionDefaults() {
  3245. return {
  3246. betabeta: false,
  3247.  
  3248. // 1. user interface
  3249. badgeWatchLater: true,
  3250. recommend: true,
  3251. electric: true,
  3252. electricSkippable: false,
  3253.  
  3254. // 2. automation
  3255. scroll: true,
  3256. focus: true,
  3257. menuFocus: true,
  3258. restorePrevent: true,
  3259. restoreDanmuku: true,
  3260. restoreSpeed: true,
  3261. restoreWide: true,
  3262. autoResume: true,
  3263. autoPlay: false,
  3264. autoFullScreen: false,
  3265. oped: true,
  3266. series: true,
  3267.  
  3268. // 3. interaction
  3269. limitedKeydown: true,
  3270. dblclick: true,
  3271.  
  3272. // 4. easter eggs
  3273. speech: false,
  3274. }
  3275. }
  3276.  
  3277. static _UNIT_TEST() {
  3278. console.warn('This test is impossible.');
  3279. console.warn('You need to close the tab, reopen it, etc.');
  3280. console.warn('Maybe you also want to test between bideo parts, etc.');
  3281. console.warn('I am too lazy to find workarounds.');
  3282. }
  3283. }
  3284.  
  3285. /***
  3286. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3287. *
  3288. * @author qli5 <goodlq11[at](163|gmail).com>
  3289. *
  3290. * This Source Code Form is subject to the terms of the Mozilla Public
  3291. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3292. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3293. */
  3294.  
  3295. class Exporter {
  3296. static exportIDM(urls, referrer = top.location.origin) {
  3297. return urls.map(url => `<\r\n${url}\r\nreferer: ${referrer}\r\n>\r\n`).join('');
  3298. }
  3299.  
  3300. static exportM3U8(urls, referrer = top.location.origin, userAgent = top.navigator.userAgent) {
  3301. return '#EXTM3U\n' + urls.map(url => `#EXTVLCOPT:http-referrer=${referrer}\n#EXTVLCOPT:http-user-agent=${userAgent}\n#EXTINF:-1\n${url}\n`).join('');
  3302. }
  3303.  
  3304. static exportAria2(urls, referrer = top.location.origin) {
  3305. return urls.map(url => `${url}\r\n referer=${referrer}\r\n`).join('');
  3306. }
  3307.  
  3308. static async sendToAria2RPC(urls, referrer = top.location.origin, target = 'http://127.0.0.1:6800/jsonrpc') {
  3309. // 1. prepare body
  3310. const h = 'referer';
  3311. const body = JSON.stringify(urls.map((url, id) => ({
  3312. id,
  3313. jsonrpc: 2,
  3314. method: "aria2.addUri",
  3315. params: [
  3316. [url],
  3317. { [h]: referrer }
  3318. ]
  3319. })));
  3320.  
  3321. // 2. send to jsonrpc target
  3322. const method = 'POST';
  3323. while (1) {
  3324. try {
  3325. return await (await fetch(target, { method, body })).json();
  3326. }
  3327. catch (e) {
  3328. target = top.prompt('Aria2 connection failed. Please provide a valid server address:', target);
  3329. if (!target) return null;
  3330. }
  3331. }
  3332. }
  3333.  
  3334. static copyToClipboard(text) {
  3335. const textarea = document.createElement('textarea');
  3336. document.body.appendChild(textarea);
  3337. textarea.value = text;
  3338. textarea.select();
  3339. document.execCommand('copy');
  3340. document.body.removeChild(textarea);
  3341. }
  3342. }
  3343.  
  3344. /***
  3345. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3346. *
  3347. * @author qli5 <goodlq11[at](163|gmail).com>
  3348. *
  3349. * This Source Code Form is subject to the terms of the Mozilla Public
  3350. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3351. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3352. */
  3353.  
  3354. class TwentyFourDataView extends DataView {
  3355. getUint24(byteOffset, littleEndian) {
  3356. if (littleEndian) throw 'littleEndian int24 not implemented';
  3357. return this.getUint32(byteOffset - 1) & 0x00FFFFFF;
  3358. }
  3359.  
  3360. setUint24(byteOffset, value, littleEndian) {
  3361. if (littleEndian) throw 'littleEndian int24 not implemented';
  3362. if (value > 0x00FFFFFF) throw 'setUint24: number out of range';
  3363. let msb = value >> 16;
  3364. let lsb = value & 0xFFFF;
  3365. this.setUint8(byteOffset, msb);
  3366. this.setUint16(byteOffset + 1, lsb);
  3367. }
  3368.  
  3369. indexOf(search, startOffset = 0, endOffset = this.byteLength - search.length + 1) {
  3370. // I know it is NAIVE
  3371. if (search.charCodeAt) {
  3372. for (let i = startOffset; i < endOffset; i++) {
  3373. if (this.getUint8(i) != search.charCodeAt(0)) continue;
  3374. let found = 1;
  3375. for (let j = 0; j < search.length; j++) {
  3376. if (this.getUint8(i + j) != search.charCodeAt(j)) {
  3377. found = 0;
  3378. break;
  3379. }
  3380. }
  3381. if (found) return i;
  3382. }
  3383. return -1;
  3384. }
  3385. else {
  3386. for (let i = startOffset; i < endOffset; i++) {
  3387. if (this.getUint8(i) != search[0]) continue;
  3388. let found = 1;
  3389. for (let j = 0; j < search.length; j++) {
  3390. if (this.getUint8(i + j) != search[j]) {
  3391. found = 0;
  3392. break;
  3393. }
  3394. }
  3395. if (found) return i;
  3396. }
  3397. return -1;
  3398. }
  3399. }
  3400. }
  3401.  
  3402. /***
  3403. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3404. *
  3405. * @author qli5 <goodlq11[at](163|gmail).com>
  3406. *
  3407. * This Source Code Form is subject to the terms of the Mozilla Public
  3408. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3409. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3410. */
  3411.  
  3412. class FLVTag {
  3413. constructor(dataView, currentOffset = 0) {
  3414. this.tagHeader = new TwentyFourDataView(dataView.buffer, dataView.byteOffset + currentOffset, 11);
  3415. this.tagData = new TwentyFourDataView(dataView.buffer, dataView.byteOffset + currentOffset + 11, this.dataSize);
  3416. this.previousSize = new TwentyFourDataView(dataView.buffer, dataView.byteOffset + currentOffset + 11 + this.dataSize, 4);
  3417. }
  3418.  
  3419. get tagType() {
  3420. return this.tagHeader.getUint8(0);
  3421. }
  3422.  
  3423. get dataSize() {
  3424. return this.tagHeader.getUint24(1);
  3425. }
  3426.  
  3427. get timestamp() {
  3428. return this.tagHeader.getUint24(4);
  3429. }
  3430.  
  3431. get timestampExtension() {
  3432. return this.tagHeader.getUint8(7);
  3433. }
  3434.  
  3435. get streamID() {
  3436. return this.tagHeader.getUint24(8);
  3437. }
  3438.  
  3439. stripKeyframesScriptData() {
  3440. let hasKeyframes = 'hasKeyframes\x01';
  3441. if (this.tagType != 0x12) throw 'can not strip non-scriptdata\'s keyframes';
  3442.  
  3443. let index;
  3444. index = this.tagData.indexOf(hasKeyframes);
  3445. if (index != -1) {
  3446. //0x0101 => 0x0100
  3447. this.tagData.setUint8(index + hasKeyframes.length, 0x00);
  3448. }
  3449.  
  3450. // Well, I think it is unnecessary
  3451. /*index = this.tagData.indexOf(keyframes)
  3452. if (index != -1) {
  3453. this.dataSize = index;
  3454. this.tagHeader.setUint24(1, index);
  3455. this.tagData = new TwentyFourDataView(this.tagData.buffer, this.tagData.byteOffset, index);
  3456. }*/
  3457. }
  3458.  
  3459. getDuration() {
  3460. if (this.tagType != 0x12) throw 'can not find non-scriptdata\'s duration';
  3461.  
  3462. let duration = 'duration\x00';
  3463. let index = this.tagData.indexOf(duration);
  3464. if (index == -1) throw 'can not get flv meta duration';
  3465.  
  3466. index += 9;
  3467. return this.tagData.getFloat64(index);
  3468. }
  3469.  
  3470. getDurationAndView() {
  3471. if (this.tagType != 0x12) throw 'can not find non-scriptdata\'s duration';
  3472.  
  3473. let duration = 'duration\x00';
  3474. let index = this.tagData.indexOf(duration);
  3475. if (index == -1) throw 'can not get flv meta duration';
  3476.  
  3477. index += 9;
  3478. return {
  3479. duration: this.tagData.getFloat64(index),
  3480. durationDataView: new TwentyFourDataView(this.tagData.buffer, this.tagData.byteOffset + index, 8)
  3481. };
  3482. }
  3483.  
  3484. getCombinedTimestamp() {
  3485. return (this.timestampExtension << 24 | this.timestamp);
  3486. }
  3487.  
  3488. setCombinedTimestamp(timestamp) {
  3489. if (timestamp < 0) throw 'timestamp < 0';
  3490. this.tagHeader.setUint8(7, timestamp >> 24);
  3491. this.tagHeader.setUint24(4, timestamp & 0x00FFFFFF);
  3492. }
  3493. }
  3494.  
  3495. /***
  3496. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3497. *
  3498. * @author qli5 <goodlq11[at](163|gmail).com>
  3499. *
  3500. * This Source Code Form is subject to the terms of the Mozilla Public
  3501. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3502. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3503. *
  3504. * The FLV merge utility is a Javascript translation of
  3505. * https://github.com/grepmusic/flvmerge
  3506. * by grepmusic
  3507. */
  3508.  
  3509. /**
  3510. * A simple flv parser
  3511. */
  3512. class FLV {
  3513. constructor(dataView) {
  3514. if (dataView.indexOf('FLV', 0, 1) != 0) throw 'Invalid FLV header';
  3515. this.header = new TwentyFourDataView(dataView.buffer, dataView.byteOffset, 9);
  3516. this.firstPreviousTagSize = new TwentyFourDataView(dataView.buffer, dataView.byteOffset + 9, 4);
  3517.  
  3518. this.tags = [];
  3519. let offset = this.headerLength + 4;
  3520. while (offset < dataView.byteLength) {
  3521. let tag = new FLVTag(dataView, offset);
  3522. // debug for scrpit data tag
  3523. // if (tag.tagType != 0x08 && tag.tagType != 0x09)
  3524. offset += 11 + tag.dataSize + 4;
  3525. this.tags.push(tag);
  3526. }
  3527.  
  3528. if (offset != dataView.byteLength) throw 'FLV unexpected end of file';
  3529. }
  3530.  
  3531. get type() {
  3532. return 'FLV';
  3533. }
  3534.  
  3535. get version() {
  3536. return this.header.getUint8(3);
  3537. }
  3538.  
  3539. get typeFlag() {
  3540. return this.header.getUint8(4);
  3541. }
  3542.  
  3543. get headerLength() {
  3544. return this.header.getUint32(5);
  3545. }
  3546.  
  3547. static merge(flvs) {
  3548. if (flvs.length < 1) throw 'Usage: FLV.merge([flvs])';
  3549. let blobParts = [];
  3550. let basetimestamp = [0, 0];
  3551. let lasttimestamp = [0, 0];
  3552. let duration = 0.0;
  3553. let durationDataView;
  3554.  
  3555. blobParts.push(flvs[0].header);
  3556. blobParts.push(flvs[0].firstPreviousTagSize);
  3557.  
  3558. for (let flv of flvs) {
  3559. let bts = duration * 1000;
  3560. basetimestamp[0] = lasttimestamp[0];
  3561. basetimestamp[1] = lasttimestamp[1];
  3562. bts = Math.max(bts, basetimestamp[0], basetimestamp[1]);
  3563. let foundDuration = 0;
  3564. for (let tag of flv.tags) {
  3565. if (tag.tagType == 0x12 && !foundDuration) {
  3566. duration += tag.getDuration();
  3567. foundDuration = 1;
  3568. if (flv == flvs[0]) {
  3569. ({ duration, durationDataView } = tag.getDurationAndView());
  3570. tag.stripKeyframesScriptData();
  3571. blobParts.push(tag.tagHeader);
  3572. blobParts.push(tag.tagData);
  3573. blobParts.push(tag.previousSize);
  3574. }
  3575. }
  3576. else if (tag.tagType == 0x08 || tag.tagType == 0x09) {
  3577. lasttimestamp[tag.tagType - 0x08] = bts + tag.getCombinedTimestamp();
  3578. tag.setCombinedTimestamp(lasttimestamp[tag.tagType - 0x08]);
  3579. blobParts.push(tag.tagHeader);
  3580. blobParts.push(tag.tagData);
  3581. blobParts.push(tag.previousSize);
  3582. }
  3583. }
  3584. }
  3585. durationDataView.setFloat64(0, duration);
  3586.  
  3587. return new Blob(blobParts);
  3588. }
  3589.  
  3590. static async mergeBlobs(blobs) {
  3591. // Blobs can be swapped to disk, while Arraybuffers can not.
  3592. // This is a RAM saving workaround. Somewhat.
  3593. if (blobs.length < 1) throw 'Usage: FLV.mergeBlobs([blobs])';
  3594. let ret = [];
  3595. let basetimestamp = [0, 0];
  3596. let lasttimestamp = [0, 0];
  3597. let duration = 0.0;
  3598. let durationDataView;
  3599.  
  3600. for (let blob of blobs) {
  3601. let bts = duration * 1000;
  3602. basetimestamp[0] = lasttimestamp[0];
  3603. basetimestamp[1] = lasttimestamp[1];
  3604. bts = Math.max(bts, basetimestamp[0], basetimestamp[1]);
  3605. let foundDuration = 0;
  3606.  
  3607. let flv = await new Promise((resolve, reject) => {
  3608. let fr = new FileReader();
  3609. fr.onload = () => resolve(new FLV(new TwentyFourDataView(fr.result)));
  3610. fr.readAsArrayBuffer(blob);
  3611. fr.onerror = reject;
  3612. });
  3613.  
  3614. let modifiedMediaTags = [];
  3615. for (let tag of flv.tags) {
  3616. if (tag.tagType == 0x12 && !foundDuration) {
  3617. duration += tag.getDuration();
  3618. foundDuration = 1;
  3619. if (blob == blobs[0]) {
  3620. ret.push(flv.header, flv.firstPreviousTagSize);
  3621. ({ duration, durationDataView } = tag.getDurationAndView());
  3622. tag.stripKeyframesScriptData();
  3623. ret.push(tag.tagHeader);
  3624. ret.push(tag.tagData);
  3625. ret.push(tag.previousSize);
  3626. }
  3627. }
  3628. else if (tag.tagType == 0x08 || tag.tagType == 0x09) {
  3629. lasttimestamp[tag.tagType - 0x08] = bts + tag.getCombinedTimestamp();
  3630. tag.setCombinedTimestamp(lasttimestamp[tag.tagType - 0x08]);
  3631. modifiedMediaTags.push(tag.tagHeader, tag.tagData, tag.previousSize);
  3632. }
  3633. }
  3634. ret.push(new Blob(modifiedMediaTags));
  3635. }
  3636. durationDataView.setFloat64(0, duration);
  3637.  
  3638. return new Blob(ret);
  3639. }
  3640. }
  3641.  
  3642. var embeddedHTML = `<html>
  3643.  
  3644. <body>
  3645. <p>
  3646. 加载文件…… loading files...
  3647. <progress value="0" max="100" id="fileProgress"></progress>
  3648. </p>
  3649. <p>
  3650. 构建mkv…… building mkv...
  3651. <progress value="0" max="100" id="mkvProgress"></progress>
  3652. </p>
  3653. <p>
  3654. <a id="a" download="merged.mkv">merged.mkv</a>
  3655. </p>
  3656. <footer>
  3657. author qli5 &lt;goodlq11[at](163|gmail).com&gt;
  3658. </footer>
  3659. <script>
  3660. var FLVASS2MKV = (function () {
  3661. 'use strict';
  3662.  
  3663. /***
  3664. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3665. *
  3666. * @author qli5 <goodlq11[at](163|gmail).com>
  3667. *
  3668. * This Source Code Form is subject to the terms of the Mozilla Public
  3669. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3670. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3671. */
  3672.  
  3673. const _navigator = typeof navigator === 'object' && navigator || { userAgent: 'chrome' };
  3674.  
  3675. const _Blob = typeof Blob === 'function' && Blob || class {
  3676. constructor(array) {
  3677. return Buffer.concat(array.map(Buffer.from.bind(Buffer)));
  3678. }
  3679. };
  3680.  
  3681. const _TextEncoder = typeof TextEncoder === 'function' && TextEncoder || class {
  3682. /**
  3683. * @param {string} chunk
  3684. * @returns {Uint8Array}
  3685. */
  3686. encode(chunk) {
  3687. return Buffer.from(chunk, 'utf-8');
  3688. }
  3689. };
  3690.  
  3691. const _TextDecoder = typeof TextDecoder === 'function' && TextDecoder || class extends require('string_decoder').StringDecoder {
  3692. /**
  3693. * @param {ArrayBuffer} chunk
  3694. * @returns {string}
  3695. */
  3696. decode(chunk) {
  3697. return this.end(Buffer.from(chunk));
  3698. }
  3699. };
  3700.  
  3701. /***
  3702. * The FLV demuxer is from flv.js
  3703. *
  3704. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  3705. *
  3706. * @author zheng qian <xqq@xqq.im>
  3707. *
  3708. * Licensed under the Apache License, Version 2.0 (the "License");
  3709. * you may not use this file except in compliance with the License.
  3710. * You may obtain a copy of the License at
  3711. *
  3712. * http://www.apache.org/licenses/LICENSE-2.0
  3713. *
  3714. * Unless required by applicable law or agreed to in writing, software
  3715. * distributed under the License is distributed on an "AS IS" BASIS,
  3716. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3717. * See the License for the specific language governing permissions and
  3718. * limitations under the License.
  3719. */
  3720.  
  3721. // import FLVDemuxer from 'flv.js/src/demux/flv-demuxer.js';
  3722. // ..import Log from '../utils/logger.js';
  3723. const Log = {
  3724. e: console.error.bind(console),
  3725. w: console.warn.bind(console),
  3726. i: console.log.bind(console),
  3727. v: console.log.bind(console),
  3728. };
  3729.  
  3730. // ..import AMF from './amf-parser.js';
  3731. // ....import Log from '../utils/logger.js';
  3732. // ....import decodeUTF8 from '../utils/utf8-conv.js';
  3733. function checkContinuation(uint8array, start, checkLength) {
  3734. let array = uint8array;
  3735. if (start + checkLength < array.length) {
  3736. while (checkLength--) {
  3737. if ((array[++start] & 0xC0) !== 0x80)
  3738. return false;
  3739. }
  3740. return true;
  3741. } else {
  3742. return false;
  3743. }
  3744. }
  3745.  
  3746. function decodeUTF8(uint8array) {
  3747. let out = [];
  3748. let input = uint8array;
  3749. let i = 0;
  3750. let length = uint8array.length;
  3751.  
  3752. while (i < length) {
  3753. if (input[i] < 0x80) {
  3754. out.push(String.fromCharCode(input[i]));
  3755. ++i;
  3756. continue;
  3757. } else if (input[i] < 0xC0) {
  3758. // fallthrough
  3759. } else if (input[i] < 0xE0) {
  3760. if (checkContinuation(input, i, 1)) {
  3761. let ucs4 = (input[i] & 0x1F) << 6 | (input[i + 1] & 0x3F);
  3762. if (ucs4 >= 0x80) {
  3763. out.push(String.fromCharCode(ucs4 & 0xFFFF));
  3764. i += 2;
  3765. continue;
  3766. }
  3767. }
  3768. } else if (input[i] < 0xF0) {
  3769. if (checkContinuation(input, i, 2)) {
  3770. let ucs4 = (input[i] & 0xF) << 12 | (input[i + 1] & 0x3F) << 6 | input[i + 2] & 0x3F;
  3771. if (ucs4 >= 0x800 && (ucs4 & 0xF800) !== 0xD800) {
  3772. out.push(String.fromCharCode(ucs4 & 0xFFFF));
  3773. i += 3;
  3774. continue;
  3775. }
  3776. }
  3777. } else if (input[i] < 0xF8) {
  3778. if (checkContinuation(input, i, 3)) {
  3779. let ucs4 = (input[i] & 0x7) << 18 | (input[i + 1] & 0x3F) << 12
  3780. | (input[i + 2] & 0x3F) << 6 | (input[i + 3] & 0x3F);
  3781. if (ucs4 > 0x10000 && ucs4 < 0x110000) {
  3782. ucs4 -= 0x10000;
  3783. out.push(String.fromCharCode((ucs4 >>> 10) | 0xD800));
  3784. out.push(String.fromCharCode((ucs4 & 0x3FF) | 0xDC00));
  3785. i += 4;
  3786. continue;
  3787. }
  3788. }
  3789. }
  3790. out.push(String.fromCharCode(0xFFFD));
  3791. ++i;
  3792. }
  3793.  
  3794. return out.join('');
  3795. }
  3796.  
  3797. // ....import {IllegalStateException} from '../utils/exception.js';
  3798. class IllegalStateException extends Error { }
  3799.  
  3800. let le = (function () {
  3801. let buf = new ArrayBuffer(2);
  3802. (new DataView(buf)).setInt16(0, 256, true); // little-endian write
  3803. return (new Int16Array(buf))[0] === 256; // platform-spec read, if equal then LE
  3804. })();
  3805.  
  3806. class AMF {
  3807.  
  3808. static parseScriptData(arrayBuffer, dataOffset, dataSize) {
  3809. let data = {};
  3810.  
  3811. try {
  3812. let name = AMF.parseValue(arrayBuffer, dataOffset, dataSize);
  3813. let value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  3814.  
  3815. data[name.data] = value.data;
  3816. } catch (e) {
  3817. Log.e('AMF', e.toString());
  3818. }
  3819.  
  3820. return data;
  3821. }
  3822.  
  3823. static parseObject(arrayBuffer, dataOffset, dataSize) {
  3824. if (dataSize < 3) {
  3825. throw new IllegalStateException('Data not enough when parse ScriptDataObject');
  3826. }
  3827. let name = AMF.parseString(arrayBuffer, dataOffset, dataSize);
  3828. let value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  3829. let isObjectEnd = value.objectEnd;
  3830.  
  3831. return {
  3832. data: {
  3833. name: name.data,
  3834. value: value.data
  3835. },
  3836. size: name.size + value.size,
  3837. objectEnd: isObjectEnd
  3838. };
  3839. }
  3840.  
  3841. static parseVariable(arrayBuffer, dataOffset, dataSize) {
  3842. return AMF.parseObject(arrayBuffer, dataOffset, dataSize);
  3843. }
  3844.  
  3845. static parseString(arrayBuffer, dataOffset, dataSize) {
  3846. if (dataSize < 2) {
  3847. throw new IllegalStateException('Data not enough when parse String');
  3848. }
  3849. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  3850. let length = v.getUint16(0, !le);
  3851.  
  3852. let str;
  3853. if (length > 0) {
  3854. str = decodeUTF8(new Uint8Array(arrayBuffer, dataOffset + 2, length));
  3855. } else {
  3856. str = '';
  3857. }
  3858.  
  3859. return {
  3860. data: str,
  3861. size: 2 + length
  3862. };
  3863. }
  3864.  
  3865. static parseLongString(arrayBuffer, dataOffset, dataSize) {
  3866. if (dataSize < 4) {
  3867. throw new IllegalStateException('Data not enough when parse LongString');
  3868. }
  3869. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  3870. let length = v.getUint32(0, !le);
  3871.  
  3872. let str;
  3873. if (length > 0) {
  3874. str = decodeUTF8(new Uint8Array(arrayBuffer, dataOffset + 4, length));
  3875. } else {
  3876. str = '';
  3877. }
  3878.  
  3879. return {
  3880. data: str,
  3881. size: 4 + length
  3882. };
  3883. }
  3884.  
  3885. static parseDate(arrayBuffer, dataOffset, dataSize) {
  3886. if (dataSize < 10) {
  3887. throw new IllegalStateException('Data size invalid when parse Date');
  3888. }
  3889. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  3890. let timestamp = v.getFloat64(0, !le);
  3891. let localTimeOffset = v.getInt16(8, !le);
  3892. timestamp += localTimeOffset * 60 * 1000; // get UTC time
  3893.  
  3894. return {
  3895. data: new Date(timestamp),
  3896. size: 8 + 2
  3897. };
  3898. }
  3899.  
  3900. static parseValue(arrayBuffer, dataOffset, dataSize) {
  3901. if (dataSize < 1) {
  3902. throw new IllegalStateException('Data not enough when parse Value');
  3903. }
  3904.  
  3905. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  3906.  
  3907. let offset = 1;
  3908. let type = v.getUint8(0);
  3909. let value;
  3910. let objectEnd = false;
  3911.  
  3912. try {
  3913. switch (type) {
  3914. case 0: // Number(Double) type
  3915. value = v.getFloat64(1, !le);
  3916. offset += 8;
  3917. break;
  3918. case 1: { // Boolean type
  3919. let b = v.getUint8(1);
  3920. value = b ? true : false;
  3921. offset += 1;
  3922. break;
  3923. }
  3924. case 2: { // String type
  3925. let amfstr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  3926. value = amfstr.data;
  3927. offset += amfstr.size;
  3928. break;
  3929. }
  3930. case 3: { // Object(s) type
  3931. value = {};
  3932. let terminal = 0; // workaround for malformed Objects which has missing ScriptDataObjectEnd
  3933. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  3934. terminal = 3;
  3935. }
  3936. while (offset < dataSize - 4) { // 4 === type(UI8) + ScriptDataObjectEnd(UI24)
  3937. let amfobj = AMF.parseObject(arrayBuffer, dataOffset + offset, dataSize - offset - terminal);
  3938. if (amfobj.objectEnd)
  3939. break;
  3940. value[amfobj.data.name] = amfobj.data.value;
  3941. offset += amfobj.size;
  3942. }
  3943. if (offset <= dataSize - 3) {
  3944. let marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  3945. if (marker === 9) {
  3946. offset += 3;
  3947. }
  3948. }
  3949. break;
  3950. }
  3951. case 8: { // ECMA array type (Mixed array)
  3952. value = {};
  3953. offset += 4; // ECMAArrayLength(UI32)
  3954. let terminal = 0; // workaround for malformed MixedArrays which has missing ScriptDataObjectEnd
  3955. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  3956. terminal = 3;
  3957. }
  3958. while (offset < dataSize - 8) { // 8 === type(UI8) + ECMAArrayLength(UI32) + ScriptDataVariableEnd(UI24)
  3959. let amfvar = AMF.parseVariable(arrayBuffer, dataOffset + offset, dataSize - offset - terminal);
  3960. if (amfvar.objectEnd)
  3961. break;
  3962. value[amfvar.data.name] = amfvar.data.value;
  3963. offset += amfvar.size;
  3964. }
  3965. if (offset <= dataSize - 3) {
  3966. let marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  3967. if (marker === 9) {
  3968. offset += 3;
  3969. }
  3970. }
  3971. break;
  3972. }
  3973. case 9: // ScriptDataObjectEnd
  3974. value = undefined;
  3975. offset = 1;
  3976. objectEnd = true;
  3977. break;
  3978. case 10: { // Strict array type
  3979. // ScriptDataValue[n]. NOTE: according to video_file_format_spec_v10_1.pdf
  3980. value = [];
  3981. let strictArrayLength = v.getUint32(1, !le);
  3982. offset += 4;
  3983. for (let i = 0; i < strictArrayLength; i++) {
  3984. let val = AMF.parseValue(arrayBuffer, dataOffset + offset, dataSize - offset);
  3985. value.push(val.data);
  3986. offset += val.size;
  3987. }
  3988. break;
  3989. }
  3990. case 11: { // Date type
  3991. let date = AMF.parseDate(arrayBuffer, dataOffset + 1, dataSize - 1);
  3992. value = date.data;
  3993. offset += date.size;
  3994. break;
  3995. }
  3996. case 12: { // Long string type
  3997. let amfLongStr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  3998. value = amfLongStr.data;
  3999. offset += amfLongStr.size;
  4000. break;
  4001. }
  4002. default:
  4003. // ignore and skip
  4004. offset = dataSize;
  4005. Log.w('AMF', 'Unsupported AMF value type ' + type);
  4006. }
  4007. } catch (e) {
  4008. Log.e('AMF', e.toString());
  4009. }
  4010.  
  4011. return {
  4012. data: value,
  4013. size: offset,
  4014. objectEnd: objectEnd
  4015. };
  4016. }
  4017.  
  4018. }
  4019.  
  4020. // ..import SPSParser from './sps-parser.js';
  4021. // ....import ExpGolomb from './exp-golomb.js';
  4022. // ......import {IllegalStateException, InvalidArgumentException} from '../utils/exception.js';
  4023. class InvalidArgumentException extends Error { }
  4024.  
  4025. class ExpGolomb {
  4026.  
  4027. constructor(uint8array) {
  4028. this.TAG = 'ExpGolomb';
  4029.  
  4030. this._buffer = uint8array;
  4031. this._buffer_index = 0;
  4032. this._total_bytes = uint8array.byteLength;
  4033. this._total_bits = uint8array.byteLength * 8;
  4034. this._current_word = 0;
  4035. this._current_word_bits_left = 0;
  4036. }
  4037.  
  4038. destroy() {
  4039. this._buffer = null;
  4040. }
  4041.  
  4042. _fillCurrentWord() {
  4043. let buffer_bytes_left = this._total_bytes - this._buffer_index;
  4044. if (buffer_bytes_left <= 0)
  4045. throw new IllegalStateException('ExpGolomb: _fillCurrentWord() but no bytes available');
  4046.  
  4047. let bytes_read = Math.min(4, buffer_bytes_left);
  4048. let word = new Uint8Array(4);
  4049. word.set(this._buffer.subarray(this._buffer_index, this._buffer_index + bytes_read));
  4050. this._current_word = new DataView(word.buffer).getUint32(0, false);
  4051.  
  4052. this._buffer_index += bytes_read;
  4053. this._current_word_bits_left = bytes_read * 8;
  4054. }
  4055.  
  4056. readBits(bits) {
  4057. if (bits > 32)
  4058. throw new InvalidArgumentException('ExpGolomb: readBits() bits exceeded max 32bits!');
  4059.  
  4060. if (bits <= this._current_word_bits_left) {
  4061. let result = this._current_word >>> (32 - bits);
  4062. this._current_word <<= bits;
  4063. this._current_word_bits_left -= bits;
  4064. return result;
  4065. }
  4066.  
  4067. let result = this._current_word_bits_left ? this._current_word : 0;
  4068. result = result >>> (32 - this._current_word_bits_left);
  4069. let bits_need_left = bits - this._current_word_bits_left;
  4070.  
  4071. this._fillCurrentWord();
  4072. let bits_read_next = Math.min(bits_need_left, this._current_word_bits_left);
  4073.  
  4074. let result2 = this._current_word >>> (32 - bits_read_next);
  4075. this._current_word <<= bits_read_next;
  4076. this._current_word_bits_left -= bits_read_next;
  4077.  
  4078. result = (result << bits_read_next) | result2;
  4079. return result;
  4080. }
  4081.  
  4082. readBool() {
  4083. return this.readBits(1) === 1;
  4084. }
  4085.  
  4086. readByte() {
  4087. return this.readBits(8);
  4088. }
  4089.  
  4090. _skipLeadingZero() {
  4091. let zero_count;
  4092. for (zero_count = 0; zero_count < this._current_word_bits_left; zero_count++) {
  4093. if (0 !== (this._current_word & (0x80000000 >>> zero_count))) {
  4094. this._current_word <<= zero_count;
  4095. this._current_word_bits_left -= zero_count;
  4096. return zero_count;
  4097. }
  4098. }
  4099. this._fillCurrentWord();
  4100. return zero_count + this._skipLeadingZero();
  4101. }
  4102.  
  4103. readUEG() { // unsigned exponential golomb
  4104. let leading_zeros = this._skipLeadingZero();
  4105. return this.readBits(leading_zeros + 1) - 1;
  4106. }
  4107.  
  4108. readSEG() { // signed exponential golomb
  4109. let value = this.readUEG();
  4110. if (value & 0x01) {
  4111. return (value + 1) >>> 1;
  4112. } else {
  4113. return -1 * (value >>> 1);
  4114. }
  4115. }
  4116.  
  4117. }
  4118.  
  4119. class SPSParser {
  4120.  
  4121. static _ebsp2rbsp(uint8array) {
  4122. let src = uint8array;
  4123. let src_length = src.byteLength;
  4124. let dst = new Uint8Array(src_length);
  4125. let dst_idx = 0;
  4126.  
  4127. for (let i = 0; i < src_length; i++) {
  4128. if (i >= 2) {
  4129. // Unescape: Skip 0x03 after 00 00
  4130. if (src[i] === 0x03 && src[i - 1] === 0x00 && src[i - 2] === 0x00) {
  4131. continue;
  4132. }
  4133. }
  4134. dst[dst_idx] = src[i];
  4135. dst_idx++;
  4136. }
  4137.  
  4138. return new Uint8Array(dst.buffer, 0, dst_idx);
  4139. }
  4140.  
  4141. static parseSPS(uint8array) {
  4142. let rbsp = SPSParser._ebsp2rbsp(uint8array);
  4143. let gb = new ExpGolomb(rbsp);
  4144.  
  4145. gb.readByte();
  4146. let profile_idc = gb.readByte(); // profile_idc
  4147. gb.readByte(); // constraint_set_flags[5] + reserved_zero[3]
  4148. let level_idc = gb.readByte(); // level_idc
  4149. gb.readUEG(); // seq_parameter_set_id
  4150.  
  4151. let profile_string = SPSParser.getProfileString(profile_idc);
  4152. let level_string = SPSParser.getLevelString(level_idc);
  4153. let chroma_format_idc = 1;
  4154. let chroma_format = 420;
  4155. let chroma_format_table = [0, 420, 422, 444];
  4156. let bit_depth = 8;
  4157.  
  4158. if (profile_idc === 100 || profile_idc === 110 || profile_idc === 122 ||
  4159. profile_idc === 244 || profile_idc === 44 || profile_idc === 83 ||
  4160. profile_idc === 86 || profile_idc === 118 || profile_idc === 128 ||
  4161. profile_idc === 138 || profile_idc === 144) {
  4162.  
  4163. chroma_format_idc = gb.readUEG();
  4164. if (chroma_format_idc === 3) {
  4165. gb.readBits(1); // separate_colour_plane_flag
  4166. }
  4167. if (chroma_format_idc <= 3) {
  4168. chroma_format = chroma_format_table[chroma_format_idc];
  4169. }
  4170.  
  4171. bit_depth = gb.readUEG() + 8; // bit_depth_luma_minus8
  4172. gb.readUEG(); // bit_depth_chroma_minus8
  4173. gb.readBits(1); // qpprime_y_zero_transform_bypass_flag
  4174. if (gb.readBool()) { // seq_scaling_matrix_present_flag
  4175. let scaling_list_count = (chroma_format_idc !== 3) ? 8 : 12;
  4176. for (let i = 0; i < scaling_list_count; i++) {
  4177. if (gb.readBool()) { // seq_scaling_list_present_flag
  4178. if (i < 6) {
  4179. SPSParser._skipScalingList(gb, 16);
  4180. } else {
  4181. SPSParser._skipScalingList(gb, 64);
  4182. }
  4183. }
  4184. }
  4185. }
  4186. }
  4187. gb.readUEG(); // log2_max_frame_num_minus4
  4188. let pic_order_cnt_type = gb.readUEG();
  4189. if (pic_order_cnt_type === 0) {
  4190. gb.readUEG(); // log2_max_pic_order_cnt_lsb_minus_4
  4191. } else if (pic_order_cnt_type === 1) {
  4192. gb.readBits(1); // delta_pic_order_always_zero_flag
  4193. gb.readSEG(); // offset_for_non_ref_pic
  4194. gb.readSEG(); // offset_for_top_to_bottom_field
  4195. let num_ref_frames_in_pic_order_cnt_cycle = gb.readUEG();
  4196. for (let i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++) {
  4197. gb.readSEG(); // offset_for_ref_frame
  4198. }
  4199. }
  4200. gb.readUEG(); // max_num_ref_frames
  4201. gb.readBits(1); // gaps_in_frame_num_value_allowed_flag
  4202.  
  4203. let pic_width_in_mbs_minus1 = gb.readUEG();
  4204. let pic_height_in_map_units_minus1 = gb.readUEG();
  4205.  
  4206. let frame_mbs_only_flag = gb.readBits(1);
  4207. if (frame_mbs_only_flag === 0) {
  4208. gb.readBits(1); // mb_adaptive_frame_field_flag
  4209. }
  4210. gb.readBits(1); // direct_8x8_inference_flag
  4211.  
  4212. let frame_crop_left_offset = 0;
  4213. let frame_crop_right_offset = 0;
  4214. let frame_crop_top_offset = 0;
  4215. let frame_crop_bottom_offset = 0;
  4216.  
  4217. let frame_cropping_flag = gb.readBool();
  4218. if (frame_cropping_flag) {
  4219. frame_crop_left_offset = gb.readUEG();
  4220. frame_crop_right_offset = gb.readUEG();
  4221. frame_crop_top_offset = gb.readUEG();
  4222. frame_crop_bottom_offset = gb.readUEG();
  4223. }
  4224.  
  4225. let sar_width = 1, sar_height = 1;
  4226. let fps = 0, fps_fixed = true, fps_num = 0, fps_den = 0;
  4227.  
  4228. let vui_parameters_present_flag = gb.readBool();
  4229. if (vui_parameters_present_flag) {
  4230. if (gb.readBool()) { // aspect_ratio_info_present_flag
  4231. let aspect_ratio_idc = gb.readByte();
  4232. let sar_w_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  4233. let sar_h_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  4234.  
  4235. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  4236. sar_width = sar_w_table[aspect_ratio_idc - 1];
  4237. sar_height = sar_h_table[aspect_ratio_idc - 1];
  4238. } else if (aspect_ratio_idc === 255) {
  4239. sar_width = gb.readByte() << 8 | gb.readByte();
  4240. sar_height = gb.readByte() << 8 | gb.readByte();
  4241. }
  4242. }
  4243.  
  4244. if (gb.readBool()) { // overscan_info_present_flag
  4245. gb.readBool(); // overscan_appropriate_flag
  4246. }
  4247. if (gb.readBool()) { // video_signal_type_present_flag
  4248. gb.readBits(4); // video_format & video_full_range_flag
  4249. if (gb.readBool()) { // colour_description_present_flag
  4250. gb.readBits(24); // colour_primaries & transfer_characteristics & matrix_coefficients
  4251. }
  4252. }
  4253. if (gb.readBool()) { // chroma_loc_info_present_flag
  4254. gb.readUEG(); // chroma_sample_loc_type_top_field
  4255. gb.readUEG(); // chroma_sample_loc_type_bottom_field
  4256. }
  4257. if (gb.readBool()) { // timing_info_present_flag
  4258. let num_units_in_tick = gb.readBits(32);
  4259. let time_scale = gb.readBits(32);
  4260. fps_fixed = gb.readBool(); // fixed_frame_rate_flag
  4261.  
  4262. fps_num = time_scale;
  4263. fps_den = num_units_in_tick * 2;
  4264. fps = fps_num / fps_den;
  4265. }
  4266. }
  4267.  
  4268. let sarScale = 1;
  4269. if (sar_width !== 1 || sar_height !== 1) {
  4270. sarScale = sar_width / sar_height;
  4271. }
  4272.  
  4273. let crop_unit_x = 0, crop_unit_y = 0;
  4274. if (chroma_format_idc === 0) {
  4275. crop_unit_x = 1;
  4276. crop_unit_y = 2 - frame_mbs_only_flag;
  4277. } else {
  4278. let sub_wc = (chroma_format_idc === 3) ? 1 : 2;
  4279. let sub_hc = (chroma_format_idc === 1) ? 2 : 1;
  4280. crop_unit_x = sub_wc;
  4281. crop_unit_y = sub_hc * (2 - frame_mbs_only_flag);
  4282. }
  4283.  
  4284. let codec_width = (pic_width_in_mbs_minus1 + 1) * 16;
  4285. let codec_height = (2 - frame_mbs_only_flag) * ((pic_height_in_map_units_minus1 + 1) * 16);
  4286.  
  4287. codec_width -= (frame_crop_left_offset + frame_crop_right_offset) * crop_unit_x;
  4288. codec_height -= (frame_crop_top_offset + frame_crop_bottom_offset) * crop_unit_y;
  4289.  
  4290. let present_width = Math.ceil(codec_width * sarScale);
  4291.  
  4292. gb.destroy();
  4293. gb = null;
  4294.  
  4295. return {
  4296. profile_string: profile_string, // baseline, high, high10, ...
  4297. level_string: level_string, // 3, 3.1, 4, 4.1, 5, 5.1, ...
  4298. bit_depth: bit_depth, // 8bit, 10bit, ...
  4299. chroma_format: chroma_format, // 4:2:0, 4:2:2, ...
  4300. chroma_format_string: SPSParser.getChromaFormatString(chroma_format),
  4301.  
  4302. frame_rate: {
  4303. fixed: fps_fixed,
  4304. fps: fps,
  4305. fps_den: fps_den,
  4306. fps_num: fps_num
  4307. },
  4308.  
  4309. sar_ratio: {
  4310. width: sar_width,
  4311. height: sar_height
  4312. },
  4313.  
  4314. codec_size: {
  4315. width: codec_width,
  4316. height: codec_height
  4317. },
  4318.  
  4319. present_size: {
  4320. width: present_width,
  4321. height: codec_height
  4322. }
  4323. };
  4324. }
  4325.  
  4326. static _skipScalingList(gb, count) {
  4327. let last_scale = 8, next_scale = 8;
  4328. let delta_scale = 0;
  4329. for (let i = 0; i < count; i++) {
  4330. if (next_scale !== 0) {
  4331. delta_scale = gb.readSEG();
  4332. next_scale = (last_scale + delta_scale + 256) % 256;
  4333. }
  4334. last_scale = (next_scale === 0) ? last_scale : next_scale;
  4335. }
  4336. }
  4337.  
  4338. static getProfileString(profile_idc) {
  4339. switch (profile_idc) {
  4340. case 66:
  4341. return 'Baseline';
  4342. case 77:
  4343. return 'Main';
  4344. case 88:
  4345. return 'Extended';
  4346. case 100:
  4347. return 'High';
  4348. case 110:
  4349. return 'High10';
  4350. case 122:
  4351. return 'High422';
  4352. case 244:
  4353. return 'High444';
  4354. default:
  4355. return 'Unknown';
  4356. }
  4357. }
  4358.  
  4359. static getLevelString(level_idc) {
  4360. return (level_idc / 10).toFixed(1);
  4361. }
  4362.  
  4363. static getChromaFormatString(chroma) {
  4364. switch (chroma) {
  4365. case 420:
  4366. return '4:2:0';
  4367. case 422:
  4368. return '4:2:2';
  4369. case 444:
  4370. return '4:4:4';
  4371. default:
  4372. return 'Unknown';
  4373. }
  4374. }
  4375.  
  4376. }
  4377.  
  4378. // ..import DemuxErrors from './demux-errors.js';
  4379. const DemuxErrors = {
  4380. OK: 'OK',
  4381. FORMAT_ERROR: 'FormatError',
  4382. FORMAT_UNSUPPORTED: 'FormatUnsupported',
  4383. CODEC_UNSUPPORTED: 'CodecUnsupported'
  4384. };
  4385.  
  4386. // ..import MediaInfo from '../core/media-info.js';
  4387. class MediaInfo {
  4388.  
  4389. constructor() {
  4390. this.mimeType = null;
  4391. this.duration = null;
  4392.  
  4393. this.hasAudio = null;
  4394. this.hasVideo = null;
  4395. this.audioCodec = null;
  4396. this.videoCodec = null;
  4397. this.audioDataRate = null;
  4398. this.videoDataRate = null;
  4399.  
  4400. this.audioSampleRate = null;
  4401. this.audioChannelCount = null;
  4402.  
  4403. this.width = null;
  4404. this.height = null;
  4405. this.fps = null;
  4406. this.profile = null;
  4407. this.level = null;
  4408. this.chromaFormat = null;
  4409. this.sarNum = null;
  4410. this.sarDen = null;
  4411.  
  4412. this.metadata = null;
  4413. this.segments = null; // MediaInfo[]
  4414. this.segmentCount = null;
  4415. this.hasKeyframesIndex = null;
  4416. this.keyframesIndex = null;
  4417. }
  4418.  
  4419. isComplete() {
  4420. let audioInfoComplete = (this.hasAudio === false) ||
  4421. (this.hasAudio === true &&
  4422. this.audioCodec != null &&
  4423. this.audioSampleRate != null &&
  4424. this.audioChannelCount != null);
  4425.  
  4426. let videoInfoComplete = (this.hasVideo === false) ||
  4427. (this.hasVideo === true &&
  4428. this.videoCodec != null &&
  4429. this.width != null &&
  4430. this.height != null &&
  4431. this.fps != null &&
  4432. this.profile != null &&
  4433. this.level != null &&
  4434. this.chromaFormat != null &&
  4435. this.sarNum != null &&
  4436. this.sarDen != null);
  4437.  
  4438. // keyframesIndex may not be present
  4439. return this.mimeType != null &&
  4440. this.duration != null &&
  4441. this.metadata != null &&
  4442. this.hasKeyframesIndex != null &&
  4443. audioInfoComplete &&
  4444. videoInfoComplete;
  4445. }
  4446.  
  4447. isSeekable() {
  4448. return this.hasKeyframesIndex === true;
  4449. }
  4450.  
  4451. getNearestKeyframe(milliseconds) {
  4452. if (this.keyframesIndex == null) {
  4453. return null;
  4454. }
  4455.  
  4456. let table = this.keyframesIndex;
  4457. let keyframeIdx = this._search(table.times, milliseconds);
  4458.  
  4459. return {
  4460. index: keyframeIdx,
  4461. milliseconds: table.times[keyframeIdx],
  4462. fileposition: table.filepositions[keyframeIdx]
  4463. };
  4464. }
  4465.  
  4466. _search(list, value) {
  4467. let idx = 0;
  4468.  
  4469. let last = list.length - 1;
  4470. let mid = 0;
  4471. let lbound = 0;
  4472. let ubound = last;
  4473.  
  4474. if (value < list[0]) {
  4475. idx = 0;
  4476. lbound = ubound + 1; // skip search
  4477. }
  4478.  
  4479. while (lbound <= ubound) {
  4480. mid = lbound + Math.floor((ubound - lbound) / 2);
  4481. if (mid === last || (value >= list[mid] && value < list[mid + 1])) {
  4482. idx = mid;
  4483. break;
  4484. } else if (list[mid] < value) {
  4485. lbound = mid + 1;
  4486. } else {
  4487. ubound = mid - 1;
  4488. }
  4489. }
  4490.  
  4491. return idx;
  4492. }
  4493.  
  4494. }
  4495.  
  4496. function ReadBig32(array, index) {
  4497. return ((array[index] << 24) |
  4498. (array[index + 1] << 16) |
  4499. (array[index + 2] << 8) |
  4500. (array[index + 3]));
  4501. }
  4502.  
  4503. class FLVDemuxer {
  4504.  
  4505. /**
  4506. * Create a new FLV demuxer
  4507. * @param {Object} probeData
  4508. * @param {boolean} probeData.match
  4509. * @param {number} probeData.consumed
  4510. * @param {number} probeData.dataOffset
  4511. * @param {booleam} probeData.hasAudioTrack
  4512. * @param {boolean} probeData.hasVideoTrack
  4513. * @param {*} config
  4514. */
  4515. constructor(probeData, config) {
  4516. this.TAG = 'FLVDemuxer';
  4517.  
  4518. this._config = config;
  4519.  
  4520. this._onError = null;
  4521. this._onMediaInfo = null;
  4522. this._onTrackMetadata = null;
  4523. this._onDataAvailable = null;
  4524.  
  4525. this._dataOffset = probeData.dataOffset;
  4526. this._firstParse = true;
  4527. this._dispatch = false;
  4528.  
  4529. this._hasAudio = probeData.hasAudioTrack;
  4530. this._hasVideo = probeData.hasVideoTrack;
  4531.  
  4532. this._hasAudioFlagOverrided = false;
  4533. this._hasVideoFlagOverrided = false;
  4534.  
  4535. this._audioInitialMetadataDispatched = false;
  4536. this._videoInitialMetadataDispatched = false;
  4537.  
  4538. this._mediaInfo = new MediaInfo();
  4539. this._mediaInfo.hasAudio = this._hasAudio;
  4540. this._mediaInfo.hasVideo = this._hasVideo;
  4541. this._metadata = null;
  4542. this._audioMetadata = null;
  4543. this._videoMetadata = null;
  4544.  
  4545. this._naluLengthSize = 4;
  4546. this._timestampBase = 0; // int32, in milliseconds
  4547. this._timescale = 1000;
  4548. this._duration = 0; // int32, in milliseconds
  4549. this._durationOverrided = false;
  4550. this._referenceFrameRate = {
  4551. fixed: true,
  4552. fps: 23.976,
  4553. fps_num: 23976,
  4554. fps_den: 1000
  4555. };
  4556.  
  4557. this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48000];
  4558.  
  4559. this._mpegSamplingRates = [
  4560. 96000, 88200, 64000, 48000, 44100, 32000,
  4561. 24000, 22050, 16000, 12000, 11025, 8000, 7350
  4562. ];
  4563.  
  4564. this._mpegAudioV10SampleRateTable = [44100, 48000, 32000, 0];
  4565. this._mpegAudioV20SampleRateTable = [22050, 24000, 16000, 0];
  4566. this._mpegAudioV25SampleRateTable = [11025, 12000, 8000, 0];
  4567.  
  4568. this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1];
  4569. this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1];
  4570. this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1];
  4571.  
  4572. this._videoTrack = { type: 'video', id: 1, sequenceNumber: 0, samples: [], length: 0 };
  4573. this._audioTrack = { type: 'audio', id: 2, sequenceNumber: 0, samples: [], length: 0 };
  4574.  
  4575. this._littleEndian = (function () {
  4576. let buf = new ArrayBuffer(2);
  4577. (new DataView(buf)).setInt16(0, 256, true); // little-endian write
  4578. return (new Int16Array(buf))[0] === 256; // platform-spec read, if equal then LE
  4579. })();
  4580. }
  4581.  
  4582. destroy() {
  4583. this._mediaInfo = null;
  4584. this._metadata = null;
  4585. this._audioMetadata = null;
  4586. this._videoMetadata = null;
  4587. this._videoTrack = null;
  4588. this._audioTrack = null;
  4589.  
  4590. this._onError = null;
  4591. this._onMediaInfo = null;
  4592. this._onTrackMetadata = null;
  4593. this._onDataAvailable = null;
  4594. }
  4595.  
  4596. /**
  4597. * Probe the flv data
  4598. * @param {ArrayBuffer} buffer
  4599. * @returns {Object} - probeData to be feed into constructor
  4600. */
  4601. static probe(buffer) {
  4602. let data = new Uint8Array(buffer);
  4603. let mismatch = { match: false };
  4604.  
  4605. if (data[0] !== 0x46 || data[1] !== 0x4C || data[2] !== 0x56 || data[3] !== 0x01) {
  4606. return mismatch;
  4607. }
  4608.  
  4609. let hasAudio = ((data[4] & 4) >>> 2) !== 0;
  4610. let hasVideo = (data[4] & 1) !== 0;
  4611.  
  4612. let offset = ReadBig32(data, 5);
  4613.  
  4614. if (offset < 9) {
  4615. return mismatch;
  4616. }
  4617.  
  4618. return {
  4619. match: true,
  4620. consumed: offset,
  4621. dataOffset: offset,
  4622. hasAudioTrack: hasAudio,
  4623. hasVideoTrack: hasVideo
  4624. };
  4625. }
  4626.  
  4627. bindDataSource(loader) {
  4628. loader.onDataArrival = this.parseChunks.bind(this);
  4629. return this;
  4630. }
  4631.  
  4632. // prototype: function(type: string, metadata: any): void
  4633. get onTrackMetadata() {
  4634. return this._onTrackMetadata;
  4635. }
  4636.  
  4637. set onTrackMetadata(callback) {
  4638. this._onTrackMetadata = callback;
  4639. }
  4640.  
  4641. // prototype: function(mediaInfo: MediaInfo): void
  4642. get onMediaInfo() {
  4643. return this._onMediaInfo;
  4644. }
  4645.  
  4646. set onMediaInfo(callback) {
  4647. this._onMediaInfo = callback;
  4648. }
  4649.  
  4650. // prototype: function(type: number, info: string): void
  4651. get onError() {
  4652. return this._onError;
  4653. }
  4654.  
  4655. set onError(callback) {
  4656. this._onError = callback;
  4657. }
  4658.  
  4659. // prototype: function(videoTrack: any, audioTrack: any): void
  4660. get onDataAvailable() {
  4661. return this._onDataAvailable;
  4662. }
  4663.  
  4664. set onDataAvailable(callback) {
  4665. this._onDataAvailable = callback;
  4666. }
  4667.  
  4668. // timestamp base for output samples, must be in milliseconds
  4669. get timestampBase() {
  4670. return this._timestampBase;
  4671. }
  4672.  
  4673. set timestampBase(base) {
  4674. this._timestampBase = base;
  4675. }
  4676.  
  4677. get overridedDuration() {
  4678. return this._duration;
  4679. }
  4680.  
  4681. // Force-override media duration. Must be in milliseconds, int32
  4682. set overridedDuration(duration) {
  4683. this._durationOverrided = true;
  4684. this._duration = duration;
  4685. this._mediaInfo.duration = duration;
  4686. }
  4687.  
  4688. // Force-override audio track present flag, boolean
  4689. set overridedHasAudio(hasAudio) {
  4690. this._hasAudioFlagOverrided = true;
  4691. this._hasAudio = hasAudio;
  4692. this._mediaInfo.hasAudio = hasAudio;
  4693. }
  4694.  
  4695. // Force-override video track present flag, boolean
  4696. set overridedHasVideo(hasVideo) {
  4697. this._hasVideoFlagOverrided = true;
  4698. this._hasVideo = hasVideo;
  4699. this._mediaInfo.hasVideo = hasVideo;
  4700. }
  4701.  
  4702. resetMediaInfo() {
  4703. this._mediaInfo = new MediaInfo();
  4704. }
  4705.  
  4706. _isInitialMetadataDispatched() {
  4707. if (this._hasAudio && this._hasVideo) { // both audio & video
  4708. return this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched;
  4709. }
  4710. if (this._hasAudio && !this._hasVideo) { // audio only
  4711. return this._audioInitialMetadataDispatched;
  4712. }
  4713. if (!this._hasAudio && this._hasVideo) { // video only
  4714. return this._videoInitialMetadataDispatched;
  4715. }
  4716. return false;
  4717. }
  4718.  
  4719. // function parseChunks(chunk: ArrayBuffer, byteStart: number): number;
  4720. parseChunks(chunk, byteStart) {
  4721. if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) {
  4722. throw new IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');
  4723. }
  4724.  
  4725. // qli5: fix nonzero byteStart
  4726. let offset = byteStart || 0;
  4727. let le = this._littleEndian;
  4728.  
  4729. if (byteStart === 0) { // buffer with FLV header
  4730. if (chunk.byteLength > 13) {
  4731. let probeData = FLVDemuxer.probe(chunk);
  4732. offset = probeData.dataOffset;
  4733. } else {
  4734. return 0;
  4735. }
  4736. }
  4737.  
  4738. if (this._firstParse) { // handle PreviousTagSize0 before Tag1
  4739. this._firstParse = false;
  4740. if (offset !== this._dataOffset) {
  4741. Log.w(this.TAG, 'First time parsing but chunk byteStart invalid!');
  4742. }
  4743.  
  4744. let v = new DataView(chunk, offset);
  4745. let prevTagSize0 = v.getUint32(0, !le);
  4746. if (prevTagSize0 !== 0) {
  4747. Log.w(this.TAG, 'PrevTagSize0 !== 0 !!!');
  4748. }
  4749. offset += 4;
  4750. }
  4751.  
  4752. while (offset < chunk.byteLength) {
  4753. this._dispatch = true;
  4754.  
  4755. let v = new DataView(chunk, offset);
  4756.  
  4757. if (offset + 11 + 4 > chunk.byteLength) {
  4758. // data not enough for parsing an flv tag
  4759. break;
  4760. }
  4761.  
  4762. let tagType = v.getUint8(0);
  4763. let dataSize = v.getUint32(0, !le) & 0x00FFFFFF;
  4764.  
  4765. if (offset + 11 + dataSize + 4 > chunk.byteLength) {
  4766. // data not enough for parsing actual data body
  4767. break;
  4768. }
  4769.  
  4770. if (tagType !== 8 && tagType !== 9 && tagType !== 18) {
  4771. Log.w(this.TAG, \`Unsupported tag type \${tagType}, skipped\`);
  4772. // consume the whole tag (skip it)
  4773. offset += 11 + dataSize + 4;
  4774. continue;
  4775. }
  4776.  
  4777. let ts2 = v.getUint8(4);
  4778. let ts1 = v.getUint8(5);
  4779. let ts0 = v.getUint8(6);
  4780. let ts3 = v.getUint8(7);
  4781.  
  4782. let timestamp = ts0 | (ts1 << 8) | (ts2 << 16) | (ts3 << 24);
  4783.  
  4784. let streamId = v.getUint32(7, !le) & 0x00FFFFFF;
  4785. if (streamId !== 0) {
  4786. Log.w(this.TAG, 'Meet tag which has StreamID != 0!');
  4787. }
  4788.  
  4789. let dataOffset = offset + 11;
  4790.  
  4791. switch (tagType) {
  4792. case 8: // Audio
  4793. this._parseAudioData(chunk, dataOffset, dataSize, timestamp);
  4794. break;
  4795. case 9: // Video
  4796. this._parseVideoData(chunk, dataOffset, dataSize, timestamp, byteStart + offset);
  4797. break;
  4798. case 18: // ScriptDataObject
  4799. this._parseScriptData(chunk, dataOffset, dataSize);
  4800. break;
  4801. }
  4802.  
  4803. let prevTagSize = v.getUint32(11 + dataSize, !le);
  4804. if (prevTagSize !== 11 + dataSize) {
  4805. Log.w(this.TAG, \`Invalid PrevTagSize \${prevTagSize}\`);
  4806. }
  4807.  
  4808. offset += 11 + dataSize + 4; // tagBody + dataSize + prevTagSize
  4809. }
  4810.  
  4811. // dispatch parsed frames to consumer (typically, the remuxer)
  4812. if (this._isInitialMetadataDispatched()) {
  4813. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4814. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4815. }
  4816. }
  4817.  
  4818. return offset; // consumed bytes, just equals latest offset index
  4819. }
  4820.  
  4821. _parseScriptData(arrayBuffer, dataOffset, dataSize) {
  4822. let scriptData = AMF.parseScriptData(arrayBuffer, dataOffset, dataSize);
  4823.  
  4824. if (scriptData.hasOwnProperty('onMetaData')) {
  4825. if (scriptData.onMetaData == null || typeof scriptData.onMetaData !== 'object') {
  4826. Log.w(this.TAG, 'Invalid onMetaData structure!');
  4827. return;
  4828. }
  4829. if (this._metadata) {
  4830. Log.w(this.TAG, 'Found another onMetaData tag!');
  4831. }
  4832. this._metadata = scriptData;
  4833. let onMetaData = this._metadata.onMetaData;
  4834.  
  4835. if (typeof onMetaData.hasAudio === 'boolean') { // hasAudio
  4836. if (this._hasAudioFlagOverrided === false) {
  4837. this._hasAudio = onMetaData.hasAudio;
  4838. this._mediaInfo.hasAudio = this._hasAudio;
  4839. }
  4840. }
  4841. if (typeof onMetaData.hasVideo === 'boolean') { // hasVideo
  4842. if (this._hasVideoFlagOverrided === false) {
  4843. this._hasVideo = onMetaData.hasVideo;
  4844. this._mediaInfo.hasVideo = this._hasVideo;
  4845. }
  4846. }
  4847. if (typeof onMetaData.audiodatarate === 'number') { // audiodatarate
  4848. this._mediaInfo.audioDataRate = onMetaData.audiodatarate;
  4849. }
  4850. if (typeof onMetaData.videodatarate === 'number') { // videodatarate
  4851. this._mediaInfo.videoDataRate = onMetaData.videodatarate;
  4852. }
  4853. if (typeof onMetaData.width === 'number') { // width
  4854. this._mediaInfo.width = onMetaData.width;
  4855. }
  4856. if (typeof onMetaData.height === 'number') { // height
  4857. this._mediaInfo.height = onMetaData.height;
  4858. }
  4859. if (typeof onMetaData.duration === 'number') { // duration
  4860. if (!this._durationOverrided) {
  4861. let duration = Math.floor(onMetaData.duration * this._timescale);
  4862. this._duration = duration;
  4863. this._mediaInfo.duration = duration;
  4864. }
  4865. } else {
  4866. this._mediaInfo.duration = 0;
  4867. }
  4868. if (typeof onMetaData.framerate === 'number') { // framerate
  4869. let fps_num = Math.floor(onMetaData.framerate * 1000);
  4870. if (fps_num > 0) {
  4871. let fps = fps_num / 1000;
  4872. this._referenceFrameRate.fixed = true;
  4873. this._referenceFrameRate.fps = fps;
  4874. this._referenceFrameRate.fps_num = fps_num;
  4875. this._referenceFrameRate.fps_den = 1000;
  4876. this._mediaInfo.fps = fps;
  4877. }
  4878. }
  4879. if (typeof onMetaData.keyframes === 'object') { // keyframes
  4880. this._mediaInfo.hasKeyframesIndex = true;
  4881. let keyframes = onMetaData.keyframes;
  4882. this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(keyframes);
  4883. onMetaData.keyframes = null; // keyframes has been extracted, remove it
  4884. } else {
  4885. this._mediaInfo.hasKeyframesIndex = false;
  4886. }
  4887. this._dispatch = false;
  4888. this._mediaInfo.metadata = onMetaData;
  4889. Log.v(this.TAG, 'Parsed onMetaData');
  4890. if (this._mediaInfo.isComplete()) {
  4891. this._onMediaInfo(this._mediaInfo);
  4892. }
  4893. }
  4894. }
  4895.  
  4896. _parseKeyframesIndex(keyframes) {
  4897. let times = [];
  4898. let filepositions = [];
  4899.  
  4900. // ignore first keyframe which is actually AVC Sequence Header (AVCDecoderConfigurationRecord)
  4901. for (let i = 1; i < keyframes.times.length; i++) {
  4902. let time = this._timestampBase + Math.floor(keyframes.times[i] * 1000);
  4903. times.push(time);
  4904. filepositions.push(keyframes.filepositions[i]);
  4905. }
  4906.  
  4907. return {
  4908. times: times,
  4909. filepositions: filepositions
  4910. };
  4911. }
  4912.  
  4913. _parseAudioData(arrayBuffer, dataOffset, dataSize, tagTimestamp) {
  4914. if (dataSize <= 1) {
  4915. Log.w(this.TAG, 'Flv: Invalid audio packet, missing SoundData payload!');
  4916. return;
  4917. }
  4918.  
  4919. if (this._hasAudioFlagOverrided === true && this._hasAudio === false) {
  4920. // If hasAudio: false indicated explicitly in MediaDataSource,
  4921. // Ignore all the audio packets
  4922. return;
  4923. }
  4924.  
  4925. let le = this._littleEndian;
  4926. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  4927.  
  4928. let soundSpec = v.getUint8(0);
  4929.  
  4930. let soundFormat = soundSpec >>> 4;
  4931. if (soundFormat !== 2 && soundFormat !== 10) { // MP3 or AAC
  4932. this._onError(DemuxErrors.CODEC_UNSUPPORTED, 'Flv: Unsupported audio codec idx: ' + soundFormat);
  4933. return;
  4934. }
  4935.  
  4936. let soundRate = 0;
  4937. let soundRateIndex = (soundSpec & 12) >>> 2;
  4938. if (soundRateIndex >= 0 && soundRateIndex <= 4) {
  4939. soundRate = this._flvSoundRateTable[soundRateIndex];
  4940. } else {
  4941. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid audio sample rate idx: ' + soundRateIndex);
  4942. return;
  4943. }
  4944. let soundType = (soundSpec & 1);
  4945.  
  4946.  
  4947. let meta = this._audioMetadata;
  4948. let track = this._audioTrack;
  4949.  
  4950. if (!meta) {
  4951. if (this._hasAudio === false && this._hasAudioFlagOverrided === false) {
  4952. this._hasAudio = true;
  4953. this._mediaInfo.hasAudio = true;
  4954. }
  4955.  
  4956. // initial metadata
  4957. meta = this._audioMetadata = {};
  4958. meta.type = 'audio';
  4959. meta.id = track.id;
  4960. meta.timescale = this._timescale;
  4961. meta.duration = this._duration;
  4962. meta.audioSampleRate = soundRate;
  4963. meta.channelCount = (soundType === 0 ? 1 : 2);
  4964. }
  4965.  
  4966. if (soundFormat === 10) { // AAC
  4967. let aacData = this._parseAACAudioData(arrayBuffer, dataOffset + 1, dataSize - 1);
  4968. if (aacData == undefined) {
  4969. return;
  4970. }
  4971.  
  4972. if (aacData.packetType === 0) { // AAC sequence header (AudioSpecificConfig)
  4973. if (meta.config) {
  4974. Log.w(this.TAG, 'Found another AudioSpecificConfig!');
  4975. }
  4976. let misc = aacData.data;
  4977. meta.audioSampleRate = misc.samplingRate;
  4978. meta.channelCount = misc.channelCount;
  4979. meta.codec = misc.codec;
  4980. meta.originalCodec = misc.originalCodec;
  4981. meta.config = misc.config;
  4982. // added by qli5
  4983. meta.configRaw = misc.configRaw;
  4984. // The decode result of an aac sample is 1024 PCM samples
  4985. meta.refSampleDuration = 1024 / meta.audioSampleRate * meta.timescale;
  4986. Log.v(this.TAG, 'Parsed AudioSpecificConfig');
  4987.  
  4988. if (this._isInitialMetadataDispatched()) {
  4989. // Non-initial metadata, force dispatch (or flush) parsed frames to remuxer
  4990. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4991. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4992. }
  4993. } else {
  4994. this._audioInitialMetadataDispatched = true;
  4995. }
  4996. // then notify new metadata
  4997. this._dispatch = false;
  4998. this._onTrackMetadata('audio', meta);
  4999.  
  5000. let mi = this._mediaInfo;
  5001. mi.audioCodec = meta.originalCodec;
  5002. mi.audioSampleRate = meta.audioSampleRate;
  5003. mi.audioChannelCount = meta.channelCount;
  5004. if (mi.hasVideo) {
  5005. if (mi.videoCodec != null) {
  5006. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  5007. }
  5008. } else {
  5009. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  5010. }
  5011. if (mi.isComplete()) {
  5012. this._onMediaInfo(mi);
  5013. }
  5014. } else if (aacData.packetType === 1) { // AAC raw frame data
  5015. let dts = this._timestampBase + tagTimestamp;
  5016. let aacSample = { unit: aacData.data, length: aacData.data.byteLength, dts: dts, pts: dts };
  5017. track.samples.push(aacSample);
  5018. track.length += aacData.data.length;
  5019. } else {
  5020. Log.e(this.TAG, \`Flv: Unsupported AAC data type \${aacData.packetType}\`);
  5021. }
  5022. } else if (soundFormat === 2) { // MP3
  5023. if (!meta.codec) {
  5024. // We need metadata for mp3 audio track, extract info from frame header
  5025. let misc = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, true);
  5026. if (misc == undefined) {
  5027. return;
  5028. }
  5029. meta.audioSampleRate = misc.samplingRate;
  5030. meta.channelCount = misc.channelCount;
  5031. meta.codec = misc.codec;
  5032. meta.originalCodec = misc.originalCodec;
  5033. // The decode result of an mp3 sample is 1152 PCM samples
  5034. meta.refSampleDuration = 1152 / meta.audioSampleRate * meta.timescale;
  5035. Log.v(this.TAG, 'Parsed MPEG Audio Frame Header');
  5036.  
  5037. this._audioInitialMetadataDispatched = true;
  5038. this._onTrackMetadata('audio', meta);
  5039.  
  5040. let mi = this._mediaInfo;
  5041. mi.audioCodec = meta.codec;
  5042. mi.audioSampleRate = meta.audioSampleRate;
  5043. mi.audioChannelCount = meta.channelCount;
  5044. mi.audioDataRate = misc.bitRate;
  5045. if (mi.hasVideo) {
  5046. if (mi.videoCodec != null) {
  5047. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  5048. }
  5049. } else {
  5050. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  5051. }
  5052. if (mi.isComplete()) {
  5053. this._onMediaInfo(mi);
  5054. }
  5055. }
  5056.  
  5057. // This packet is always a valid audio packet, extract it
  5058. let data = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, false);
  5059. if (data == undefined) {
  5060. return;
  5061. }
  5062. let dts = this._timestampBase + tagTimestamp;
  5063. let mp3Sample = { unit: data, length: data.byteLength, dts: dts, pts: dts };
  5064. track.samples.push(mp3Sample);
  5065. track.length += data.length;
  5066. }
  5067. }
  5068.  
  5069. _parseAACAudioData(arrayBuffer, dataOffset, dataSize) {
  5070. if (dataSize <= 1) {
  5071. Log.w(this.TAG, 'Flv: Invalid AAC packet, missing AACPacketType or/and Data!');
  5072. return;
  5073. }
  5074.  
  5075. let result = {};
  5076. let array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  5077.  
  5078. result.packetType = array[0];
  5079.  
  5080. if (array[0] === 0) {
  5081. result.data = this._parseAACAudioSpecificConfig(arrayBuffer, dataOffset + 1, dataSize - 1);
  5082. } else {
  5083. result.data = array.subarray(1);
  5084. }
  5085.  
  5086. return result;
  5087. }
  5088.  
  5089. _parseAACAudioSpecificConfig(arrayBuffer, dataOffset, dataSize) {
  5090. let array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  5091. let config = null;
  5092.  
  5093. /* Audio Object Type:
  5094. 0: Null
  5095. 1: AAC Main
  5096. 2: AAC LC
  5097. 3: AAC SSR (Scalable Sample Rate)
  5098. 4: AAC LTP (Long Term Prediction)
  5099. 5: HE-AAC / SBR (Spectral Band Replication)
  5100. 6: AAC Scalable
  5101. */
  5102.  
  5103. let audioObjectType = 0;
  5104. let originalAudioObjectType = 0;
  5105. let samplingIndex = 0;
  5106. let extensionSamplingIndex = null;
  5107.  
  5108. // 5 bits
  5109. audioObjectType = originalAudioObjectType = array[0] >>> 3;
  5110. // 4 bits
  5111. samplingIndex = ((array[0] & 0x07) << 1) | (array[1] >>> 7);
  5112. if (samplingIndex < 0 || samplingIndex >= this._mpegSamplingRates.length) {
  5113. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: AAC invalid sampling frequency index!');
  5114. return;
  5115. }
  5116.  
  5117. let samplingFrequence = this._mpegSamplingRates[samplingIndex];
  5118.  
  5119. // 4 bits
  5120. let channelConfig = (array[1] & 0x78) >>> 3;
  5121. if (channelConfig < 0 || channelConfig >= 8) {
  5122. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: AAC invalid channel configuration');
  5123. return;
  5124. }
  5125.  
  5126. if (audioObjectType === 5) { // HE-AAC?
  5127. // 4 bits
  5128. extensionSamplingIndex = ((array[1] & 0x07) << 1) | (array[2] >>> 7);
  5129. }
  5130.  
  5131. // workarounds for various browsers
  5132. let userAgent = _navigator.userAgent.toLowerCase();
  5133.  
  5134. if (userAgent.indexOf('firefox') !== -1) {
  5135. // firefox: use SBR (HE-AAC) if freq less than 24kHz
  5136. if (samplingIndex >= 6) {
  5137. audioObjectType = 5;
  5138. config = new Array(4);
  5139. extensionSamplingIndex = samplingIndex - 3;
  5140. } else { // use LC-AAC
  5141. audioObjectType = 2;
  5142. config = new Array(2);
  5143. extensionSamplingIndex = samplingIndex;
  5144. }
  5145. } else if (userAgent.indexOf('android') !== -1) {
  5146. // android: always use LC-AAC
  5147. audioObjectType = 2;
  5148. config = new Array(2);
  5149. extensionSamplingIndex = samplingIndex;
  5150. } else {
  5151. // for other browsers, e.g. chrome...
  5152. // Always use HE-AAC to make it easier to switch aac codec profile
  5153. audioObjectType = 5;
  5154. extensionSamplingIndex = samplingIndex;
  5155. config = new Array(4);
  5156.  
  5157. if (samplingIndex >= 6) {
  5158. extensionSamplingIndex = samplingIndex - 3;
  5159. } else if (channelConfig === 1) { // Mono channel
  5160. audioObjectType = 2;
  5161. config = new Array(2);
  5162. extensionSamplingIndex = samplingIndex;
  5163. }
  5164. }
  5165.  
  5166. config[0] = audioObjectType << 3;
  5167. config[0] |= (samplingIndex & 0x0F) >>> 1;
  5168. config[1] = (samplingIndex & 0x0F) << 7;
  5169. config[1] |= (channelConfig & 0x0F) << 3;
  5170. if (audioObjectType === 5) {
  5171. config[1] |= ((extensionSamplingIndex & 0x0F) >>> 1);
  5172. config[2] = (extensionSamplingIndex & 0x01) << 7;
  5173. // extended audio object type: force to 2 (LC-AAC)
  5174. config[2] |= (2 << 2);
  5175. config[3] = 0;
  5176. }
  5177.  
  5178. return {
  5179. // configRaw: added by qli5
  5180. configRaw: array,
  5181. config: config,
  5182. samplingRate: samplingFrequence,
  5183. channelCount: channelConfig,
  5184. codec: 'mp4a.40.' + audioObjectType,
  5185. originalCodec: 'mp4a.40.' + originalAudioObjectType
  5186. };
  5187. }
  5188.  
  5189. _parseMP3AudioData(arrayBuffer, dataOffset, dataSize, requestHeader) {
  5190. if (dataSize < 4) {
  5191. Log.w(this.TAG, 'Flv: Invalid MP3 packet, header missing!');
  5192. return;
  5193. }
  5194.  
  5195. let le = this._littleEndian;
  5196. let array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  5197. let result = null;
  5198.  
  5199. if (requestHeader) {
  5200. if (array[0] !== 0xFF) {
  5201. return;
  5202. }
  5203. let ver = (array[1] >>> 3) & 0x03;
  5204. let layer = (array[1] & 0x06) >> 1;
  5205.  
  5206. let bitrate_index = (array[2] & 0xF0) >>> 4;
  5207. let sampling_freq_index = (array[2] & 0x0C) >>> 2;
  5208.  
  5209. let channel_mode = (array[3] >>> 6) & 0x03;
  5210. let channel_count = channel_mode !== 3 ? 2 : 1;
  5211.  
  5212. let sample_rate = 0;
  5213. let bit_rate = 0;
  5214.  
  5215. let codec = 'mp3';
  5216.  
  5217. switch (ver) {
  5218. case 0: // MPEG 2.5
  5219. sample_rate = this._mpegAudioV25SampleRateTable[sampling_freq_index];
  5220. break;
  5221. case 2: // MPEG 2
  5222. sample_rate = this._mpegAudioV20SampleRateTable[sampling_freq_index];
  5223. break;
  5224. case 3: // MPEG 1
  5225. sample_rate = this._mpegAudioV10SampleRateTable[sampling_freq_index];
  5226. break;
  5227. }
  5228.  
  5229. switch (layer) {
  5230. case 1: // Layer 3
  5231. if (bitrate_index < this._mpegAudioL3BitRateTable.length) {
  5232. bit_rate = this._mpegAudioL3BitRateTable[bitrate_index];
  5233. }
  5234. break;
  5235. case 2: // Layer 2
  5236. if (bitrate_index < this._mpegAudioL2BitRateTable.length) {
  5237. bit_rate = this._mpegAudioL2BitRateTable[bitrate_index];
  5238. }
  5239. break;
  5240. case 3: // Layer 1
  5241. if (bitrate_index < this._mpegAudioL1BitRateTable.length) {
  5242. bit_rate = this._mpegAudioL1BitRateTable[bitrate_index];
  5243. }
  5244. break;
  5245. }
  5246.  
  5247. result = {
  5248. bitRate: bit_rate,
  5249. samplingRate: sample_rate,
  5250. channelCount: channel_count,
  5251. codec: codec,
  5252. originalCodec: codec
  5253. };
  5254. } else {
  5255. result = array;
  5256. }
  5257.  
  5258. return result;
  5259. }
  5260.  
  5261. _parseVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition) {
  5262. if (dataSize <= 1) {
  5263. Log.w(this.TAG, 'Flv: Invalid video packet, missing VideoData payload!');
  5264. return;
  5265. }
  5266.  
  5267. if (this._hasVideoFlagOverrided === true && this._hasVideo === false) {
  5268. // If hasVideo: false indicated explicitly in MediaDataSource,
  5269. // Ignore all the video packets
  5270. return;
  5271. }
  5272.  
  5273. let spec = (new Uint8Array(arrayBuffer, dataOffset, dataSize))[0];
  5274.  
  5275. let frameType = (spec & 240) >>> 4;
  5276. let codecId = spec & 15;
  5277.  
  5278. if (codecId !== 7) {
  5279. this._onError(DemuxErrors.CODEC_UNSUPPORTED, \`Flv: Unsupported codec in video frame: \${codecId}\`);
  5280. return;
  5281. }
  5282.  
  5283. this._parseAVCVideoPacket(arrayBuffer, dataOffset + 1, dataSize - 1, tagTimestamp, tagPosition, frameType);
  5284. }
  5285.  
  5286. _parseAVCVideoPacket(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType) {
  5287. if (dataSize < 4) {
  5288. Log.w(this.TAG, 'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime');
  5289. return;
  5290. }
  5291.  
  5292. let le = this._littleEndian;
  5293. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  5294.  
  5295. let packetType = v.getUint8(0);
  5296. let cts = v.getUint32(0, !le) & 0x00FFFFFF;
  5297.  
  5298. if (packetType === 0) { // AVCDecoderConfigurationRecord
  5299. this._parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset + 4, dataSize - 4);
  5300. } else if (packetType === 1) { // One or more Nalus
  5301. this._parseAVCVideoData(arrayBuffer, dataOffset + 4, dataSize - 4, tagTimestamp, tagPosition, frameType, cts);
  5302. } else if (packetType === 2) {
  5303. // empty, AVC end of sequence
  5304. } else {
  5305. this._onError(DemuxErrors.FORMAT_ERROR, \`Flv: Invalid video packet type \${packetType}\`);
  5306. return;
  5307. }
  5308. }
  5309.  
  5310. _parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset, dataSize) {
  5311. if (dataSize < 7) {
  5312. Log.w(this.TAG, 'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!');
  5313. return;
  5314. }
  5315.  
  5316. let meta = this._videoMetadata;
  5317. let track = this._videoTrack;
  5318. let le = this._littleEndian;
  5319. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  5320.  
  5321. if (!meta) {
  5322. if (this._hasVideo === false && this._hasVideoFlagOverrided === false) {
  5323. this._hasVideo = true;
  5324. this._mediaInfo.hasVideo = true;
  5325. }
  5326.  
  5327. meta = this._videoMetadata = {};
  5328. meta.type = 'video';
  5329. meta.id = track.id;
  5330. meta.timescale = this._timescale;
  5331. meta.duration = this._duration;
  5332. } else {
  5333. if (typeof meta.avcc !== 'undefined') {
  5334. Log.w(this.TAG, 'Found another AVCDecoderConfigurationRecord!');
  5335. }
  5336. }
  5337.  
  5338. let version = v.getUint8(0); // configurationVersion
  5339. let avcProfile = v.getUint8(1); // avcProfileIndication
  5340. let profileCompatibility = v.getUint8(2); // profile_compatibility
  5341. let avcLevel = v.getUint8(3); // AVCLevelIndication
  5342.  
  5343. if (version !== 1 || avcProfile === 0) {
  5344. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord');
  5345. return;
  5346. }
  5347.  
  5348. this._naluLengthSize = (v.getUint8(4) & 3) + 1; // lengthSizeMinusOne
  5349. if (this._naluLengthSize !== 3 && this._naluLengthSize !== 4) { // holy shit!!!
  5350. this._onError(DemuxErrors.FORMAT_ERROR, \`Flv: Strange NaluLengthSizeMinusOne: \${this._naluLengthSize - 1}\`);
  5351. return;
  5352. }
  5353.  
  5354. let spsCount = v.getUint8(5) & 31; // numOfSequenceParameterSets
  5355. if (spsCount === 0) {
  5356. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No SPS');
  5357. return;
  5358. } else if (spsCount > 1) {
  5359. Log.w(this.TAG, \`Flv: Strange AVCDecoderConfigurationRecord: SPS Count = \${spsCount}\`);
  5360. }
  5361.  
  5362. let offset = 6;
  5363.  
  5364. for (let i = 0; i < spsCount; i++) {
  5365. let len = v.getUint16(offset, !le); // sequenceParameterSetLength
  5366. offset += 2;
  5367.  
  5368. if (len === 0) {
  5369. continue;
  5370. }
  5371.  
  5372. // Notice: Nalu without startcode header (00 00 00 01)
  5373. let sps = new Uint8Array(arrayBuffer, dataOffset + offset, len);
  5374. offset += len;
  5375.  
  5376. let config = SPSParser.parseSPS(sps);
  5377. if (i !== 0) {
  5378. // ignore other sps's config
  5379. continue;
  5380. }
  5381.  
  5382. meta.codecWidth = config.codec_size.width;
  5383. meta.codecHeight = config.codec_size.height;
  5384. meta.presentWidth = config.present_size.width;
  5385. meta.presentHeight = config.present_size.height;
  5386.  
  5387. meta.profile = config.profile_string;
  5388. meta.level = config.level_string;
  5389. meta.bitDepth = config.bit_depth;
  5390. meta.chromaFormat = config.chroma_format;
  5391. meta.sarRatio = config.sar_ratio;
  5392. meta.frameRate = config.frame_rate;
  5393.  
  5394. if (config.frame_rate.fixed === false ||
  5395. config.frame_rate.fps_num === 0 ||
  5396. config.frame_rate.fps_den === 0) {
  5397. meta.frameRate = this._referenceFrameRate;
  5398. }
  5399.  
  5400. let fps_den = meta.frameRate.fps_den;
  5401. let fps_num = meta.frameRate.fps_num;
  5402. meta.refSampleDuration = meta.timescale * (fps_den / fps_num);
  5403.  
  5404. let codecArray = sps.subarray(1, 4);
  5405. let codecString = 'avc1.';
  5406. for (let j = 0; j < 3; j++) {
  5407. let h = codecArray[j].toString(16);
  5408. if (h.length < 2) {
  5409. h = '0' + h;
  5410. }
  5411. codecString += h;
  5412. }
  5413. meta.codec = codecString;
  5414.  
  5415. let mi = this._mediaInfo;
  5416. mi.width = meta.codecWidth;
  5417. mi.height = meta.codecHeight;
  5418. mi.fps = meta.frameRate.fps;
  5419. mi.profile = meta.profile;
  5420. mi.level = meta.level;
  5421. mi.chromaFormat = config.chroma_format_string;
  5422. mi.sarNum = meta.sarRatio.width;
  5423. mi.sarDen = meta.sarRatio.height;
  5424. mi.videoCodec = codecString;
  5425.  
  5426. if (mi.hasAudio) {
  5427. if (mi.audioCodec != null) {
  5428. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  5429. }
  5430. } else {
  5431. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + '"';
  5432. }
  5433. if (mi.isComplete()) {
  5434. this._onMediaInfo(mi);
  5435. }
  5436. }
  5437.  
  5438. let ppsCount = v.getUint8(offset); // numOfPictureParameterSets
  5439. if (ppsCount === 0) {
  5440. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No PPS');
  5441. return;
  5442. } else if (ppsCount > 1) {
  5443. Log.w(this.TAG, \`Flv: Strange AVCDecoderConfigurationRecord: PPS Count = \${ppsCount}\`);
  5444. }
  5445.  
  5446. offset++;
  5447.  
  5448. for (let i = 0; i < ppsCount; i++) {
  5449. let len = v.getUint16(offset, !le); // pictureParameterSetLength
  5450. offset += 2;
  5451.  
  5452. if (len === 0) {
  5453. continue;
  5454. }
  5455.  
  5456. // pps is useless for extracting video information
  5457. offset += len;
  5458. }
  5459.  
  5460. meta.avcc = new Uint8Array(dataSize);
  5461. meta.avcc.set(new Uint8Array(arrayBuffer, dataOffset, dataSize), 0);
  5462. Log.v(this.TAG, 'Parsed AVCDecoderConfigurationRecord');
  5463.  
  5464. if (this._isInitialMetadataDispatched()) {
  5465. // flush parsed frames
  5466. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  5467. this._onDataAvailable(this._audioTrack, this._videoTrack);
  5468. }
  5469. } else {
  5470. this._videoInitialMetadataDispatched = true;
  5471. }
  5472. // notify new metadata
  5473. this._dispatch = false;
  5474. this._onTrackMetadata('video', meta);
  5475. }
  5476.  
  5477. _parseAVCVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType, cts) {
  5478. let le = this._littleEndian;
  5479. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  5480.  
  5481. let units = [], length = 0;
  5482.  
  5483. let offset = 0;
  5484. const lengthSize = this._naluLengthSize;
  5485. let dts = this._timestampBase + tagTimestamp;
  5486. let keyframe = (frameType === 1); // from FLV Frame Type constants
  5487. let refIdc = 1; // added by qli5
  5488.  
  5489. while (offset < dataSize) {
  5490. if (offset + 4 >= dataSize) {
  5491. Log.w(this.TAG, \`Malformed Nalu near timestamp \${dts}, offset = \${offset}, dataSize = \${dataSize}\`);
  5492. break; // data not enough for next Nalu
  5493. }
  5494. // Nalu with length-header (AVC1)
  5495. let naluSize = v.getUint32(offset, !le); // Big-Endian read
  5496. if (lengthSize === 3) {
  5497. naluSize >>>= 8;
  5498. }
  5499. if (naluSize > dataSize - lengthSize) {
  5500. Log.w(this.TAG, \`Malformed Nalus near timestamp \${dts}, NaluSize > DataSize!\`);
  5501. return;
  5502. }
  5503.  
  5504. let unitType = v.getUint8(offset + lengthSize) & 0x1F;
  5505. // added by qli5
  5506. refIdc = v.getUint8(offset + lengthSize) & 0x60;
  5507.  
  5508. if (unitType === 5) { // IDR
  5509. keyframe = true;
  5510. }
  5511.  
  5512. let data = new Uint8Array(arrayBuffer, dataOffset + offset, lengthSize + naluSize);
  5513. let unit = { type: unitType, data: data };
  5514. units.push(unit);
  5515. length += data.byteLength;
  5516.  
  5517. offset += lengthSize + naluSize;
  5518. }
  5519.  
  5520. if (units.length) {
  5521. let track = this._videoTrack;
  5522. let avcSample = {
  5523. units: units,
  5524. length: length,
  5525. isKeyframe: keyframe,
  5526. refIdc: refIdc,
  5527. dts: dts,
  5528. cts: cts,
  5529. pts: (dts + cts)
  5530. };
  5531. if (keyframe) {
  5532. avcSample.fileposition = tagPosition;
  5533. }
  5534. track.samples.push(avcSample);
  5535. track.length += length;
  5536. }
  5537. }
  5538.  
  5539. }
  5540.  
  5541. /***
  5542. * Copyright (C) 2018 Qli5. All Rights Reserved.
  5543. *
  5544. * @author qli5 <goodlq11[at](163|gmail).com>
  5545. *
  5546. * This Source Code Form is subject to the terms of the Mozilla Public
  5547. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5548. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5549. */
  5550.  
  5551. class ASS {
  5552. /**
  5553. * Extract sections from ass string
  5554. * @param {string} str
  5555. * @returns {Object} - object from sections
  5556. */
  5557. static extractSections(str) {
  5558. const regex = /^\\ufeff?\\[(.*)\\]\$/mg;
  5559. let match;
  5560. let matchArr = [];
  5561. while ((match = regex.exec(str)) !== null) {
  5562. matchArr.push({ name: match[1], index: match.index });
  5563. }
  5564. let ret = {};
  5565. matchArr.forEach((match, i) => ret[match.name] = str.slice(match.index, matchArr[i + 1] && matchArr[i + 1].index));
  5566. return ret;
  5567. }
  5568.  
  5569. /**
  5570. * Extract subtitle lines from section Events
  5571. * @param {string} str
  5572. * @returns {Array<Object>} - array of subtitle lines
  5573. */
  5574. static extractSubtitleLines(str) {
  5575. const lines = str.split('\\n');
  5576. if (lines[0] != '[Events]' && lines[0] != '[events]') throw new Error('ASSDemuxer: section is not [Events]');
  5577. if (lines[1].indexOf('Format:') != 0 && lines[1].indexOf('format:') != 0) throw new Error('ASSDemuxer: cannot find Format definition in section [Events]');
  5578.  
  5579. const format = lines[1].slice(lines[1].indexOf(':') + 1).split(',').map(e => e.trim());
  5580. return lines.slice(2).map(e => {
  5581. let j = {};
  5582. e.replace(/[d|D]ialogue:\\s*/, '')
  5583. .match(new RegExp(new Array(format.length - 1).fill('(.*?),').join('') + '(.*)'))
  5584. .slice(1)
  5585. .forEach((k, index) => j[format[index]] = k);
  5586. return j;
  5587. });
  5588. }
  5589.  
  5590. /**
  5591. * Create a new ASS Demuxer
  5592. */
  5593. constructor() {
  5594. this.info = '';
  5595. this.styles = '';
  5596. this.events = '';
  5597. this.eventsHeader = '';
  5598. this.pictures = '';
  5599. this.fonts = '';
  5600. this.lines = '';
  5601. }
  5602.  
  5603. get header() {
  5604. // return this.info + this.styles + this.eventsHeader;
  5605. return this.info + this.styles;
  5606. }
  5607.  
  5608. /**
  5609. * Load a file from an arraybuffer of a string
  5610. * @param {(ArrayBuffer|string)} chunk
  5611. */
  5612. parseFile(chunk) {
  5613. const str = typeof chunk == 'string' ? chunk : new _TextDecoder('utf-8').decode(chunk);
  5614. for (let [i, j] of Object.entries(ASS.extractSections(str))) {
  5615. if (i.match(/Script Info(?:mation)?/i)) this.info = j;
  5616. else if (i.match(/V4\\+? Styles?/i)) this.styles = j;
  5617. else if (i.match(/Events?/i)) this.events = j;
  5618. else if (i.match(/Pictures?/i)) this.pictures = j;
  5619. else if (i.match(/Fonts?/i)) this.fonts = j;
  5620. }
  5621. this.eventsHeader = this.events.split('\\n', 2).join('\\n') + '\\n';
  5622. this.lines = ASS.extractSubtitleLines(this.events);
  5623. return this;
  5624. }
  5625. }
  5626.  
  5627. /** Detect free variable \`global\` from Node.js. */
  5628. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  5629.  
  5630. /** Detect free variable \`self\`. */
  5631. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  5632.  
  5633. /** Used as a reference to the global object. */
  5634. var root = freeGlobal || freeSelf || Function('return this')();
  5635.  
  5636. /** Built-in value references. */
  5637. var Symbol = root.Symbol;
  5638.  
  5639. /** Used for built-in method references. */
  5640. var objectProto = Object.prototype;
  5641.  
  5642. /** Used to check objects for own properties. */
  5643. var hasOwnProperty = objectProto.hasOwnProperty;
  5644.  
  5645. /**
  5646. * Used to resolve the
  5647. * [\`toStringTag\`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  5648. * of values.
  5649. */
  5650. var nativeObjectToString = objectProto.toString;
  5651.  
  5652. /** Built-in value references. */
  5653. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  5654.  
  5655. /**
  5656. * A specialized version of \`baseGetTag\` which ignores \`Symbol.toStringTag\` values.
  5657. *
  5658. * @private
  5659. * @param {*} value The value to query.
  5660. * @returns {string} Returns the raw \`toStringTag\`.
  5661. */
  5662. function getRawTag(value) {
  5663. var isOwn = hasOwnProperty.call(value, symToStringTag),
  5664. tag = value[symToStringTag];
  5665.  
  5666. try {
  5667. value[symToStringTag] = undefined;
  5668. var unmasked = true;
  5669. } catch (e) {}
  5670.  
  5671. var result = nativeObjectToString.call(value);
  5672. if (unmasked) {
  5673. if (isOwn) {
  5674. value[symToStringTag] = tag;
  5675. } else {
  5676. delete value[symToStringTag];
  5677. }
  5678. }
  5679. return result;
  5680. }
  5681.  
  5682. /** Used for built-in method references. */
  5683. var objectProto\$1 = Object.prototype;
  5684.  
  5685. /**
  5686. * Used to resolve the
  5687. * [\`toStringTag\`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  5688. * of values.
  5689. */
  5690. var nativeObjectToString\$1 = objectProto\$1.toString;
  5691.  
  5692. /**
  5693. * Converts \`value\` to a string using \`Object.prototype.toString\`.
  5694. *
  5695. * @private
  5696. * @param {*} value The value to convert.
  5697. * @returns {string} Returns the converted string.
  5698. */
  5699. function objectToString(value) {
  5700. return nativeObjectToString\$1.call(value);
  5701. }
  5702.  
  5703. /** \`Object#toString\` result references. */
  5704. var nullTag = '[object Null]',
  5705. undefinedTag = '[object Undefined]';
  5706.  
  5707. /** Built-in value references. */
  5708. var symToStringTag\$1 = Symbol ? Symbol.toStringTag : undefined;
  5709.  
  5710. /**
  5711. * The base implementation of \`getTag\` without fallbacks for buggy environments.
  5712. *
  5713. * @private
  5714. * @param {*} value The value to query.
  5715. * @returns {string} Returns the \`toStringTag\`.
  5716. */
  5717. function baseGetTag(value) {
  5718. if (value == null) {
  5719. return value === undefined ? undefinedTag : nullTag;
  5720. }
  5721. return (symToStringTag\$1 && symToStringTag\$1 in Object(value))
  5722. ? getRawTag(value)
  5723. : objectToString(value);
  5724. }
  5725.  
  5726. /**
  5727. * Checks if \`value\` is the
  5728. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  5729. * of \`Object\`. (e.g. arrays, functions, objects, regexes, \`new Number(0)\`, and \`new String('')\`)
  5730. *
  5731. * @static
  5732. * @memberOf _
  5733. * @since 0.1.0
  5734. * @category Lang
  5735. * @param {*} value The value to check.
  5736. * @returns {boolean} Returns \`true\` if \`value\` is an object, else \`false\`.
  5737. * @example
  5738. *
  5739. * _.isObject({});
  5740. * // => true
  5741. *
  5742. * _.isObject([1, 2, 3]);
  5743. * // => true
  5744. *
  5745. * _.isObject(_.noop);
  5746. * // => true
  5747. *
  5748. * _.isObject(null);
  5749. * // => false
  5750. */
  5751. function isObject(value) {
  5752. var type = typeof value;
  5753. return value != null && (type == 'object' || type == 'function');
  5754. }
  5755.  
  5756. /** \`Object#toString\` result references. */
  5757. var asyncTag = '[object AsyncFunction]',
  5758. funcTag = '[object Function]',
  5759. genTag = '[object GeneratorFunction]',
  5760. proxyTag = '[object Proxy]';
  5761.  
  5762. /**
  5763. * Checks if \`value\` is classified as a \`Function\` object.
  5764. *
  5765. * @static
  5766. * @memberOf _
  5767. * @since 0.1.0
  5768. * @category Lang
  5769. * @param {*} value The value to check.
  5770. * @returns {boolean} Returns \`true\` if \`value\` is a function, else \`false\`.
  5771. * @example
  5772. *
  5773. * _.isFunction(_);
  5774. * // => true
  5775. *
  5776. * _.isFunction(/abc/);
  5777. * // => false
  5778. */
  5779. function isFunction(value) {
  5780. if (!isObject(value)) {
  5781. return false;
  5782. }
  5783. // The use of \`Object#toString\` avoids issues with the \`typeof\` operator
  5784. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  5785. var tag = baseGetTag(value);
  5786. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  5787. }
  5788.  
  5789. /** Used to detect overreaching core-js shims. */
  5790. var coreJsData = root['__core-js_shared__'];
  5791.  
  5792. /** Used to detect methods masquerading as native. */
  5793. var maskSrcKey = (function() {
  5794. var uid = /[^.]+\$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  5795. return uid ? ('Symbol(src)_1.' + uid) : '';
  5796. }());
  5797.  
  5798. /**
  5799. * Checks if \`func\` has its source masked.
  5800. *
  5801. * @private
  5802. * @param {Function} func The function to check.
  5803. * @returns {boolean} Returns \`true\` if \`func\` is masked, else \`false\`.
  5804. */
  5805. function isMasked(func) {
  5806. return !!maskSrcKey && (maskSrcKey in func);
  5807. }
  5808.  
  5809. /** Used for built-in method references. */
  5810. var funcProto = Function.prototype;
  5811.  
  5812. /** Used to resolve the decompiled source of functions. */
  5813. var funcToString = funcProto.toString;
  5814.  
  5815. /**
  5816. * Converts \`func\` to its source code.
  5817. *
  5818. * @private
  5819. * @param {Function} func The function to convert.
  5820. * @returns {string} Returns the source code.
  5821. */
  5822. function toSource(func) {
  5823. if (func != null) {
  5824. try {
  5825. return funcToString.call(func);
  5826. } catch (e) {}
  5827. try {
  5828. return (func + '');
  5829. } catch (e) {}
  5830. }
  5831. return '';
  5832. }
  5833.  
  5834. /**
  5835. * Used to match \`RegExp\`
  5836. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  5837. */
  5838. var reRegExpChar = /[\\\\^\$.*+?()[\\]{}|]/g;
  5839.  
  5840. /** Used to detect host constructors (Safari). */
  5841. var reIsHostCtor = /^\\[object .+?Constructor\\]\$/;
  5842.  
  5843. /** Used for built-in method references. */
  5844. var funcProto\$1 = Function.prototype,
  5845. objectProto\$2 = Object.prototype;
  5846.  
  5847. /** Used to resolve the decompiled source of functions. */
  5848. var funcToString\$1 = funcProto\$1.toString;
  5849.  
  5850. /** Used to check objects for own properties. */
  5851. var hasOwnProperty\$1 = objectProto\$2.hasOwnProperty;
  5852.  
  5853. /** Used to detect if a method is native. */
  5854. var reIsNative = RegExp('^' +
  5855. funcToString\$1.call(hasOwnProperty\$1).replace(reRegExpChar, '\\\\\$&')
  5856. .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '\$1.*?') + '\$'
  5857. );
  5858.  
  5859. /**
  5860. * The base implementation of \`_.isNative\` without bad shim checks.
  5861. *
  5862. * @private
  5863. * @param {*} value The value to check.
  5864. * @returns {boolean} Returns \`true\` if \`value\` is a native function,
  5865. * else \`false\`.
  5866. */
  5867. function baseIsNative(value) {
  5868. if (!isObject(value) || isMasked(value)) {
  5869. return false;
  5870. }
  5871. var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  5872. return pattern.test(toSource(value));
  5873. }
  5874.  
  5875. /**
  5876. * Gets the value at \`key\` of \`object\`.
  5877. *
  5878. * @private
  5879. * @param {Object} [object] The object to query.
  5880. * @param {string} key The key of the property to get.
  5881. * @returns {*} Returns the property value.
  5882. */
  5883. function getValue(object, key) {
  5884. return object == null ? undefined : object[key];
  5885. }
  5886.  
  5887. /**
  5888. * Gets the native function at \`key\` of \`object\`.
  5889. *
  5890. * @private
  5891. * @param {Object} object The object to query.
  5892. * @param {string} key The key of the method to get.
  5893. * @returns {*} Returns the function if it's native, else \`undefined\`.
  5894. */
  5895. function getNative(object, key) {
  5896. var value = getValue(object, key);
  5897. return baseIsNative(value) ? value : undefined;
  5898. }
  5899.  
  5900. /* Built-in method references that are verified to be native. */
  5901. var nativeCreate = getNative(Object, 'create');
  5902.  
  5903. /**
  5904. * Removes all key-value entries from the hash.
  5905. *
  5906. * @private
  5907. * @name clear
  5908. * @memberOf Hash
  5909. */
  5910. function hashClear() {
  5911. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  5912. this.size = 0;
  5913. }
  5914.  
  5915. /**
  5916. * Removes \`key\` and its value from the hash.
  5917. *
  5918. * @private
  5919. * @name delete
  5920. * @memberOf Hash
  5921. * @param {Object} hash The hash to modify.
  5922. * @param {string} key The key of the value to remove.
  5923. * @returns {boolean} Returns \`true\` if the entry was removed, else \`false\`.
  5924. */
  5925. function hashDelete(key) {
  5926. var result = this.has(key) && delete this.__data__[key];
  5927. this.size -= result ? 1 : 0;
  5928. return result;
  5929. }
  5930.  
  5931. /** Used to stand-in for \`undefined\` hash values. */
  5932. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  5933.  
  5934. /** Used for built-in method references. */
  5935. var objectProto\$3 = Object.prototype;
  5936.  
  5937. /** Used to check objects for own properties. */
  5938. var hasOwnProperty\$2 = objectProto\$3.hasOwnProperty;
  5939.  
  5940. /**
  5941. * Gets the hash value for \`key\`.
  5942. *
  5943. * @private
  5944. * @name get
  5945. * @memberOf Hash
  5946. * @param {string} key The key of the value to get.
  5947. * @returns {*} Returns the entry value.
  5948. */
  5949. function hashGet(key) {
  5950. var data = this.__data__;
  5951. if (nativeCreate) {
  5952. var result = data[key];
  5953. return result === HASH_UNDEFINED ? undefined : result;
  5954. }
  5955. return hasOwnProperty\$2.call(data, key) ? data[key] : undefined;
  5956. }
  5957.  
  5958. /** Used for built-in method references. */
  5959. var objectProto\$4 = Object.prototype;
  5960.  
  5961. /** Used to check objects for own properties. */
  5962. var hasOwnProperty\$3 = objectProto\$4.hasOwnProperty;
  5963.  
  5964. /**
  5965. * Checks if a hash value for \`key\` exists.
  5966. *
  5967. * @private
  5968. * @name has
  5969. * @memberOf Hash
  5970. * @param {string} key The key of the entry to check.
  5971. * @returns {boolean} Returns \`true\` if an entry for \`key\` exists, else \`false\`.
  5972. */
  5973. function hashHas(key) {
  5974. var data = this.__data__;
  5975. return nativeCreate ? (data[key] !== undefined) : hasOwnProperty\$3.call(data, key);
  5976. }
  5977.  
  5978. /** Used to stand-in for \`undefined\` hash values. */
  5979. var HASH_UNDEFINED\$1 = '__lodash_hash_undefined__';
  5980.  
  5981. /**
  5982. * Sets the hash \`key\` to \`value\`.
  5983. *
  5984. * @private
  5985. * @name set
  5986. * @memberOf Hash
  5987. * @param {string} key The key of the value to set.
  5988. * @param {*} value The value to set.
  5989. * @returns {Object} Returns the hash instance.
  5990. */
  5991. function hashSet(key, value) {
  5992. var data = this.__data__;
  5993. this.size += this.has(key) ? 0 : 1;
  5994. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED\$1 : value;
  5995. return this;
  5996. }
  5997.  
  5998. /**
  5999. * Creates a hash object.
  6000. *
  6001. * @private
  6002. * @constructor
  6003. * @param {Array} [entries] The key-value pairs to cache.
  6004. */
  6005. function Hash(entries) {
  6006. var index = -1,
  6007. length = entries == null ? 0 : entries.length;
  6008.  
  6009. this.clear();
  6010. while (++index < length) {
  6011. var entry = entries[index];
  6012. this.set(entry[0], entry[1]);
  6013. }
  6014. }
  6015.  
  6016. // Add methods to \`Hash\`.
  6017. Hash.prototype.clear = hashClear;
  6018. Hash.prototype['delete'] = hashDelete;
  6019. Hash.prototype.get = hashGet;
  6020. Hash.prototype.has = hashHas;
  6021. Hash.prototype.set = hashSet;
  6022.  
  6023. /**
  6024. * Removes all key-value entries from the list cache.
  6025. *
  6026. * @private
  6027. * @name clear
  6028. * @memberOf ListCache
  6029. */
  6030. function listCacheClear() {
  6031. this.__data__ = [];
  6032. this.size = 0;
  6033. }
  6034.  
  6035. /**
  6036. * Performs a
  6037. * [\`SameValueZero\`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  6038. * comparison between two values to determine if they are equivalent.
  6039. *
  6040. * @static
  6041. * @memberOf _
  6042. * @since 4.0.0
  6043. * @category Lang
  6044. * @param {*} value The value to compare.
  6045. * @param {*} other The other value to compare.
  6046. * @returns {boolean} Returns \`true\` if the values are equivalent, else \`false\`.
  6047. * @example
  6048. *
  6049. * var object = { 'a': 1 };
  6050. * var other = { 'a': 1 };
  6051. *
  6052. * _.eq(object, object);
  6053. * // => true
  6054. *
  6055. * _.eq(object, other);
  6056. * // => false
  6057. *
  6058. * _.eq('a', 'a');
  6059. * // => true
  6060. *
  6061. * _.eq('a', Object('a'));
  6062. * // => false
  6063. *
  6064. * _.eq(NaN, NaN);
  6065. * // => true
  6066. */
  6067. function eq(value, other) {
  6068. return value === other || (value !== value && other !== other);
  6069. }
  6070.  
  6071. /**
  6072. * Gets the index at which the \`key\` is found in \`array\` of key-value pairs.
  6073. *
  6074. * @private
  6075. * @param {Array} array The array to inspect.
  6076. * @param {*} key The key to search for.
  6077. * @returns {number} Returns the index of the matched value, else \`-1\`.
  6078. */
  6079. function assocIndexOf(array, key) {
  6080. var length = array.length;
  6081. while (length--) {
  6082. if (eq(array[length][0], key)) {
  6083. return length;
  6084. }
  6085. }
  6086. return -1;
  6087. }
  6088.  
  6089. /** Used for built-in method references. */
  6090. var arrayProto = Array.prototype;
  6091.  
  6092. /** Built-in value references. */
  6093. var splice = arrayProto.splice;
  6094.  
  6095. /**
  6096. * Removes \`key\` and its value from the list cache.
  6097. *
  6098. * @private
  6099. * @name delete
  6100. * @memberOf ListCache
  6101. * @param {string} key The key of the value to remove.
  6102. * @returns {boolean} Returns \`true\` if the entry was removed, else \`false\`.
  6103. */
  6104. function listCacheDelete(key) {
  6105. var data = this.__data__,
  6106. index = assocIndexOf(data, key);
  6107.  
  6108. if (index < 0) {
  6109. return false;
  6110. }
  6111. var lastIndex = data.length - 1;
  6112. if (index == lastIndex) {
  6113. data.pop();
  6114. } else {
  6115. splice.call(data, index, 1);
  6116. }
  6117. --this.size;
  6118. return true;
  6119. }
  6120.  
  6121. /**
  6122. * Gets the list cache value for \`key\`.
  6123. *
  6124. * @private
  6125. * @name get
  6126. * @memberOf ListCache
  6127. * @param {string} key The key of the value to get.
  6128. * @returns {*} Returns the entry value.
  6129. */
  6130. function listCacheGet(key) {
  6131. var data = this.__data__,
  6132. index = assocIndexOf(data, key);
  6133.  
  6134. return index < 0 ? undefined : data[index][1];
  6135. }
  6136.  
  6137. /**
  6138. * Checks if a list cache value for \`key\` exists.
  6139. *
  6140. * @private
  6141. * @name has
  6142. * @memberOf ListCache
  6143. * @param {string} key The key of the entry to check.
  6144. * @returns {boolean} Returns \`true\` if an entry for \`key\` exists, else \`false\`.
  6145. */
  6146. function listCacheHas(key) {
  6147. return assocIndexOf(this.__data__, key) > -1;
  6148. }
  6149.  
  6150. /**
  6151. * Sets the list cache \`key\` to \`value\`.
  6152. *
  6153. * @private
  6154. * @name set
  6155. * @memberOf ListCache
  6156. * @param {string} key The key of the value to set.
  6157. * @param {*} value The value to set.
  6158. * @returns {Object} Returns the list cache instance.
  6159. */
  6160. function listCacheSet(key, value) {
  6161. var data = this.__data__,
  6162. index = assocIndexOf(data, key);
  6163.  
  6164. if (index < 0) {
  6165. ++this.size;
  6166. data.push([key, value]);
  6167. } else {
  6168. data[index][1] = value;
  6169. }
  6170. return this;
  6171. }
  6172.  
  6173. /**
  6174. * Creates an list cache object.
  6175. *
  6176. * @private
  6177. * @constructor
  6178. * @param {Array} [entries] The key-value pairs to cache.
  6179. */
  6180. function ListCache(entries) {
  6181. var index = -1,
  6182. length = entries == null ? 0 : entries.length;
  6183.  
  6184. this.clear();
  6185. while (++index < length) {
  6186. var entry = entries[index];
  6187. this.set(entry[0], entry[1]);
  6188. }
  6189. }
  6190.  
  6191. // Add methods to \`ListCache\`.
  6192. ListCache.prototype.clear = listCacheClear;
  6193. ListCache.prototype['delete'] = listCacheDelete;
  6194. ListCache.prototype.get = listCacheGet;
  6195. ListCache.prototype.has = listCacheHas;
  6196. ListCache.prototype.set = listCacheSet;
  6197.  
  6198. /* Built-in method references that are verified to be native. */
  6199. var Map = getNative(root, 'Map');
  6200.  
  6201. /**
  6202. * Removes all key-value entries from the map.
  6203. *
  6204. * @private
  6205. * @name clear
  6206. * @memberOf MapCache
  6207. */
  6208. function mapCacheClear() {
  6209. this.size = 0;
  6210. this.__data__ = {
  6211. 'hash': new Hash,
  6212. 'map': new (Map || ListCache),
  6213. 'string': new Hash
  6214. };
  6215. }
  6216.  
  6217. /**
  6218. * Checks if \`value\` is suitable for use as unique object key.
  6219. *
  6220. * @private
  6221. * @param {*} value The value to check.
  6222. * @returns {boolean} Returns \`true\` if \`value\` is suitable, else \`false\`.
  6223. */
  6224. function isKeyable(value) {
  6225. var type = typeof value;
  6226. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  6227. ? (value !== '__proto__')
  6228. : (value === null);
  6229. }
  6230.  
  6231. /**
  6232. * Gets the data for \`map\`.
  6233. *
  6234. * @private
  6235. * @param {Object} map The map to query.
  6236. * @param {string} key The reference key.
  6237. * @returns {*} Returns the map data.
  6238. */
  6239. function getMapData(map, key) {
  6240. var data = map.__data__;
  6241. return isKeyable(key)
  6242. ? data[typeof key == 'string' ? 'string' : 'hash']
  6243. : data.map;
  6244. }
  6245.  
  6246. /**
  6247. * Removes \`key\` and its value from the map.
  6248. *
  6249. * @private
  6250. * @name delete
  6251. * @memberOf MapCache
  6252. * @param {string} key The key of the value to remove.
  6253. * @returns {boolean} Returns \`true\` if the entry was removed, else \`false\`.
  6254. */
  6255. function mapCacheDelete(key) {
  6256. var result = getMapData(this, key)['delete'](key);
  6257. this.size -= result ? 1 : 0;
  6258. return result;
  6259. }
  6260.  
  6261. /**
  6262. * Gets the map value for \`key\`.
  6263. *
  6264. * @private
  6265. * @name get
  6266. * @memberOf MapCache
  6267. * @param {string} key The key of the value to get.
  6268. * @returns {*} Returns the entry value.
  6269. */
  6270. function mapCacheGet(key) {
  6271. return getMapData(this, key).get(key);
  6272. }
  6273.  
  6274. /**
  6275. * Checks if a map value for \`key\` exists.
  6276. *
  6277. * @private
  6278. * @name has
  6279. * @memberOf MapCache
  6280. * @param {string} key The key of the entry to check.
  6281. * @returns {boolean} Returns \`true\` if an entry for \`key\` exists, else \`false\`.
  6282. */
  6283. function mapCacheHas(key) {
  6284. return getMapData(this, key).has(key);
  6285. }
  6286.  
  6287. /**
  6288. * Sets the map \`key\` to \`value\`.
  6289. *
  6290. * @private
  6291. * @name set
  6292. * @memberOf MapCache
  6293. * @param {string} key The key of the value to set.
  6294. * @param {*} value The value to set.
  6295. * @returns {Object} Returns the map cache instance.
  6296. */
  6297. function mapCacheSet(key, value) {
  6298. var data = getMapData(this, key),
  6299. size = data.size;
  6300.  
  6301. data.set(key, value);
  6302. this.size += data.size == size ? 0 : 1;
  6303. return this;
  6304. }
  6305.  
  6306. /**
  6307. * Creates a map cache object to store key-value pairs.
  6308. *
  6309. * @private
  6310. * @constructor
  6311. * @param {Array} [entries] The key-value pairs to cache.
  6312. */
  6313. function MapCache(entries) {
  6314. var index = -1,
  6315. length = entries == null ? 0 : entries.length;
  6316.  
  6317. this.clear();
  6318. while (++index < length) {
  6319. var entry = entries[index];
  6320. this.set(entry[0], entry[1]);
  6321. }
  6322. }
  6323.  
  6324. // Add methods to \`MapCache\`.
  6325. MapCache.prototype.clear = mapCacheClear;
  6326. MapCache.prototype['delete'] = mapCacheDelete;
  6327. MapCache.prototype.get = mapCacheGet;
  6328. MapCache.prototype.has = mapCacheHas;
  6329. MapCache.prototype.set = mapCacheSet;
  6330.  
  6331. /** Error message constants. */
  6332. var FUNC_ERROR_TEXT = 'Expected a function';
  6333.  
  6334. /**
  6335. * Creates a function that memoizes the result of \`func\`. If \`resolver\` is
  6336. * provided, it determines the cache key for storing the result based on the
  6337. * arguments provided to the memoized function. By default, the first argument
  6338. * provided to the memoized function is used as the map cache key. The \`func\`
  6339. * is invoked with the \`this\` binding of the memoized function.
  6340. *
  6341. * **Note:** The cache is exposed as the \`cache\` property on the memoized
  6342. * function. Its creation may be customized by replacing the \`_.memoize.Cache\`
  6343. * constructor with one whose instances implement the
  6344. * [\`Map\`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  6345. * method interface of \`clear\`, \`delete\`, \`get\`, \`has\`, and \`set\`.
  6346. *
  6347. * @static
  6348. * @memberOf _
  6349. * @since 0.1.0
  6350. * @category Function
  6351. * @param {Function} func The function to have its output memoized.
  6352. * @param {Function} [resolver] The function to resolve the cache key.
  6353. * @returns {Function} Returns the new memoized function.
  6354. * @example
  6355. *
  6356. * var object = { 'a': 1, 'b': 2 };
  6357. * var other = { 'c': 3, 'd': 4 };
  6358. *
  6359. * var values = _.memoize(_.values);
  6360. * values(object);
  6361. * // => [1, 2]
  6362. *
  6363. * values(other);
  6364. * // => [3, 4]
  6365. *
  6366. * object.a = 2;
  6367. * values(object);
  6368. * // => [1, 2]
  6369. *
  6370. * // Modify the result cache.
  6371. * values.cache.set(object, ['a', 'b']);
  6372. * values(object);
  6373. * // => ['a', 'b']
  6374. *
  6375. * // Replace \`_.memoize.Cache\`.
  6376. * _.memoize.Cache = WeakMap;
  6377. */
  6378. function memoize(func, resolver) {
  6379. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  6380. throw new TypeError(FUNC_ERROR_TEXT);
  6381. }
  6382. var memoized = function() {
  6383. var args = arguments,
  6384. key = resolver ? resolver.apply(this, args) : args[0],
  6385. cache = memoized.cache;
  6386.  
  6387. if (cache.has(key)) {
  6388. return cache.get(key);
  6389. }
  6390. var result = func.apply(this, args);
  6391. memoized.cache = cache.set(key, result) || cache;
  6392. return result;
  6393. };
  6394. memoized.cache = new (memoize.Cache || MapCache);
  6395. return memoized;
  6396. }
  6397.  
  6398. // Expose \`MapCache\`.
  6399. memoize.Cache = MapCache;
  6400.  
  6401. const numberToByteArray = (num, byteLength = getNumberByteLength(num)) => {
  6402. var byteArray;
  6403. if (byteLength == 1) {
  6404. byteArray = new DataView(new ArrayBuffer(1));
  6405. byteArray.setUint8(0, num);
  6406. }
  6407. else if (byteLength == 2) {
  6408. byteArray = new DataView(new ArrayBuffer(2));
  6409. byteArray.setUint16(0, num);
  6410. }
  6411. else if (byteLength == 3) {
  6412. byteArray = new DataView(new ArrayBuffer(3));
  6413. byteArray.setUint8(0, num >> 16);
  6414. byteArray.setUint16(1, num & 0xffff);
  6415. }
  6416. else if (byteLength == 4) {
  6417. byteArray = new DataView(new ArrayBuffer(4));
  6418. byteArray.setUint32(0, num);
  6419. }
  6420. else if (num < 0xffffffff) {
  6421. byteArray = new DataView(new ArrayBuffer(5));
  6422. byteArray.setUint32(1, num);
  6423. }
  6424. else if (byteLength == 5) {
  6425. byteArray = new DataView(new ArrayBuffer(5));
  6426. byteArray.setUint8(0, num / 0x100000000 | 0);
  6427. byteArray.setUint32(1, num % 0x100000000);
  6428. }
  6429. else if (byteLength == 6) {
  6430. byteArray = new DataView(new ArrayBuffer(6));
  6431. byteArray.setUint16(0, num / 0x100000000 | 0);
  6432. byteArray.setUint32(2, num % 0x100000000);
  6433. }
  6434. else if (byteLength == 7) {
  6435. byteArray = new DataView(new ArrayBuffer(7));
  6436. byteArray.setUint8(0, num / 0x1000000000000 | 0);
  6437. byteArray.setUint16(1, num / 0x100000000 & 0xffff);
  6438. byteArray.setUint32(3, num % 0x100000000);
  6439. }
  6440. else if (byteLength == 8) {
  6441. byteArray = new DataView(new ArrayBuffer(8));
  6442. byteArray.setUint32(0, num / 0x100000000 | 0);
  6443. byteArray.setUint32(4, num % 0x100000000);
  6444. }
  6445. else {
  6446. throw new Error("EBML.typedArrayUtils.numberToByteArray: byte length must be less than or equal to 8");
  6447. }
  6448. return new Uint8Array(byteArray.buffer);
  6449. };
  6450. const stringToByteArray = memoize((str) => {
  6451. return Uint8Array.from(Array.from(str).map(_ => _.codePointAt(0)));
  6452. });
  6453. function getNumberByteLength(num) {
  6454. if (num < 0) {
  6455. throw new Error("EBML.typedArrayUtils.getNumberByteLength: negative number not implemented");
  6456. }
  6457. else if (num < 0x100) {
  6458. return 1;
  6459. }
  6460. else if (num < 0x10000) {
  6461. return 2;
  6462. }
  6463. else if (num < 0x1000000) {
  6464. return 3;
  6465. }
  6466. else if (num < 0x100000000) {
  6467. return 4;
  6468. }
  6469. else if (num < 0x10000000000) {
  6470. return 5;
  6471. }
  6472. else if (num < 0x1000000000000) {
  6473. return 6;
  6474. }
  6475. else if (num < 0x20000000000000) {
  6476. return 7;
  6477. }
  6478. else {
  6479. throw new Error("EBML.typedArrayUtils.getNumberByteLength: number exceeds Number.MAX_SAFE_INTEGER");
  6480. }
  6481. }
  6482. const int16Bit = memoize((num) => {
  6483. const ab = new ArrayBuffer(2);
  6484. new DataView(ab).setInt16(0, num);
  6485. return new Uint8Array(ab);
  6486. });
  6487. const float32bit = memoize((num) => {
  6488. const ab = new ArrayBuffer(4);
  6489. new DataView(ab).setFloat32(0, num);
  6490. return new Uint8Array(ab);
  6491. });
  6492. const dumpBytes = (b) => {
  6493. return Array.from(new Uint8Array(b)).map(_ => \`0x\${_.toString(16)}\`).join(", ");
  6494. };
  6495.  
  6496. class Value {
  6497. constructor(bytes) {
  6498. this.bytes = bytes;
  6499. }
  6500. write(buf, pos) {
  6501. buf.set(this.bytes, pos);
  6502. return pos + this.bytes.length;
  6503. }
  6504. countSize() {
  6505. return this.bytes.length;
  6506. }
  6507. }
  6508. class Element {
  6509. constructor(id, children, isSizeUnknown) {
  6510. this.id = id;
  6511. this.children = children;
  6512. const bodySize = this.children.reduce((p, c) => p + c.countSize(), 0);
  6513. this.sizeMetaData = isSizeUnknown ?
  6514. UNKNOWN_SIZE :
  6515. vintEncode(numberToByteArray(bodySize, getEBMLByteLength(bodySize)));
  6516. this.size = this.id.length + this.sizeMetaData.length + bodySize;
  6517. }
  6518. write(buf, pos) {
  6519. buf.set(this.id, pos);
  6520. buf.set(this.sizeMetaData, pos + this.id.length);
  6521. return this.children.reduce((p, c) => c.write(buf, p), pos + this.id.length + this.sizeMetaData.length);
  6522. }
  6523. countSize() {
  6524. return this.size;
  6525. }
  6526. }
  6527. const bytes = memoize((data) => {
  6528. return new Value(data);
  6529. });
  6530. const number = memoize((num) => {
  6531. return bytes(numberToByteArray(num));
  6532. });
  6533. const vintEncodedNumber = memoize((num) => {
  6534. return bytes(vintEncode(numberToByteArray(num, getEBMLByteLength(num))));
  6535. });
  6536. const int16 = memoize((num) => {
  6537. return bytes(int16Bit(num));
  6538. });
  6539. const float = memoize((num) => {
  6540. return bytes(float32bit(num));
  6541. });
  6542. const string = memoize((str) => {
  6543. return bytes(stringToByteArray(str));
  6544. });
  6545. const element = (id, child) => {
  6546. return new Element(id, Array.isArray(child) ? child : [child], false);
  6547. };
  6548. const unknownSizeElement = (id, child) => {
  6549. return new Element(id, Array.isArray(child) ? child : [child], true);
  6550. };
  6551. const build = (v) => {
  6552. const b = new Uint8Array(v.countSize());
  6553. v.write(b, 0);
  6554. return b;
  6555. };
  6556. const getEBMLByteLength = (num) => {
  6557. if (num < 0x7f) {
  6558. return 1;
  6559. }
  6560. else if (num < 0x3fff) {
  6561. return 2;
  6562. }
  6563. else if (num < 0x1fffff) {
  6564. return 3;
  6565. }
  6566. else if (num < 0xfffffff) {
  6567. return 4;
  6568. }
  6569. else if (num < 0x7ffffffff) {
  6570. return 5;
  6571. }
  6572. else if (num < 0x3ffffffffff) {
  6573. return 6;
  6574. }
  6575. else if (num < 0x1ffffffffffff) {
  6576. return 7;
  6577. }
  6578. else if (num < 0x20000000000000) {
  6579. return 8;
  6580. }
  6581. else if (num < 0xffffffffffffff) {
  6582. throw new Error("EBMLgetEBMLByteLength: number exceeds Number.MAX_SAFE_INTEGER");
  6583. }
  6584. else {
  6585. throw new Error("EBMLgetEBMLByteLength: data size must be less than or equal to " + (Math.pow(2, 56) - 2));
  6586. }
  6587. };
  6588. const UNKNOWN_SIZE = new Uint8Array([0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
  6589. const vintEncode = (byteArray) => {
  6590. byteArray[0] = getSizeMask(byteArray.length) | byteArray[0];
  6591. return byteArray;
  6592. };
  6593. const getSizeMask = (byteLength) => {
  6594. return 0x80 >> (byteLength - 1);
  6595. };
  6596.  
  6597. /**
  6598. * @see https://www.matroska.org/technical/specs/index.html
  6599. */
  6600. const ID = {
  6601. EBML: Uint8Array.of(0x1A, 0x45, 0xDF, 0xA3),
  6602. EBMLVersion: Uint8Array.of(0x42, 0x86),
  6603. EBMLReadVersion: Uint8Array.of(0x42, 0xF7),
  6604. EBMLMaxIDLength: Uint8Array.of(0x42, 0xF2),
  6605. EBMLMaxSizeLength: Uint8Array.of(0x42, 0xF3),
  6606. DocType: Uint8Array.of(0x42, 0x82),
  6607. DocTypeVersion: Uint8Array.of(0x42, 0x87),
  6608. DocTypeReadVersion: Uint8Array.of(0x42, 0x85),
  6609. Void: Uint8Array.of(0xEC),
  6610. CRC32: Uint8Array.of(0xBF),
  6611. Segment: Uint8Array.of(0x18, 0x53, 0x80, 0x67),
  6612. SeekHead: Uint8Array.of(0x11, 0x4D, 0x9B, 0x74),
  6613. Seek: Uint8Array.of(0x4D, 0xBB),
  6614. SeekID: Uint8Array.of(0x53, 0xAB),
  6615. SeekPosition: Uint8Array.of(0x53, 0xAC),
  6616. Info: Uint8Array.of(0x15, 0x49, 0xA9, 0x66),
  6617. SegmentUID: Uint8Array.of(0x73, 0xA4),
  6618. SegmentFilename: Uint8Array.of(0x73, 0x84),
  6619. PrevUID: Uint8Array.of(0x3C, 0xB9, 0x23),
  6620. PrevFilename: Uint8Array.of(0x3C, 0x83, 0xAB),
  6621. NextUID: Uint8Array.of(0x3E, 0xB9, 0x23),
  6622. NextFilename: Uint8Array.of(0x3E, 0x83, 0xBB),
  6623. SegmentFamily: Uint8Array.of(0x44, 0x44),
  6624. ChapterTranslate: Uint8Array.of(0x69, 0x24),
  6625. ChapterTranslateEditionUID: Uint8Array.of(0x69, 0xFC),
  6626. ChapterTranslateCodec: Uint8Array.of(0x69, 0xBF),
  6627. ChapterTranslateID: Uint8Array.of(0x69, 0xA5),
  6628. TimecodeScale: Uint8Array.of(0x2A, 0xD7, 0xB1),
  6629. Duration: Uint8Array.of(0x44, 0x89),
  6630. DateUTC: Uint8Array.of(0x44, 0x61),
  6631. Title: Uint8Array.of(0x7B, 0xA9),
  6632. MuxingApp: Uint8Array.of(0x4D, 0x80),
  6633. WritingApp: Uint8Array.of(0x57, 0x41),
  6634. Cluster: Uint8Array.of(0x1F, 0x43, 0xB6, 0x75),
  6635. Timecode: Uint8Array.of(0xE7),
  6636. SilentTracks: Uint8Array.of(0x58, 0x54),
  6637. SilentTrackNumber: Uint8Array.of(0x58, 0xD7),
  6638. Position: Uint8Array.of(0xA7),
  6639. PrevSize: Uint8Array.of(0xAB),
  6640. SimpleBlock: Uint8Array.of(0xA3),
  6641. BlockGroup: Uint8Array.of(0xA0),
  6642. Block: Uint8Array.of(0xA1),
  6643. BlockAdditions: Uint8Array.of(0x75, 0xA1),
  6644. BlockMore: Uint8Array.of(0xA6),
  6645. BlockAddID: Uint8Array.of(0xEE),
  6646. BlockAdditional: Uint8Array.of(0xA5),
  6647. BlockDuration: Uint8Array.of(0x9B),
  6648. ReferencePriority: Uint8Array.of(0xFA),
  6649. ReferenceBlock: Uint8Array.of(0xFB),
  6650. CodecState: Uint8Array.of(0xA4),
  6651. DiscardPadding: Uint8Array.of(0x75, 0xA2),
  6652. Slices: Uint8Array.of(0x8E),
  6653. TimeSlice: Uint8Array.of(0xE8),
  6654. LaceNumber: Uint8Array.of(0xCC),
  6655. Tracks: Uint8Array.of(0x16, 0x54, 0xAE, 0x6B),
  6656. TrackEntry: Uint8Array.of(0xAE),
  6657. TrackNumber: Uint8Array.of(0xD7),
  6658. TrackUID: Uint8Array.of(0x73, 0xC5),
  6659. TrackType: Uint8Array.of(0x83),
  6660. FlagEnabled: Uint8Array.of(0xB9),
  6661. FlagDefault: Uint8Array.of(0x88),
  6662. FlagForced: Uint8Array.of(0x55, 0xAA),
  6663. FlagLacing: Uint8Array.of(0x9C),
  6664. MinCache: Uint8Array.of(0x6D, 0xE7),
  6665. MaxCache: Uint8Array.of(0x6D, 0xF8),
  6666. DefaultDuration: Uint8Array.of(0x23, 0xE3, 0x83),
  6667. DefaultDecodedFieldDuration: Uint8Array.of(0x23, 0x4E, 0x7A),
  6668. MaxBlockAdditionID: Uint8Array.of(0x55, 0xEE),
  6669. Name: Uint8Array.of(0x53, 0x6E),
  6670. Language: Uint8Array.of(0x22, 0xB5, 0x9C),
  6671. CodecID: Uint8Array.of(0x86),
  6672. CodecPrivate: Uint8Array.of(0x63, 0xA2),
  6673. CodecName: Uint8Array.of(0x25, 0x86, 0x88),
  6674. AttachmentLink: Uint8Array.of(0x74, 0x46),
  6675. CodecDecodeAll: Uint8Array.of(0xAA),
  6676. TrackOverlay: Uint8Array.of(0x6F, 0xAB),
  6677. CodecDelay: Uint8Array.of(0x56, 0xAA),
  6678. SeekPreRoll: Uint8Array.of(0x56, 0xBB),
  6679. TrackTranslate: Uint8Array.of(0x66, 0x24),
  6680. TrackTranslateEditionUID: Uint8Array.of(0x66, 0xFC),
  6681. TrackTranslateCodec: Uint8Array.of(0x66, 0xBF),
  6682. TrackTranslateTrackID: Uint8Array.of(0x66, 0xA5),
  6683. Video: Uint8Array.of(0xE0),
  6684. FlagInterlaced: Uint8Array.of(0x9A),
  6685. FieldOrder: Uint8Array.of(0x9D),
  6686. StereoMode: Uint8Array.of(0x53, 0xB8),
  6687. AlphaMode: Uint8Array.of(0x53, 0xC0),
  6688. PixelWidth: Uint8Array.of(0xB0),
  6689. PixelHeight: Uint8Array.of(0xBA),
  6690. PixelCropBottom: Uint8Array.of(0x54, 0xAA),
  6691. PixelCropTop: Uint8Array.of(0x54, 0xBB),
  6692. PixelCropLeft: Uint8Array.of(0x54, 0xCC),
  6693. PixelCropRight: Uint8Array.of(0x54, 0xDD),
  6694. DisplayWidth: Uint8Array.of(0x54, 0xB0),
  6695. DisplayHeight: Uint8Array.of(0x54, 0xBA),
  6696. DisplayUnit: Uint8Array.of(0x54, 0xB2),
  6697. AspectRatioType: Uint8Array.of(0x54, 0xB3),
  6698. ColourSpace: Uint8Array.of(0x2E, 0xB5, 0x24),
  6699. Colour: Uint8Array.of(0x55, 0xB0),
  6700. MatrixCoefficients: Uint8Array.of(0x55, 0xB1),
  6701. BitsPerChannel: Uint8Array.of(0x55, 0xB2),
  6702. ChromaSubsamplingHorz: Uint8Array.of(0x55, 0xB3),
  6703. ChromaSubsamplingVert: Uint8Array.of(0x55, 0xB4),
  6704. CbSubsamplingHorz: Uint8Array.of(0x55, 0xB5),
  6705. CbSubsamplingVert: Uint8Array.of(0x55, 0xB6),
  6706. ChromaSitingHorz: Uint8Array.of(0x55, 0xB7),
  6707. ChromaSitingVert: Uint8Array.of(0x55, 0xB8),
  6708. Range: Uint8Array.of(0x55, 0xB9),
  6709. TransferCharacteristics: Uint8Array.of(0x55, 0xBA),
  6710. Primaries: Uint8Array.of(0x55, 0xBB),
  6711. MaxCLL: Uint8Array.of(0x55, 0xBC),
  6712. MaxFALL: Uint8Array.of(0x55, 0xBD),
  6713. MasteringMetadata: Uint8Array.of(0x55, 0xD0),
  6714. PrimaryRChromaticityX: Uint8Array.of(0x55, 0xD1),
  6715. PrimaryRChromaticityY: Uint8Array.of(0x55, 0xD2),
  6716. PrimaryGChromaticityX: Uint8Array.of(0x55, 0xD3),
  6717. PrimaryGChromaticityY: Uint8Array.of(0x55, 0xD4),
  6718. PrimaryBChromaticityX: Uint8Array.of(0x55, 0xD5),
  6719. PrimaryBChromaticityY: Uint8Array.of(0x55, 0xD6),
  6720. WhitePointChromaticityX: Uint8Array.of(0x55, 0xD7),
  6721. WhitePointChromaticityY: Uint8Array.of(0x55, 0xD8),
  6722. LuminanceMax: Uint8Array.of(0x55, 0xD9),
  6723. LuminanceMin: Uint8Array.of(0x55, 0xDA),
  6724. Audio: Uint8Array.of(0xE1),
  6725. SamplingFrequency: Uint8Array.of(0xB5),
  6726. OutputSamplingFrequency: Uint8Array.of(0x78, 0xB5),
  6727. Channels: Uint8Array.of(0x9F),
  6728. BitDepth: Uint8Array.of(0x62, 0x64),
  6729. TrackOperation: Uint8Array.of(0xE2),
  6730. TrackCombinePlanes: Uint8Array.of(0xE3),
  6731. TrackPlane: Uint8Array.of(0xE4),
  6732. TrackPlaneUID: Uint8Array.of(0xE5),
  6733. TrackPlaneType: Uint8Array.of(0xE6),
  6734. TrackJoinBlocks: Uint8Array.of(0xE9),
  6735. TrackJoinUID: Uint8Array.of(0xED),
  6736. ContentEncodings: Uint8Array.of(0x6D, 0x80),
  6737. ContentEncoding: Uint8Array.of(0x62, 0x40),
  6738. ContentEncodingOrder: Uint8Array.of(0x50, 0x31),
  6739. ContentEncodingScope: Uint8Array.of(0x50, 0x32),
  6740. ContentEncodingType: Uint8Array.of(0x50, 0x33),
  6741. ContentCompression: Uint8Array.of(0x50, 0x34),
  6742. ContentCompAlgo: Uint8Array.of(0x42, 0x54),
  6743. ContentCompSettings: Uint8Array.of(0x42, 0x55),
  6744. ContentEncryption: Uint8Array.of(0x50, 0x35),
  6745. ContentEncAlgo: Uint8Array.of(0x47, 0xE1),
  6746. ContentEncKeyID: Uint8Array.of(0x47, 0xE2),
  6747. ContentSignature: Uint8Array.of(0x47, 0xE3),
  6748. ContentSigKeyID: Uint8Array.of(0x47, 0xE4),
  6749. ContentSigAlgo: Uint8Array.of(0x47, 0xE5),
  6750. ContentSigHashAlgo: Uint8Array.of(0x47, 0xE6),
  6751. Cues: Uint8Array.of(0x1C, 0x53, 0xBB, 0x6B),
  6752. CuePoint: Uint8Array.of(0xBB),
  6753. CueTime: Uint8Array.of(0xB3),
  6754. CueTrackPositions: Uint8Array.of(0xB7),
  6755. CueTrack: Uint8Array.of(0xF7),
  6756. CueClusterPosition: Uint8Array.of(0xF1),
  6757. CueRelativePosition: Uint8Array.of(0xF0),
  6758. CueDuration: Uint8Array.of(0xB2),
  6759. CueBlockNumber: Uint8Array.of(0x53, 0x78),
  6760. CueCodecState: Uint8Array.of(0xEA),
  6761. CueReference: Uint8Array.of(0xDB),
  6762. CueRefTime: Uint8Array.of(0x96),
  6763. Attachments: Uint8Array.of(0x19, 0x41, 0xA4, 0x69),
  6764. AttachedFile: Uint8Array.of(0x61, 0xA7),
  6765. FileDescription: Uint8Array.of(0x46, 0x7E),
  6766. FileName: Uint8Array.of(0x46, 0x6E),
  6767. FileMimeType: Uint8Array.of(0x46, 0x60),
  6768. FileData: Uint8Array.of(0x46, 0x5C),
  6769. FileUID: Uint8Array.of(0x46, 0xAE),
  6770. Chapters: Uint8Array.of(0x10, 0x43, 0xA7, 0x70),
  6771. EditionEntry: Uint8Array.of(0x45, 0xB9),
  6772. EditionUID: Uint8Array.of(0x45, 0xBC),
  6773. EditionFlagHidden: Uint8Array.of(0x45, 0xBD),
  6774. EditionFlagDefault: Uint8Array.of(0x45, 0xDB),
  6775. EditionFlagOrdered: Uint8Array.of(0x45, 0xDD),
  6776. ChapterAtom: Uint8Array.of(0xB6),
  6777. ChapterUID: Uint8Array.of(0x73, 0xC4),
  6778. ChapterStringUID: Uint8Array.of(0x56, 0x54),
  6779. ChapterTimeStart: Uint8Array.of(0x91),
  6780. ChapterTimeEnd: Uint8Array.of(0x92),
  6781. ChapterFlagHidden: Uint8Array.of(0x98),
  6782. ChapterFlagEnabled: Uint8Array.of(0x45, 0x98),
  6783. ChapterSegmentUID: Uint8Array.of(0x6E, 0x67),
  6784. ChapterSegmentEditionUID: Uint8Array.of(0x6E, 0xBC),
  6785. ChapterPhysicalEquiv: Uint8Array.of(0x63, 0xC3),
  6786. ChapterTrack: Uint8Array.of(0x8F),
  6787. ChapterTrackNumber: Uint8Array.of(0x89),
  6788. ChapterDisplay: Uint8Array.of(0x80),
  6789. ChapString: Uint8Array.of(0x85),
  6790. ChapLanguage: Uint8Array.of(0x43, 0x7C),
  6791. ChapCountry: Uint8Array.of(0x43, 0x7E),
  6792. ChapProcess: Uint8Array.of(0x69, 0x44),
  6793. ChapProcessCodecID: Uint8Array.of(0x69, 0x55),
  6794. ChapProcessPrivate: Uint8Array.of(0x45, 0x0D),
  6795. ChapProcessCommand: Uint8Array.of(0x69, 0x11),
  6796. ChapProcessTime: Uint8Array.of(0x69, 0x22),
  6797. ChapProcessData: Uint8Array.of(0x69, 0x33),
  6798. Tags: Uint8Array.of(0x12, 0x54, 0xC3, 0x67),
  6799. Tag: Uint8Array.of(0x73, 0x73),
  6800. Targets: Uint8Array.of(0x63, 0xC0),
  6801. TargetTypeValue: Uint8Array.of(0x68, 0xCA),
  6802. TargetType: Uint8Array.of(0x63, 0xCA),
  6803. TagTrackUID: Uint8Array.of(0x63, 0xC5),
  6804. TagEditionUID: Uint8Array.of(0x63, 0xC9),
  6805. TagChapterUID: Uint8Array.of(0x63, 0xC4),
  6806. TagAttachmentUID: Uint8Array.of(0x63, 0xC6),
  6807. SimpleTag: Uint8Array.of(0x67, 0xC8),
  6808. TagName: Uint8Array.of(0x45, 0xA3),
  6809. TagLanguage: Uint8Array.of(0x44, 0x7A),
  6810. TagDefault: Uint8Array.of(0x44, 0x84),
  6811. TagString: Uint8Array.of(0x44, 0x87),
  6812. TagBinary: Uint8Array.of(0x44, 0x85),
  6813. };
  6814.  
  6815.  
  6816.  
  6817. var EBML = /*#__PURE__*/Object.freeze({
  6818. Value: Value,
  6819. Element: Element,
  6820. bytes: bytes,
  6821. number: number,
  6822. vintEncodedNumber: vintEncodedNumber,
  6823. int16: int16,
  6824. float: float,
  6825. string: string,
  6826. element: element,
  6827. unknownSizeElement: unknownSizeElement,
  6828. build: build,
  6829. getEBMLByteLength: getEBMLByteLength,
  6830. UNKNOWN_SIZE: UNKNOWN_SIZE,
  6831. vintEncode: vintEncode,
  6832. getSizeMask: getSizeMask,
  6833. ID: ID,
  6834. numberToByteArray: numberToByteArray,
  6835. stringToByteArray: stringToByteArray,
  6836. getNumberByteLength: getNumberByteLength,
  6837. int16Bit: int16Bit,
  6838. float32bit: float32bit,
  6839. dumpBytes: dumpBytes
  6840. });
  6841.  
  6842. /***
  6843. * The EMBL builder is from simple-ebml-builder
  6844. *
  6845. * Copyright 2017 ryiwamoto
  6846. *
  6847. * @author ryiwamoto, qli5
  6848. *
  6849. * Permission is hereby granted, free of charge, to any person obtaining
  6850. * a copy of this software and associated documentation files (the
  6851. * "Software"), to deal in the Software without restriction, including
  6852. * without limitation the rights to use, copy, modify, merge, publish,
  6853. * distribute, sublicense, and/or sell copies of the Software, and to
  6854. * permit persons to whom the Software is furnished to do so, subject
  6855. * to the following conditions:
  6856. *
  6857. * The above copyright notice and this permission notice shall be
  6858. * included in all copies or substantial portions of the Software.
  6859. *
  6860. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  6861. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6862. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  6863. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  6864. * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  6865. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  6866. * DEALINGS IN THE SOFTWARE.
  6867. */
  6868.  
  6869. /***
  6870. * Copyright (C) 2018 Qli5. All Rights Reserved.
  6871. *
  6872. * @author qli5 <goodlq11[at](163|gmail).com>
  6873. *
  6874. * This Source Code Form is subject to the terms of the Mozilla Public
  6875. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6876. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6877. */
  6878.  
  6879. class MKV {
  6880. constructor(config) {
  6881. this.min = true;
  6882. this.onprogress = null;
  6883. Object.assign(this, config);
  6884. this.segmentUID = MKV.randomBytes(16);
  6885. this.trackUIDBase = Math.trunc(Math.random() * 2 ** 16);
  6886. this.trackMetadata = { h264: null, aac: null, ass: null };
  6887. this.duration = 0;
  6888. this.blocks = { h264: [], aac: [], ass: [] };
  6889. }
  6890.  
  6891. static randomBytes(num) {
  6892. return Array.from(new Array(num), () => Math.trunc(Math.random() * 256));
  6893. }
  6894.  
  6895. static textToMS(str) {
  6896. const [, h, mm, ss, ms10] = str.match(/(\\d+):(\\d+):(\\d+).(\\d+)/);
  6897. return h * 3600000 + mm * 60000 + ss * 1000 + ms10 * 10;
  6898. }
  6899.  
  6900. static mimeToCodecID(str) {
  6901. if (str.startsWith('avc1')) {
  6902. return 'V_MPEG4/ISO/AVC';
  6903. }
  6904. else if (str.startsWith('mp4a')) {
  6905. return 'A_AAC';
  6906. }
  6907. else {
  6908. throw new Error(\`MKVRemuxer: unknown codec \${str}\`);
  6909. }
  6910. }
  6911.  
  6912. static uint8ArrayConcat(...array) {
  6913. // if (Array.isArray(array[0])) array = array[0];
  6914. if (array.length == 1) return array[0];
  6915. if (typeof Buffer != 'undefined') return Buffer.concat(array);
  6916. const ret = new Uint8Array(array.reduce((i, j) => i + j.byteLength, 0));
  6917. let length = 0;
  6918. for (let e of array) {
  6919. ret.set(e, length);
  6920. length += e.byteLength;
  6921. }
  6922. return ret;
  6923. }
  6924.  
  6925. addH264Metadata(h264) {
  6926. this.trackMetadata.h264 = {
  6927. codecId: MKV.mimeToCodecID(h264.codec),
  6928. codecPrivate: h264.avcc,
  6929. defaultDuration: h264.refSampleDuration * 1000000,
  6930. pixelWidth: h264.codecWidth,
  6931. pixelHeight: h264.codecHeight,
  6932. displayWidth: h264.presentWidth,
  6933. displayHeight: h264.presentHeight
  6934. };
  6935. this.duration = Math.max(this.duration, h264.duration);
  6936. }
  6937.  
  6938. addAACMetadata(aac) {
  6939. this.trackMetadata.aac = {
  6940. codecId: MKV.mimeToCodecID(aac.originalCodec),
  6941. codecPrivate: aac.configRaw,
  6942. defaultDuration: aac.refSampleDuration * 1000000,
  6943. samplingFrequence: aac.audioSampleRate,
  6944. channels: aac.channelCount
  6945. };
  6946. this.duration = Math.max(this.duration, aac.duration);
  6947. }
  6948.  
  6949. addASSMetadata(ass) {
  6950. this.trackMetadata.ass = {
  6951. codecId: 'S_TEXT/ASS',
  6952. codecPrivate: new _TextEncoder().encode(ass.header)
  6953. };
  6954. }
  6955.  
  6956. addH264Stream(h264) {
  6957. this.blocks.h264 = this.blocks.h264.concat(h264.samples.map(e => ({
  6958. track: 1,
  6959. frame: MKV.uint8ArrayConcat(...e.units.map(i => i.data)),
  6960. isKeyframe: e.isKeyframe,
  6961. discardable: Boolean(e.refIdc),
  6962. timestamp: e.pts,
  6963. simple: true,
  6964. })));
  6965. }
  6966.  
  6967. addAACStream(aac) {
  6968. this.blocks.aac = this.blocks.aac.concat(aac.samples.map(e => ({
  6969. track: 2,
  6970. frame: e.unit,
  6971. timestamp: e.pts,
  6972. simple: true,
  6973. })));
  6974. }
  6975.  
  6976. addASSStream(ass) {
  6977. this.blocks.ass = this.blocks.ass.concat(ass.lines.map((e, i) => ({
  6978. track: 3,
  6979. frame: new _TextEncoder().encode(\`\${i},\${e['Layer'] || ''},\${e['Style'] || ''},\${e['Name'] || ''},\${e['MarginL'] || ''},\${e['MarginR'] || ''},\${e['MarginV'] || ''},\${e['Effect'] || ''},\${e['Text'] || ''}\`),
  6980. timestamp: MKV.textToMS(e['Start']),
  6981. duration: MKV.textToMS(e['End']) - MKV.textToMS(e['Start']),
  6982. })));
  6983. }
  6984.  
  6985. build() {
  6986. return new _Blob([
  6987. this.buildHeader(),
  6988. this.buildBody()
  6989. ]);
  6990. }
  6991.  
  6992. buildHeader() {
  6993. return new _Blob([EBML.build(EBML.element(EBML.ID.EBML, [
  6994. EBML.element(EBML.ID.EBMLVersion, EBML.number(1)),
  6995. EBML.element(EBML.ID.EBMLReadVersion, EBML.number(1)),
  6996. EBML.element(EBML.ID.EBMLMaxIDLength, EBML.number(4)),
  6997. EBML.element(EBML.ID.EBMLMaxSizeLength, EBML.number(8)),
  6998. EBML.element(EBML.ID.DocType, EBML.string('matroska')),
  6999. EBML.element(EBML.ID.DocTypeVersion, EBML.number(4)),
  7000. EBML.element(EBML.ID.DocTypeReadVersion, EBML.number(2)),
  7001. ]))]);
  7002. }
  7003.  
  7004. buildBody() {
  7005. if (this.min) {
  7006. return new _Blob([EBML.build(EBML.element(EBML.ID.Segment, [
  7007. this.getSegmentInfo(),
  7008. this.getTracks(),
  7009. ...this.getClusterArray()
  7010. ]))]);
  7011. }
  7012. else {
  7013. return new _Blob([EBML.build(EBML.element(EBML.ID.Segment, [
  7014. this.getSeekHead(),
  7015. this.getVoid(4100),
  7016. this.getSegmentInfo(),
  7017. this.getTracks(),
  7018. this.getVoid(1100),
  7019. ...this.getClusterArray()
  7020. ]))]);
  7021. }
  7022. }
  7023.  
  7024. getSeekHead() {
  7025. return EBML.element(EBML.ID.SeekHead, [
  7026. EBML.element(EBML.ID.Seek, [
  7027. EBML.element(EBML.ID.SeekID, EBML.bytes(EBML.ID.Info)),
  7028. EBML.element(EBML.ID.SeekPosition, EBML.number(4050))
  7029. ]),
  7030. EBML.element(EBML.ID.Seek, [
  7031. EBML.element(EBML.ID.SeekID, EBML.bytes(EBML.ID.Tracks)),
  7032. EBML.element(EBML.ID.SeekPosition, EBML.number(4200))
  7033. ]),
  7034. ]);
  7035. }
  7036.  
  7037. getVoid(length = 2000) {
  7038. return EBML.element(EBML.ID.Void, EBML.bytes(new Uint8Array(length)));
  7039. }
  7040.  
  7041. getSegmentInfo() {
  7042. return EBML.element(EBML.ID.Info, [
  7043. EBML.element(EBML.ID.TimecodeScale, EBML.number(1000000)),
  7044. EBML.element(EBML.ID.MuxingApp, EBML.string('flv.js + assparser_qli5 -> simple-ebml-builder')),
  7045. EBML.element(EBML.ID.WritingApp, EBML.string('flvass2mkv.js by qli5')),
  7046. EBML.element(EBML.ID.Duration, EBML.float(this.duration)),
  7047. EBML.element(EBML.ID.SegmentUID, EBML.bytes(this.segmentUID)),
  7048. ]);
  7049. }
  7050.  
  7051. getTracks() {
  7052. return EBML.element(EBML.ID.Tracks, [
  7053. this.getVideoTrackEntry(),
  7054. this.getAudioTrackEntry(),
  7055. this.getSubtitleTrackEntry()
  7056. ]);
  7057. }
  7058.  
  7059. getVideoTrackEntry() {
  7060. return EBML.element(EBML.ID.TrackEntry, [
  7061. EBML.element(EBML.ID.TrackNumber, EBML.number(1)),
  7062. EBML.element(EBML.ID.TrackUID, EBML.number(this.trackUIDBase + 1)),
  7063. EBML.element(EBML.ID.TrackType, EBML.number(0x01)),
  7064. EBML.element(EBML.ID.FlagLacing, EBML.number(0x00)),
  7065. EBML.element(EBML.ID.CodecID, EBML.string(this.trackMetadata.h264.codecId)),
  7066. EBML.element(EBML.ID.CodecPrivate, EBML.bytes(this.trackMetadata.h264.codecPrivate)),
  7067. EBML.element(EBML.ID.DefaultDuration, EBML.number(this.trackMetadata.h264.defaultDuration)),
  7068. EBML.element(EBML.ID.Language, EBML.string('und')),
  7069. EBML.element(EBML.ID.Video, [
  7070. EBML.element(EBML.ID.PixelWidth, EBML.number(this.trackMetadata.h264.pixelWidth)),
  7071. EBML.element(EBML.ID.PixelHeight, EBML.number(this.trackMetadata.h264.pixelHeight)),
  7072. EBML.element(EBML.ID.DisplayWidth, EBML.number(this.trackMetadata.h264.displayWidth)),
  7073. EBML.element(EBML.ID.DisplayHeight, EBML.number(this.trackMetadata.h264.displayHeight)),
  7074. ]),
  7075. ]);
  7076. }
  7077.  
  7078. getAudioTrackEntry() {
  7079. return EBML.element(EBML.ID.TrackEntry, [
  7080. EBML.element(EBML.ID.TrackNumber, EBML.number(2)),
  7081. EBML.element(EBML.ID.TrackUID, EBML.number(this.trackUIDBase + 2)),
  7082. EBML.element(EBML.ID.TrackType, EBML.number(0x02)),
  7083. EBML.element(EBML.ID.FlagLacing, EBML.number(0x00)),
  7084. EBML.element(EBML.ID.CodecID, EBML.string(this.trackMetadata.aac.codecId)),
  7085. EBML.element(EBML.ID.CodecPrivate, EBML.bytes(this.trackMetadata.aac.codecPrivate)),
  7086. EBML.element(EBML.ID.DefaultDuration, EBML.number(this.trackMetadata.aac.defaultDuration)),
  7087. EBML.element(EBML.ID.Language, EBML.string('und')),
  7088. EBML.element(EBML.ID.Audio, [
  7089. EBML.element(EBML.ID.SamplingFrequency, EBML.float(this.trackMetadata.aac.samplingFrequence)),
  7090. EBML.element(EBML.ID.Channels, EBML.number(this.trackMetadata.aac.channels)),
  7091. ]),
  7092. ]);
  7093. }
  7094.  
  7095. getSubtitleTrackEntry() {
  7096. return EBML.element(EBML.ID.TrackEntry, [
  7097. EBML.element(EBML.ID.TrackNumber, EBML.number(3)),
  7098. EBML.element(EBML.ID.TrackUID, EBML.number(this.trackUIDBase + 3)),
  7099. EBML.element(EBML.ID.TrackType, EBML.number(0x11)),
  7100. EBML.element(EBML.ID.FlagLacing, EBML.number(0x00)),
  7101. EBML.element(EBML.ID.CodecID, EBML.string(this.trackMetadata.ass.codecId)),
  7102. EBML.element(EBML.ID.CodecPrivate, EBML.bytes(this.trackMetadata.ass.codecPrivate)),
  7103. EBML.element(EBML.ID.Language, EBML.string('und')),
  7104. ]);
  7105. }
  7106.  
  7107. getClusterArray() {
  7108. // H264 codecState
  7109. this.blocks.h264[0].simple = false;
  7110. this.blocks.h264[0].codecState = this.trackMetadata.h264.codecPrivate;
  7111.  
  7112. let i = 0;
  7113. let j = 0;
  7114. let k = 0;
  7115. let clusterTimeCode = 0;
  7116. let clusterContent = [EBML.element(EBML.ID.Timecode, EBML.number(clusterTimeCode))];
  7117. let ret = [clusterContent];
  7118. const progressThrottler = Math.pow(2, Math.floor(Math.log(this.blocks.h264.length >> 7) / Math.log(2))) - 1;
  7119. for (i = 0; i < this.blocks.h264.length; i++) {
  7120. const e = this.blocks.h264[i];
  7121. for (; j < this.blocks.aac.length; j++) {
  7122. if (this.blocks.aac[j].timestamp < e.timestamp) {
  7123. clusterContent.push(this.getBlocks(this.blocks.aac[j], clusterTimeCode));
  7124. }
  7125. else {
  7126. break;
  7127. }
  7128. }
  7129. for (; k < this.blocks.ass.length; k++) {
  7130. if (this.blocks.ass[k].timestamp < e.timestamp) {
  7131. clusterContent.push(this.getBlocks(this.blocks.ass[k], clusterTimeCode));
  7132. }
  7133. else {
  7134. break;
  7135. }
  7136. }
  7137. if (e.isKeyframe/* || clusterContent.length > 72 */) {
  7138. // start new cluster
  7139. clusterTimeCode = e.timestamp;
  7140. clusterContent = [EBML.element(EBML.ID.Timecode, EBML.number(clusterTimeCode))];
  7141. ret.push(clusterContent);
  7142. }
  7143. clusterContent.push(this.getBlocks(e, clusterTimeCode));
  7144. if (this.onprogress && !(i & progressThrottler)) this.onprogress({ loaded: i, total: this.blocks.h264.length });
  7145. }
  7146. for (; j < this.blocks.aac.length; j++) clusterContent.push(this.getBlocks(this.blocks.aac[j], clusterTimeCode));
  7147. for (; k < this.blocks.ass.length; k++) clusterContent.push(this.getBlocks(this.blocks.ass[k], clusterTimeCode));
  7148. if (this.onprogress) this.onprogress({ loaded: i, total: this.blocks.h264.length });
  7149. if (ret[0].length == 1) ret.shift();
  7150. ret = ret.map(clusterContent => EBML.element(EBML.ID.Cluster, clusterContent));
  7151.  
  7152. return ret;
  7153. }
  7154.  
  7155. getBlocks(e, clusterTimeCode) {
  7156. if (e.simple) {
  7157. return EBML.element(EBML.ID.SimpleBlock, [
  7158. EBML.vintEncodedNumber(e.track),
  7159. EBML.int16(e.timestamp - clusterTimeCode),
  7160. EBML.bytes(e.isKeyframe ? [128] : [0]),
  7161. EBML.bytes(e.frame)
  7162. ]);
  7163. }
  7164. else {
  7165. let blockGroupContent = [EBML.element(EBML.ID.Block, [
  7166. EBML.vintEncodedNumber(e.track),
  7167. EBML.int16(e.timestamp - clusterTimeCode),
  7168. EBML.bytes([0]),
  7169. EBML.bytes(e.frame)
  7170. ])];
  7171. if (typeof e.duration != 'undefined') {
  7172. blockGroupContent.push(EBML.element(EBML.ID.BlockDuration, EBML.number(e.duration)));
  7173. }
  7174. if (typeof e.codecState != 'undefined') {
  7175. blockGroupContent.push(EBML.element(EBML.ID.CodecState, EBML.bytes(e.codecState)));
  7176. }
  7177. return EBML.element(EBML.ID.BlockGroup, blockGroupContent);
  7178. }
  7179. }
  7180. }
  7181.  
  7182. /***
  7183. * FLV + ASS => MKV transmuxer
  7184. * Demux FLV into H264 + AAC stream and ASS into line stream; then
  7185. * remux them into a MKV file.
  7186. *
  7187. * @author qli5 <goodlq11[at](163|gmail).com>
  7188. *
  7189. * This Source Code Form is subject to the terms of the Mozilla Public
  7190. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7191. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7192. *
  7193. * The FLV demuxer is from flv.js <https://github.com/Bilibili/flv.js/>
  7194. * by zheng qian <xqq@xqq.im>, licensed under Apache 2.0.
  7195. *
  7196. * The EMBL builder is from simple-ebml-builder
  7197. * <https://www.npmjs.com/package/simple-ebml-builder> by ryiwamoto,
  7198. * licensed under MIT.
  7199. */
  7200.  
  7201. const FLVASS2MKV = class {
  7202. constructor(config = {}) {
  7203. this.onflvprogress = null;
  7204. this.onassprogress = null;
  7205. this.onurlrevokesafe = null;
  7206. this.onfileload = null;
  7207. this.onmkvprogress = null;
  7208. this.onload = null;
  7209. Object.assign(this, config);
  7210. this.mkvConfig = { onprogress: this.onmkvprogress };
  7211. Object.assign(this.mkvConfig, config.mkvConfig);
  7212. }
  7213.  
  7214. /**
  7215. * Demux FLV into H264 + AAC stream and ASS into line stream; then
  7216. * remux them into a MKV file.
  7217. * @param {Blob|string|ArrayBuffer} flv
  7218. * @param {Blob|string|ArrayBuffer} ass
  7219. */
  7220. async build(flv = './samples/gen_case.flv', ass = './samples/gen_case.ass') {
  7221. // load flv and ass as arraybuffer
  7222. await Promise.all([
  7223. new Promise((r, j) => {
  7224. if (flv instanceof _Blob) {
  7225. const e = new FileReader();
  7226. e.onprogress = this.onflvprogress;
  7227. e.onload = () => r(flv = e.result);
  7228. e.onerror = j;
  7229. e.readAsArrayBuffer(flv);
  7230. }
  7231. else if (typeof flv == 'string') {
  7232. const e = new XMLHttpRequest();
  7233. e.responseType = 'arraybuffer';
  7234. e.onprogress = this.onflvprogress;
  7235. e.onload = () => r(flv = e.response);
  7236. e.onerror = j;
  7237. e.open('get', flv);
  7238. e.send();
  7239. flv = 2; // onurlrevokesafe
  7240. }
  7241. else if (flv instanceof ArrayBuffer) {
  7242. r(flv);
  7243. }
  7244. else {
  7245. j(new TypeError('flvass2mkv: flv {Blob|string|ArrayBuffer}'));
  7246. }
  7247. if (typeof ass != 'string' && this.onurlrevokesafe) this.onurlrevokesafe();
  7248. }),
  7249. new Promise((r, j) => {
  7250. if (ass instanceof _Blob) {
  7251. const e = new FileReader();
  7252. e.onprogress = this.onflvprogress;
  7253. e.onload = () => r(ass = e.result);
  7254. e.onerror = j;
  7255. e.readAsArrayBuffer(ass);
  7256. }
  7257. else if (typeof ass == 'string') {
  7258. const e = new XMLHttpRequest();
  7259. e.responseType = 'arraybuffer';
  7260. e.onprogress = this.onflvprogress;
  7261. e.onload = () => r(ass = e.response);
  7262. e.onerror = j;
  7263. e.open('get', ass);
  7264. e.send();
  7265. ass = 2; // onurlrevokesafe
  7266. }
  7267. else if (ass instanceof ArrayBuffer) {
  7268. r(ass);
  7269. }
  7270. else {
  7271. j(new TypeError('flvass2mkv: ass {Blob|string|ArrayBuffer}'));
  7272. }
  7273. if (typeof flv != 'string' && this.onurlrevokesafe) this.onurlrevokesafe();
  7274. }),
  7275. ]);
  7276. if (this.onfileload) this.onfileload();
  7277.  
  7278. const mkv = new MKV(this.mkvConfig);
  7279.  
  7280. const assParser = new ASS();
  7281. ass = assParser.parseFile(ass);
  7282. mkv.addASSMetadata(ass);
  7283. mkv.addASSStream(ass);
  7284.  
  7285. const flvProbeData = FLVDemuxer.probe(flv);
  7286. const flvDemuxer = new FLVDemuxer(flvProbeData);
  7287. let mediaInfo = null;
  7288. let h264 = null;
  7289. let aac = null;
  7290. flvDemuxer.onDataAvailable = (...array) => {
  7291. array.forEach(e => {
  7292. if (e.type == 'video') h264 = e;
  7293. else if (e.type == 'audio') aac = e;
  7294. else throw new Error(\`MKVRemuxer: unrecoginzed data type \${e.type}\`);
  7295. });
  7296. };
  7297. flvDemuxer.onMediaInfo = i => mediaInfo = i;
  7298. flvDemuxer.onTrackMetadata = (i, e) => {
  7299. if (i == 'video') mkv.addH264Metadata(e);
  7300. else if (i == 'audio') mkv.addAACMetadata(e);
  7301. else throw new Error(\`MKVRemuxer: unrecoginzed metadata type \${i}\`);
  7302. };
  7303. flvDemuxer.onError = e => { throw new Error(e); };
  7304. const finalOffset = flvDemuxer.parseChunks(flv, flvProbeData.dataOffset);
  7305. if (finalOffset != flv.byteLength) throw new Error('FLVDemuxer: unexpected EOF');
  7306. mkv.addH264Stream(h264);
  7307. mkv.addAACStream(aac);
  7308.  
  7309. const ret = mkv.build();
  7310. if (this.onload) this.onload(ret);
  7311. return ret;
  7312. }
  7313. };
  7314.  
  7315. // if nodejs then test
  7316. if (typeof window == 'undefined') {
  7317. if (require.main == module) {
  7318. (async () => {
  7319. const fs = require('fs');
  7320. const assFileName = process.argv.slice(1).find(e => e.includes('.ass')) || './samples/gen_case.ass';
  7321. const flvFileName = process.argv.slice(1).find(e => e.includes('.flv')) || './samples/gen_case.flv';
  7322. const assFile = fs.readFileSync(assFileName).buffer;
  7323. const flvFile = fs.readFileSync(flvFileName).buffer;
  7324. fs.writeFileSync('out.mkv', await new FLVASS2MKV({ onmkvprogress: console.log.bind(console) }).build(flvFile, assFile));
  7325. })();
  7326. }
  7327. }
  7328.  
  7329. return FLVASS2MKV;
  7330.  
  7331. }());
  7332. //# sourceMappingURL=index.js.map
  7333.  
  7334. </script>
  7335. <script>
  7336. const fileProgress = document.getElementById('fileProgress');
  7337. const mkvProgress = document.getElementById('mkvProgress');
  7338. const a = document.getElementById('a');
  7339. window.exec = async option => {
  7340. const defaultOption = {
  7341. onflvprogress: ({ loaded, total }) => {
  7342. fileProgress.value = loaded;
  7343. fileProgress.max = total;
  7344. },
  7345. onfileload: () => {
  7346. console.timeEnd('file');
  7347. console.time('flvass2mkv');
  7348. },
  7349. onmkvprogress: ({ loaded, total }) => {
  7350. mkvProgress.value = loaded;
  7351. mkvProgress.max = total;
  7352. },
  7353. name: 'merged.mkv',
  7354. };
  7355. option = Object.assign(defaultOption, option);
  7356. a.download = a.textContent = option.name;
  7357. console.time('file');
  7358. const mkv = await new FLVASS2MKV(option).build(option.flv, option.ass);
  7359. console.timeEnd('flvass2mkv');
  7360. return a.href = URL.createObjectURL(mkv);
  7361. };
  7362. </script>
  7363. </body>
  7364.  
  7365. </html>
  7366. `;
  7367.  
  7368. /***
  7369. * Copyright (C) 2018 Qli5. All Rights Reserved.
  7370. *
  7371. * @author qli5 <goodlq11[at](163|gmail).com>
  7372. *
  7373. * This Source Code Form is subject to the terms of the Mozilla Public
  7374. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7375. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7376. */
  7377.  
  7378. class MKVTransmuxer {
  7379. constructor(option) {
  7380. this.workerWin = null;
  7381. this.option = option;
  7382. }
  7383.  
  7384. /**
  7385. * FLV + ASS => MKV entry point
  7386. * @param {Blob|string|ArrayBuffer} flv
  7387. * @param {Blob|string|ArrayBuffer} ass
  7388. * @param {string=} name
  7389. */
  7390. exec(flv, ass, name) {
  7391. // 1. Allocate for a new window
  7392. if (!this.workerWin) this.workerWin = top.open('', undefined, ' ');
  7393.  
  7394. // 2. Inject scripts
  7395. this.workerWin.document.write(embeddedHTML);
  7396. this.workerWin.document.close();
  7397.  
  7398. // 3. Invoke exec
  7399. if (!(this.option instanceof Object)) this.option = null;
  7400. this.workerWin.exec(Object.assign({}, this.option, { flv, ass, name }));
  7401. URL.revokeObjectURL(flv);
  7402. URL.revokeObjectURL(ass);
  7403.  
  7404. // 4. Free parent window
  7405. // if (top.confirm('MKV打包中……要关掉这个窗口,释放内存吗?'))
  7406. top.location = 'about:blank';
  7407. }
  7408. }
  7409.  
  7410. /***
  7411. * Copyright (C) 2018 Qli5. All Rights Reserved.
  7412. *
  7413. * @author qli5 <goodlq11[at](163|gmail).com>
  7414. *
  7415. * This Source Code Form is subject to the terms of the Mozilla Public
  7416. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7417. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7418. */
  7419.  
  7420. class UI {
  7421. constructor(twin, option = UI.optionDefaults) {
  7422. this.twin = twin;
  7423. this.option = option;
  7424.  
  7425. this.destroy = new HookedFunction();
  7426. this.dom = {};
  7427. this.cidSessionDestroy = new HookedFunction();
  7428. this.cidSessionDom = {};
  7429.  
  7430. this.destroy.addCallback(this.cidSessionDestroy.bind(this));
  7431.  
  7432. this.destroy.addCallback(() => {
  7433. Object.values(this.dom).forEach(e => e.remove());
  7434. this.dom = {};
  7435. });
  7436. this.cidSessionDestroy.addCallback(() => {
  7437. Object.values(this.cidSessionDom).forEach(e => e.remove());
  7438. this.cidSessionDom = {};
  7439. });
  7440.  
  7441. this.styleClearance();
  7442. }
  7443.  
  7444. styleClearance() {
  7445. let ret = `
  7446. .bilibili-player-context-menu-container.black ul.bilitwin li.context-menu-function > a:hover {
  7447. background: rgba(255,255,255,.12);
  7448. transition: all .3s ease-in-out;
  7449. cursor: pointer;
  7450. }
  7451. `;
  7452. if (top.getComputedStyle(top.document.body).color != 'rgb(34, 34, 34)') ret += `
  7453. .bilitwin a {
  7454. cursor: pointer;
  7455. color: #00a1d6;
  7456. }
  7457.  
  7458. .bilitwin a:hover {
  7459. color: #f25d8e;
  7460. }
  7461.  
  7462. .bilitwin button {
  7463. color: #fff;
  7464. cursor: pointer;
  7465. text-align: center;
  7466. border-radius: 4px;
  7467. background-color: #00a1d6;
  7468. vertical-align: middle;
  7469. border: 1px solid #00a1d6;
  7470. transition: .1s;
  7471. transition-property: background-color,border,color;
  7472. user-select: none;
  7473. }
  7474.  
  7475. .bilitwin button:hover {
  7476. background-color: #00b5e5;
  7477. border-color: #00b5e5;
  7478. }
  7479.  
  7480. .bilitwin progress {
  7481. -webkit-appearance: progress-bar;
  7482. -moz-appearance: progress-bar;
  7483. appearance: progress-bar;
  7484. }
  7485.  
  7486. .bilitwin input[type="checkbox" i] {
  7487. -webkit-appearance: checkbox;
  7488. -moz-appearance: checkbox;
  7489. appearance: checkbox;
  7490. }
  7491. `;
  7492.  
  7493. const style = document.createElement('style');
  7494. style.type = 'text/css';
  7495. style.textContent = ret;
  7496. document.head.append(style);
  7497.  
  7498. return this.dom.style = style;
  7499. }
  7500.  
  7501. cidSessionRender() {
  7502. this.buildTitle();
  7503.  
  7504. if (this.option.title) this.appendTitle();
  7505. if (this.option.menu) this.appendMenu();
  7506. }
  7507.  
  7508. // Title Append
  7509. buildTitle(monkey = this.twin.monkey) {
  7510. // 1. build flvA, mp4A, assA
  7511. const fontSize = '15px';
  7512. const flvA = document.createElement('a');
  7513. flvA.style.fontSize = fontSize;
  7514. flvA.textContent = '\u8D85\u6E05FLV';
  7515. const mp4A = document.createElement('a');
  7516. mp4A.style.fontSize = fontSize;
  7517. mp4A.textContent = '\u539F\u751FMP4';
  7518. const assA = document.createElement('a');
  7519.  
  7520. // 1.1 build flvA
  7521. assA.style.fontSize = fontSize;
  7522. assA.textContent = '\u5F39\u5E55ASS';
  7523. flvA.onmouseover = async () => {
  7524. // 1.1.1 give processing hint
  7525. flvA.textContent = '正在FLV';
  7526. flvA.onmouseover = null;
  7527.  
  7528. // 1.1.2 query flv
  7529. const href = await monkey.queryInfo('flv');
  7530. if (href == 'does_not_exist') return flvA.textContent = '没有FLV';
  7531.  
  7532. // 1.1.3 display flv
  7533. flvA.textContent = '超清FLV';
  7534. flvA.onclick = () => this.displayFLVDiv();
  7535. };
  7536.  
  7537. // 1.2 build mp4A
  7538. mp4A.onmouseover = async () => {
  7539. // 1.2.1 give processing hint
  7540. mp4A.textContent = '正在MP4';
  7541. mp4A.onmouseover = null;
  7542. if (this.option.autoDanmaku) {
  7543. await assA.onmouseover();
  7544. mp4A.onclick = () => assA.click();
  7545. }
  7546.  
  7547. // 1.2.2 query flv
  7548. let href = await monkey.queryInfo('mp4');
  7549. if (href == 'does_not_exist') return mp4A.textContent = '没有MP4';
  7550.  
  7551. // 1.2.3 response mp4
  7552. mp4A.href = href;
  7553. mp4A.textContent = '原生MP4';
  7554. mp4A.download = '';
  7555. mp4A.referrerPolicy = 'origin';
  7556. };
  7557.  
  7558. // 1.3 build assA
  7559. assA.onmouseover = async () => {
  7560. // 1.3.1 give processing hint
  7561. assA.textContent = '正在ASS';
  7562. assA.onmouseover = null;
  7563.  
  7564. // 1.3.2 query flv
  7565. assA.href = await monkey.queryInfo('ass');
  7566.  
  7567. // 1.3.3 response mp4
  7568. assA.textContent = '弹幕ASS';
  7569. if (monkey.mp4 && monkey.mp4.match) {
  7570. assA.download = monkey.mp4.match(/\d(?:\d|-|hd)*(?=\.mp4)/)[0] + '.ass';
  7571. } else {
  7572. assA.download = monkey.cid + '.ass';
  7573. }
  7574. };
  7575.  
  7576. // 2. save to cache
  7577. Object.assign(this.cidSessionDom, { flvA, mp4A, assA });
  7578. return this.cidSessionDom;
  7579. }
  7580.  
  7581. appendTitle({ flvA, mp4A, assA } = this.cidSessionDom) {
  7582. // 1. build div
  7583. const div = document.createElement('div');
  7584.  
  7585. // 2. append to title
  7586. div.addEventListener('click', e => e.stopPropagation());
  7587. div.style.float = 'left';
  7588. div.style.clear = 'left';
  7589. div.className = 'bilitwin';
  7590. div.append(...[flvA, ' ', mp4A, ' ', assA]);
  7591. const tminfo = document.querySelector('div.tminfo') || document.querySelector('div.info-second');
  7592. tminfo.style.float = 'none';
  7593. tminfo.style.marginLeft = '185px';
  7594. tminfo.parentElement.insertBefore(div, tminfo);
  7595.  
  7596. // 3. save to cache
  7597. this.cidSessionDom.titleDiv = div;
  7598.  
  7599. return div;
  7600. }
  7601.  
  7602. buildFLVDiv(monkey = this.twin.monkey, flvs = monkey.flvs, cache = monkey.cache) {
  7603. // 1. build flv splits
  7604. const flvTrs = flvs.map((href, index) => {
  7605. const tr = document.createElement('tr');
  7606. {
  7607. const td1 = document.createElement('td');
  7608. const a1 = document.createElement('a');
  7609. a1.href = href;
  7610. a1.textContent = `FLV分段 ${index + 1}`;
  7611. td1.append(a1);
  7612. tr.append(td1);
  7613. const td2 = document.createElement('td');
  7614. const a2 = document.createElement('a');
  7615.  
  7616. a2.onclick = e => this.downloadFLV({
  7617. monkey,
  7618. index,
  7619. a: e.target,
  7620. progress: tr.children[2].children[0]
  7621. });
  7622.  
  7623. a2.textContent = '\u7F13\u5B58\u672C\u6BB5';
  7624. td2.append(a2);
  7625. tr.append(td2);
  7626. const td3 = document.createElement('td');
  7627. const progress1 = document.createElement('progress');
  7628. progress1.setAttribute('value', '0');
  7629. progress1.setAttribute('max', '100');
  7630. progress1.textContent = '\u8FDB\u5EA6\u6761';
  7631. td3.append(progress1);
  7632. tr.append(td3);
  7633. }
  7634. return tr;
  7635. });
  7636.  
  7637. // 2. build exporter a
  7638. const exporterA = document.createElement('a');
  7639. if (this.option.aria2) {
  7640. exporterA.textContent = '导出Aria2';
  7641. exporterA.download = 'bilitwin.session';
  7642. exporterA.href = URL.createObjectURL(new Blob([Exporter.exportAria2(flvs, top.location.origin)]));
  7643. } else if (this.option.aria2RPC) {
  7644. exporterA.textContent = '发送Aria2 RPC';
  7645. exporterA.onclick = () => Exporter.sendToAria2RPC(flvs, top.location.origin);
  7646. } else if (this.option.m3u8) {
  7647. exporterA.textContent = '导出m3u8';
  7648. exporterA.download = 'bilitwin.m3u8';
  7649. exporterA.href = URL.createObjectURL(new Blob([Exporter.exportM3U8(flvs, top.location.origin, top.navigator.userAgent)]));
  7650. } else if (this.option.clipboard) {
  7651. exporterA.textContent = '全部复制到剪贴板';
  7652. exporterA.onclick = () => Exporter.copyToClipboard(flvs.join('\n'));
  7653. } else {
  7654. exporterA.textContent = '导出IDM';
  7655. exporterA.download = 'bilitwin.ef2';
  7656. exporterA.href = URL.createObjectURL(new Blob([Exporter.exportIDM(flvs, top.location.origin)]));
  7657. }
  7658.  
  7659. // 3. build body table
  7660. const table = document.createElement('table');
  7661. table.style.width = '100%';
  7662. table.style.lineHeight = '2em';
  7663. table.append(...flvTrs, (() => {
  7664. const tr1 = document.createElement('tr');
  7665. const td1 = document.createElement('td');
  7666. td1.append(...[exporterA]);
  7667. tr1.append(td1);
  7668. const td2 = document.createElement('td');
  7669. const a1 = document.createElement('a');
  7670.  
  7671. a1.onclick = e => this.downloadAllFLVs({
  7672. a: e.target,
  7673. monkey, table
  7674. });
  7675.  
  7676. a1.textContent = '\u7F13\u5B58\u5168\u90E8+\u81EA\u52A8\u5408\u5E76';
  7677. td2.append(a1);
  7678. tr1.append(td2);
  7679. const td3 = document.createElement('td');
  7680. const progress1 = document.createElement('progress');
  7681. progress1.setAttribute('value', '0');
  7682. progress1.setAttribute('max', flvs.length + 1);
  7683. progress1.textContent = '\u8FDB\u5EA6\u6761';
  7684. td3.append(progress1);
  7685. tr1.append(td3);
  7686. return tr1;
  7687. })(), (() => {
  7688. const tr1 = document.createElement('tr');
  7689. const td1 = document.createElement('td');
  7690. td1.colSpan = '3';
  7691. td1.textContent = '\u5408\u5E76\u529F\u80FD\u63A8\u8350\u914D\u7F6E\uFF1A\u81F3\u5C118G RAM\u3002\u628A\u81EA\u5DF1\u4E0B\u8F7D\u7684\u5206\u6BB5FLV\u62D6\u52A8\u5230\u8FD9\u91CC\uFF0C\u4E5F\u53EF\u4EE5\u5408\u5E76\u54E6~';
  7692. tr1.append(td1);
  7693. return tr1;
  7694. })(), cache ? (() => {
  7695. const tr1 = document.createElement('tr');
  7696. const td1 = document.createElement('td');
  7697. td1.colSpan = '3';
  7698. td1.textContent = '\u4E0B\u8F7D\u7684\u7F13\u5B58\u5206\u6BB5\u4F1A\u6682\u65F6\u505C\u7559\u5728\u7535\u8111\u91CC\uFF0C\u8FC7\u4E00\u6BB5\u65F6\u95F4\u4F1A\u81EA\u52A8\u6D88\u5931\u3002\u5EFA\u8BAE\u53EA\u5F00\u4E00\u4E2A\u6807\u7B7E\u9875\u3002';
  7699. tr1.append(td1);
  7700. return tr1;
  7701. })() : (() => {
  7702. const tr1 = document.createElement('tr');
  7703. const td1 = document.createElement('td');
  7704. td1.colSpan = '3';
  7705. td1.textContent = '\u5EFA\u8BAE\u53EA\u5F00\u4E00\u4E2A\u6807\u7B7E\u9875\u3002\u5173\u6389\u6807\u7B7E\u9875\u540E\uFF0C\u7F13\u5B58\u5C31\u4F1A\u88AB\u6E05\u7406\u3002\u522B\u5FD8\u4E86\u53E6\u5B58\u4E3A\uFF01';
  7706. tr1.append(td1);
  7707. return tr1;
  7708. })(), (() => {
  7709. const tr1 = document.createElement('tr');
  7710. const td1 = document.createElement('td');
  7711. td1.colSpan = '3';
  7712. this.displayQuota.bind(this)(td1);
  7713. tr1.append(td1);
  7714. return tr1;
  7715. })());
  7716. this.cidSessionDom.flvTable = table;
  7717.  
  7718. // 4. build container dlv
  7719. const div = UI.genDiv();
  7720. div.ondragenter = div.ondragover = e => UI.allowDrag(e);
  7721. div.ondrop = async e => {
  7722. // 4.1 allow drag
  7723. UI.allowDrag(e);
  7724.  
  7725. // 4.2 sort files if possible
  7726. const files = Array.from(e.dataTransfer.files);
  7727. if (files.every(e => e.name.search(/\d+-\d+(?:\d|-|hd)*\.flv/) != -1)) {
  7728. files.sort((a, b) => a.name.match(/\d+-(\d+)(?:\d|-|hd)*\.flv/)[1] - b.name.match(/\d+-(\d+)(?:\d|-|hd)*\.flv/)[1]);
  7729. }
  7730.  
  7731. // 4.3 give loaded files hint
  7732. table.append(...files.map(e => {
  7733. const tr1 = document.createElement('tr');
  7734. const td1 = document.createElement('td');
  7735. td1.colSpan = '3';
  7736. td1.textContent = e.name;
  7737. tr1.append(td1);
  7738. return tr1;
  7739. }));
  7740.  
  7741. // 4.4 determine output name
  7742. let outputName = files[0].name.match(/\d+-\d+(?:\d|-|hd)*\.flv/);
  7743. if (outputName) outputName = outputName[0].replace(/-\d/, "");else outputName = 'merge_' + files[0].name;
  7744.  
  7745. // 4.5 build output ui
  7746. const href = await this.twin.mergeFLVFiles(files);
  7747. table.append((() => {
  7748. const tr1 = document.createElement('tr');
  7749. const td1 = document.createElement('td');
  7750. td1.colSpan = '3';
  7751. const a1 = document.createElement('a');
  7752. a1.href = href;
  7753. a1.download = outputName;
  7754. a1.textContent = outputName;
  7755. td1.append(a1);
  7756. tr1.append(td1);
  7757. return tr1;
  7758. })());
  7759. };
  7760.  
  7761. // 5. build util buttons
  7762. div.append(table, (() => {
  7763. const button = document.createElement('button');
  7764. button.style.padding = '0.5em';
  7765. button.style.margin = '0.2em';
  7766.  
  7767. button.onclick = () => div.style.display = 'none';
  7768.  
  7769. button.textContent = '\u5173\u95ED';
  7770. return button;
  7771. })(), (() => {
  7772. const button = document.createElement('button');
  7773. button.style.padding = '0.5em';
  7774. button.style.margin = '0.2em';
  7775.  
  7776. button.onclick = () => monkey.cleanAllFLVsInCache();
  7777.  
  7778. button.textContent = '\u6E05\u7A7A\u8FD9\u4E2A\u89C6\u9891\u7684\u7F13\u5B58';
  7779. return button;
  7780. })(), (() => {
  7781. const button = document.createElement('button');
  7782. button.style.padding = '0.5em';
  7783. button.style.margin = '0.2em';
  7784.  
  7785. button.onclick = () => this.twin.clearCacheDB(cache);
  7786.  
  7787. button.textContent = '\u6E05\u7A7A\u6240\u6709\u89C6\u9891\u7684\u7F13\u5B58';
  7788. return button;
  7789. })());
  7790.  
  7791. // 6. cancel on destroy
  7792. this.cidSessionDestroy.addCallback(() => {
  7793. flvTrs.map(tr => {
  7794. const a = tr.children[1].children[0];
  7795. if (a.textContent == '取消') a.click();
  7796. });
  7797. });
  7798.  
  7799. return this.cidSessionDom.flvDiv = div;
  7800. }
  7801.  
  7802. displayFLVDiv(flvDiv = this.cidSessionDom.flvDiv) {
  7803. if (!flvDiv) {
  7804. flvDiv = this.buildFLVDiv();
  7805. document.body.append(flvDiv);
  7806. }
  7807. flvDiv.style.display = '';
  7808. return flvDiv;
  7809. }
  7810.  
  7811. async downloadAllFLVs({ a, monkey = this.twin.monkey, table = this.cidSessionDom.flvTable }) {
  7812. if (this.cidSessionDom.downloadAllTr) return;
  7813.  
  7814. // 1. hang player
  7815. monkey.hangPlayer();
  7816.  
  7817. // 2. give hang player hint
  7818. this.cidSessionDom.downloadAllTr = (() => {
  7819. const tr1 = document.createElement('tr');
  7820. const td1 = document.createElement('td');
  7821. td1.colSpan = '3';
  7822. td1.textContent = '\u5DF2\u5C4F\u853D\u7F51\u9875\u64AD\u653E\u5668\u7684\u7F51\u7EDC\u94FE\u63A5\u3002\u5207\u6362\u6E05\u6670\u5EA6\u53EF\u91CD\u65B0\u6FC0\u6D3B\u64AD\u653E\u5668\u3002';
  7823. tr1.append(td1);
  7824. return tr1;
  7825. })();
  7826. table.append(this.cidSessionDom.downloadAllTr);
  7827.  
  7828. // 3. click download all split
  7829. for (let i = 0; i < monkey.flvs.length; i++) {
  7830. if (table.rows[i].cells[1].children[0].textContent == '缓存本段') table.rows[i].cells[1].children[0].click();
  7831. }
  7832.  
  7833. // 4. set sprogress
  7834. const progress = a.parentElement.nextElementSibling.children[0];
  7835. progress.max = monkey.flvs.length + 1;
  7836. progress.value = 0;
  7837. for (let i = 0; i < monkey.flvs.length; i++) monkey.getFLV(i).then(e => progress.value++);
  7838.  
  7839. // 5. merge splits
  7840. const files = await monkey.getAllFLVs();
  7841. const href = await this.twin.mergeFLVFiles(files);
  7842. const ass = await monkey.ass;
  7843. const outputName = top.document.getElementsByTagName('h1')[0].textContent.trim();
  7844.  
  7845. // 6. build download all ui
  7846. progress.value++;
  7847. table.prepend((() => {
  7848. const tr1 = document.createElement('tr');
  7849. const td1 = document.createElement('td');
  7850. td1.colSpan = '3';
  7851. td1.style = 'border: 1px solid black';
  7852. const a1 = document.createElement('a');
  7853. a1.href = href;
  7854. a1.download = `${outputName}.flv`;
  7855.  
  7856. (a => {
  7857. if (this.option.autoDanmaku) a.onclick = () => a.nextElementSibling.click();
  7858. })(a1);
  7859.  
  7860. a1.textContent = '\u4FDD\u5B58\u5408\u5E76\u540EFLV';
  7861. td1.append(a1);
  7862. td1.append(' ');
  7863. const a2 = document.createElement('a');
  7864. a2.href = ass;
  7865. a2.download = `${outputName}.ass`;
  7866. a2.textContent = '\u5F39\u5E55ASS';
  7867. td1.append(a2);
  7868. td1.append(' ');
  7869. const a3 = document.createElement('a');
  7870.  
  7871. a3.onclick = () => new MKVTransmuxer().exec(href, ass, `${outputName}.mkv`);
  7872.  
  7873. a3.textContent = '\u6253\u5305MKV(\u8F6F\u5B57\u5E55\u5C01\u88C5)';
  7874. td1.append(a3);
  7875. td1.append(' ');
  7876. td1.append('\u8BB0\u5F97\u6E05\u7406\u5206\u6BB5\u7F13\u5B58\u54E6~');
  7877. tr1.append(td1);
  7878. return tr1;
  7879. })());
  7880.  
  7881. return href;
  7882. }
  7883.  
  7884. async downloadFLV({ a, monkey = this.twin.monkey, index, progress = {} }) {
  7885. // 1. add beforeUnloadHandler
  7886. const handler = e => UI.beforeUnloadHandler(e);
  7887. window.addEventListener('beforeunload', handler);
  7888.  
  7889. // 2. switch to cancel ui
  7890. a.textContent = '取消';
  7891. a.onclick = () => {
  7892. a.onclick = null;
  7893. window.removeEventListener('beforeunload', handler);
  7894. a.textContent = '已取消';
  7895. monkey.abortFLV(index);
  7896. };
  7897.  
  7898. // 3. try download
  7899. let url;
  7900. try {
  7901. url = await monkey.getFLV(index, (loaded, total) => {
  7902. progress.value = loaded;
  7903. progress.max = total;
  7904. });
  7905. url = URL.createObjectURL(url);
  7906. if (progress.value == 0) progress.value = progress.max = 1;
  7907. } catch (e) {
  7908. a.onclick = null;
  7909. window.removeEventListener('beforeunload', handler);
  7910. a.textContent = '错误';
  7911. throw e;
  7912. }
  7913.  
  7914. // 4. switch to complete ui
  7915. a.onclick = null;
  7916. window.removeEventListener('beforeunload', handler);
  7917. a.textContent = '另存为';
  7918. a.download = monkey.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.flv/)[0];
  7919. a.href = url;
  7920. return url;
  7921. }
  7922.  
  7923. async displayQuota(td) {
  7924. return new Promise(resolve => {
  7925. const temporaryStorage = window.navigator.temporaryStorage || window.navigator.webkitTemporaryStorage || window.navigator.mozTemporaryStorage || window.navigator.msTemporaryStorage;
  7926. if (!temporaryStorage) return resolve(td.textContent = '这个浏览器不支持缓存呢~关掉标签页后,缓存马上就会消失哦');
  7927. temporaryStorage.queryUsageAndQuota((usage, quota) => resolve(td.textContent = `缓存已用空间:${Math.round(usage / 1048576)} MB / ${Math.round(quota / 1048576)} MB 也包括了B站本来的缓存`));
  7928. });
  7929. }
  7930.  
  7931. // Menu Append
  7932. appendMenu(playerWin = this.twin.playerWin) {
  7933. // 1. build monkey menu and polyfill menu
  7934. const monkeyMenu = this.buildMonkeyMenu();
  7935. const polyfillMenu = this.buildPolyfillMenu();
  7936.  
  7937. // 2. build ul
  7938. const ul = document.createElement('ul');
  7939.  
  7940. // 3. append to menu
  7941. ul.className = 'bilitwin';
  7942. ul.style.borderBottom = '1px solid rgba(255,255,255,.12)';
  7943. ul.append(...[monkeyMenu, polyfillMenu]);
  7944. const div = playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black')[0];
  7945. div.prepend(ul);
  7946.  
  7947. // 4. save to cache
  7948. this.cidSessionDom.menuUl = ul;
  7949.  
  7950. return ul;
  7951. }
  7952.  
  7953. buildMonkeyMenu({
  7954. playerWin = this.twin.playerWin,
  7955. BiliMonkey = this.twin.BiliMonkey,
  7956. monkey = this.twin.monkey,
  7957. flvA = this.cidSessionDom.flvA,
  7958. mp4A = this.cidSessionDom.mp4A,
  7959. assA = this.cidSessionDom.assA
  7960. } = {}) {
  7961. const li = document.createElement('li');
  7962. li.className = 'context-menu-menu bilitwin';
  7963.  
  7964. li.onclick = () => playerWin.document.getElementById('bilibiliPlayer').click();
  7965.  
  7966. const a1 = document.createElement('a');
  7967. a1.className = 'context-menu-a';
  7968. a1.append('BiliMonkey');
  7969. const span = document.createElement('span');
  7970. span.className = 'bpui-icon bpui-icon-arrow-down';
  7971. span.style = 'transform:rotate(-90deg);margin-top:3px;';
  7972. a1.append(span);
  7973. li.append(a1);
  7974. const ul1 = document.createElement('ul');
  7975. const li1 = document.createElement('li');
  7976. li1.className = 'context-menu-function';
  7977.  
  7978. li1.onclick = async () => {
  7979. if (flvA.onmouseover) await flvA.onmouseover();
  7980. flvA.click();
  7981. };
  7982.  
  7983. const a2 = document.createElement('a');
  7984. a2.className = 'context-menu-a';
  7985. const span1 = document.createElement('span');
  7986. span1.className = 'video-contextmenu-icon';
  7987. a2.append(span1);
  7988. a2.append(' \u4E0B\u8F7DFLV');
  7989. li1.append(a2);
  7990. ul1.append(li1);
  7991. const li2 = document.createElement('li');
  7992. li2.className = 'context-menu-function';
  7993.  
  7994. li2.onclick = async () => {
  7995. if (mp4A.onmouseover) await mp4A.onmouseover();
  7996. mp4A.click();
  7997. };
  7998.  
  7999. const a3 = document.createElement('a');
  8000. a3.className = 'context-menu-a';
  8001. const span2 = document.createElement('span');
  8002. span2.className = 'video-contextmenu-icon';
  8003. a3.append(span2);
  8004. a3.append(' \u4E0B\u8F7DMP4');
  8005. li2.append(a3);
  8006. ul1.append(li2);
  8007. const li3 = document.createElement('li');
  8008. li3.className = 'context-menu-function';
  8009.  
  8010. li3.onclick = async () => {
  8011. if (assA.onmouseover) await assA.onmouseover();
  8012. assA.click();
  8013. };
  8014.  
  8015. const a4 = document.createElement('a');
  8016. a4.className = 'context-menu-a';
  8017. const span3 = document.createElement('span');
  8018. span3.className = 'video-contextmenu-icon';
  8019. a4.append(span3);
  8020. a4.append(' \u4E0B\u8F7DASS');
  8021. li3.append(a4);
  8022. ul1.append(li3);
  8023. const li4 = document.createElement('li');
  8024. li4.className = 'context-menu-function';
  8025.  
  8026. li4.onclick = () => this.displayOptionDiv();
  8027.  
  8028. const a5 = document.createElement('a');
  8029. a5.className = 'context-menu-a';
  8030. const span4 = document.createElement('span');
  8031. span4.className = 'video-contextmenu-icon';
  8032. a5.append(span4);
  8033. a5.append(' \u8BBE\u7F6E/\u5E2E\u52A9/\u5173\u4E8E');
  8034. li4.append(a5);
  8035. ul1.append(li4);
  8036. const li5 = document.createElement('li');
  8037. li5.className = 'context-menu-function';
  8038.  
  8039. li5.onclick = async () => UI.displayDownloadAllPageDefaultFormatsBody((await BiliMonkey.getAllPageDefaultFormats(playerWin)));
  8040.  
  8041. const a6 = document.createElement('a');
  8042. a6.className = 'context-menu-a';
  8043. const span5 = document.createElement('span');
  8044. span5.className = 'video-contextmenu-icon';
  8045. a6.append(span5);
  8046. a6.append(' (\u6D4B)\u6279\u91CF\u4E0B\u8F7D');
  8047. li5.append(a6);
  8048. ul1.append(li5);
  8049. const li6 = document.createElement('li');
  8050. li6.className = 'context-menu-function';
  8051.  
  8052. li6.onclick = async () => {
  8053. monkey.proxy = true;
  8054. monkey.flvs = null;
  8055. UI.hintInfo('请稍候,可能需要10秒时间……', playerWin);
  8056. // Yes, I AM lazy.
  8057. playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul li[data-value="80"]').click();
  8058. await new Promise(r => playerWin.document.getElementsByTagName('video')[0].addEventListener('emptied', r));
  8059. return monkey.queryInfo('flv');
  8060. };
  8061.  
  8062. const a7 = document.createElement('a');
  8063. a7.className = 'context-menu-a';
  8064. const span6 = document.createElement('span');
  8065. span6.className = 'video-contextmenu-icon';
  8066. a7.append(span6);
  8067. a7.append(' (\u6D4B)\u8F7D\u5165\u7F13\u5B58FLV');
  8068. li6.append(a7);
  8069. ul1.append(li6);
  8070. const li7 = document.createElement('li');
  8071. li7.className = 'context-menu-function';
  8072.  
  8073. li7.onclick = () => top.location.reload(true);
  8074.  
  8075. const a8 = document.createElement('a');
  8076. a8.className = 'context-menu-a';
  8077. const span7 = document.createElement('span');
  8078. span7.className = 'video-contextmenu-icon';
  8079. a8.append(span7);
  8080. a8.append(' (\u6D4B)\u5F3A\u5236\u5237\u65B0');
  8081. li7.append(a8);
  8082. ul1.append(li7);
  8083. const li8 = document.createElement('li');
  8084. li8.className = 'context-menu-function';
  8085.  
  8086. li8.onclick = () => this.cidSessionDestroy() && this.cidSessionRender();
  8087.  
  8088. const a9 = document.createElement('a');
  8089. a9.className = 'context-menu-a';
  8090. const span8 = document.createElement('span');
  8091. span8.className = 'video-contextmenu-icon';
  8092. a9.append(span8);
  8093. a9.append(' (\u6D4B)\u91CD\u542F\u811A\u672C');
  8094. li8.append(a9);
  8095. ul1.append(li8);
  8096. const li9 = document.createElement('li');
  8097. li9.className = 'context-menu-function';
  8098.  
  8099. li9.onclick = () => playerWin.player && playerWin.player.destroy();
  8100.  
  8101. const a10 = document.createElement('a');
  8102. a10.className = 'context-menu-a';
  8103. const span9 = document.createElement('span');
  8104. span9.className = 'video-contextmenu-icon';
  8105. a10.append(span9);
  8106. a10.append(' (\u6D4B)\u9500\u6BC1\u64AD\u653E\u5668');
  8107. li9.append(a10);
  8108. ul1.append(li9);
  8109. li.append(ul1);
  8110.  
  8111. return li;
  8112. }
  8113.  
  8114. buildPolyfillMenu({
  8115. playerWin = this.twin.playerWin,
  8116. BiliPolyfill = this.twin.BiliPolyfill,
  8117. polyfill = this.twin.polyfill
  8118. } = {}) {
  8119. let oped = [];
  8120. const refreshSession = new HookedFunction(() => oped = polyfill.userdata.oped[polyfill.getCollectionId()] || []); // as a convenient callback register
  8121. const li = document.createElement('li');
  8122. li.className = 'context-menu-menu bilitwin';
  8123.  
  8124. li.onclick = () => playerWin.document.getElementById('bilibiliPlayer').click();
  8125.  
  8126. const a1 = document.createElement('a');
  8127. a1.className = 'context-menu-a';
  8128.  
  8129. a1.onmouseover = () => refreshSession();
  8130.  
  8131. a1.append('BiliPolyfill');
  8132. a1.append(!polyfill.option.betabeta ? '(到设置开启)' : '');
  8133. const span = document.createElement('span');
  8134. span.className = 'bpui-icon bpui-icon-arrow-down';
  8135. span.style = 'transform:rotate(-90deg);margin-top:3px;';
  8136. a1.append(span);
  8137. li.append(a1);
  8138. const ul1 = document.createElement('ul');
  8139. const li1 = document.createElement('li');
  8140. li1.className = 'context-menu-function';
  8141.  
  8142. li1.onclick = () => top.window.open(polyfill.getCoverImage(), '_blank');
  8143.  
  8144. const a2 = document.createElement('a');
  8145. a2.className = 'context-menu-a';
  8146. const span1 = document.createElement('span');
  8147. span1.className = 'video-contextmenu-icon';
  8148. a2.append(span1);
  8149. a2.append(' \u83B7\u53D6\u5C01\u9762');
  8150. li1.append(a2);
  8151. ul1.append(li1);
  8152. const li2 = document.createElement('li');
  8153. li2.className = 'context-menu-menu';
  8154. const a3 = document.createElement('a');
  8155. a3.className = 'context-menu-a';
  8156. const span2 = document.createElement('span');
  8157. span2.className = 'video-contextmenu-icon';
  8158. a3.append(span2);
  8159. a3.append(' \u66F4\u591A\u64AD\u653E\u901F\u5EA6');
  8160. const span3 = document.createElement('span');
  8161. span3.className = 'bpui-icon bpui-icon-arrow-down';
  8162. span3.style = 'transform:rotate(-90deg);margin-top:3px;';
  8163. a3.append(span3);
  8164. li2.append(a3);
  8165. const ul2 = document.createElement('ul');
  8166. const li3 = document.createElement('li');
  8167. li3.className = 'context-menu-function';
  8168.  
  8169. li3.onclick = () => {
  8170. polyfill.setVideoSpeed(0.1);
  8171. };
  8172.  
  8173. const a4 = document.createElement('a');
  8174. a4.className = 'context-menu-a';
  8175. const span4 = document.createElement('span');
  8176. span4.className = 'video-contextmenu-icon';
  8177. a4.append(span4);
  8178. a4.append(' 0.1');
  8179. li3.append(a4);
  8180. ul2.append(li3);
  8181. const li4 = document.createElement('li');
  8182. li4.className = 'context-menu-function';
  8183.  
  8184. li4.onclick = () => {
  8185. polyfill.setVideoSpeed(3);
  8186. };
  8187.  
  8188. const a5 = document.createElement('a');
  8189. a5.className = 'context-menu-a';
  8190. const span5 = document.createElement('span');
  8191. span5.className = 'video-contextmenu-icon';
  8192. a5.append(span5);
  8193. a5.append(' 3');
  8194. li4.append(a5);
  8195. ul2.append(li4);
  8196. const li5 = document.createElement('li');
  8197. li5.className = 'context-menu-function';
  8198.  
  8199. li5.onclick = e => polyfill.setVideoSpeed(e.children[0].children[1].value);
  8200.  
  8201. const a6 = document.createElement('a');
  8202. a6.className = 'context-menu-a';
  8203. const span6 = document.createElement('span');
  8204. span6.className = 'video-contextmenu-icon';
  8205. a6.append(span6);
  8206. a6.append(' \u70B9\u51FB\u786E\u8BA4');
  8207. const input = document.createElement('input');
  8208. input.type = 'text';
  8209. input.style = 'width: 35px; height: 70%';
  8210.  
  8211. input.onclick = e => e.stopPropagation();
  8212.  
  8213. (e => refreshSession.addCallback(() => e.value = polyfill.video.playbackRate))(input);
  8214.  
  8215. a6.append(input);
  8216. li5.append(a6);
  8217. ul2.append(li5);
  8218. li2.append(ul2);
  8219. ul1.append(li2);
  8220. const li6 = document.createElement('li');
  8221. li6.className = 'context-menu-menu';
  8222. const a7 = document.createElement('a');
  8223. a7.className = 'context-menu-a';
  8224. const span7 = document.createElement('span');
  8225. span7.className = 'video-contextmenu-icon';
  8226. a7.append(span7);
  8227. a7.append(' \u7247\u5934\u7247\u5C3E');
  8228. const span8 = document.createElement('span');
  8229. span8.className = 'bpui-icon bpui-icon-arrow-down';
  8230. span8.style = 'transform:rotate(-90deg);margin-top:3px;';
  8231. a7.append(span8);
  8232. li6.append(a7);
  8233. const ul3 = document.createElement('ul');
  8234. const li7 = document.createElement('li');
  8235. li7.className = 'context-menu-function';
  8236.  
  8237. li7.onclick = () => polyfill.markOPEDPosition(0);
  8238.  
  8239. const a8 = document.createElement('a');
  8240. a8.className = 'context-menu-a';
  8241. const span9 = document.createElement('span');
  8242. span9.className = 'video-contextmenu-icon';
  8243. a8.append(span9);
  8244. a8.append(' \u7247\u5934\u5F00\u59CB:');
  8245. const span10 = document.createElement('span');
  8246.  
  8247. (e => refreshSession.addCallback(() => e.textContent = oped[0] ? BiliPolyfill.secondToReadable(oped[0]) : '无'))(span10);
  8248.  
  8249. a8.append(span10);
  8250. li7.append(a8);
  8251. ul3.append(li7);
  8252. const li8 = document.createElement('li');
  8253. li8.className = 'context-menu-function';
  8254.  
  8255. li8.onclick = () => polyfill.markOPEDPosition(1);
  8256.  
  8257. const a9 = document.createElement('a');
  8258. a9.className = 'context-menu-a';
  8259. const span11 = document.createElement('span');
  8260. span11.className = 'video-contextmenu-icon';
  8261. a9.append(span11);
  8262. a9.append(' \u7247\u5934\u7ED3\u675F:');
  8263. const span12 = document.createElement('span');
  8264.  
  8265. (e => refreshSession.addCallback(() => e.textContent = oped[1] ? BiliPolyfill.secondToReadable(oped[1]) : '无'))(span12);
  8266.  
  8267. a9.append(span12);
  8268. li8.append(a9);
  8269. ul3.append(li8);
  8270. const li9 = document.createElement('li');
  8271. li9.className = 'context-menu-function';
  8272.  
  8273. li9.onclick = () => polyfill.markOPEDPosition(2);
  8274.  
  8275. const a10 = document.createElement('a');
  8276. a10.className = 'context-menu-a';
  8277. const span13 = document.createElement('span');
  8278. span13.className = 'video-contextmenu-icon';
  8279. a10.append(span13);
  8280. a10.append(' \u7247\u5C3E\u5F00\u59CB:');
  8281. const span14 = document.createElement('span');
  8282.  
  8283. (e => refreshSession.addCallback(() => e.textContent = oped[2] ? BiliPolyfill.secondToReadable(oped[2]) : '无'))(span14);
  8284.  
  8285. a10.append(span14);
  8286. li9.append(a10);
  8287. ul3.append(li9);
  8288. const li10 = document.createElement('li');
  8289. li10.className = 'context-menu-function';
  8290.  
  8291. li10.onclick = () => polyfill.markOPEDPosition(3);
  8292.  
  8293. const a11 = document.createElement('a');
  8294. a11.className = 'context-menu-a';
  8295. const span15 = document.createElement('span');
  8296. span15.className = 'video-contextmenu-icon';
  8297. a11.append(span15);
  8298. a11.append(' \u7247\u5C3E\u7ED3\u675F:');
  8299. const span16 = document.createElement('span');
  8300.  
  8301. (e => refreshSession.addCallback(() => e.textContent = oped[3] ? BiliPolyfill.secondToReadable(oped[3]) : '无'))(span16);
  8302.  
  8303. a11.append(span16);
  8304. li10.append(a11);
  8305. ul3.append(li10);
  8306. const li11 = document.createElement('li');
  8307. li11.className = 'context-menu-function';
  8308.  
  8309. li11.onclick = () => polyfill.clearOPEDPosition();
  8310.  
  8311. const a12 = document.createElement('a');
  8312. a12.className = 'context-menu-a';
  8313. const span17 = document.createElement('span');
  8314. span17.className = 'video-contextmenu-icon';
  8315. a12.append(span17);
  8316. a12.append(' \u53D6\u6D88\u6807\u8BB0');
  8317. li11.append(a12);
  8318. ul3.append(li11);
  8319. const li12 = document.createElement('li');
  8320. li12.className = 'context-menu-function';
  8321.  
  8322. li12.onclick = () => this.displayPolyfillDataDiv();
  8323.  
  8324. const a13 = document.createElement('a');
  8325. a13.className = 'context-menu-a';
  8326. const span18 = document.createElement('span');
  8327. span18.className = 'video-contextmenu-icon';
  8328. a13.append(span18);
  8329. a13.append(' \u68C0\u89C6\u6570\u636E/\u8BF4\u660E');
  8330. li12.append(a13);
  8331. ul3.append(li12);
  8332. li6.append(ul3);
  8333. ul1.append(li6);
  8334. const li13 = document.createElement('li');
  8335. li13.className = 'context-menu-menu';
  8336. const a14 = document.createElement('a');
  8337. a14.className = 'context-menu-a';
  8338. const span19 = document.createElement('span');
  8339. span19.className = 'video-contextmenu-icon';
  8340. a14.append(span19);
  8341. a14.append(' \u627E\u4E0A\u4E0B\u96C6');
  8342. const span20 = document.createElement('span');
  8343. span20.className = 'bpui-icon bpui-icon-arrow-down';
  8344. span20.style = 'transform:rotate(-90deg);margin-top:3px;';
  8345. a14.append(span20);
  8346. li13.append(a14);
  8347. const ul4 = document.createElement('ul');
  8348. const li14 = document.createElement('li');
  8349. li14.className = 'context-menu-function';
  8350.  
  8351. li14.onclick = () => {
  8352. if (polyfill.series[0]) {
  8353. top.window.open(`https://www.bilibili.com/video/av${polyfill.series[0].aid}`, '_blank');
  8354. }
  8355. };
  8356.  
  8357. const a15 = document.createElement('a');
  8358. a15.className = 'context-menu-a';
  8359. a15.style.width = 'initial';
  8360. const span21 = document.createElement('span');
  8361. span21.className = 'video-contextmenu-icon';
  8362. a15.append(span21);
  8363. const span22 = document.createElement('span');
  8364.  
  8365. (e => refreshSession.addCallback(() => e.textContent = polyfill.series[0] ? polyfill.series[0].title : '找不到'))(span22);
  8366.  
  8367. a15.append(span22);
  8368. li14.append(a15);
  8369. ul4.append(li14);
  8370. const li15 = document.createElement('li');
  8371. li15.className = 'context-menu-function';
  8372.  
  8373. li15.onclick = () => {
  8374. if (polyfill.series[1]) {
  8375. top.window.open(`https://www.bilibili.com/video/av${polyfill.series[1].aid}`, '_blank');
  8376. }
  8377. };
  8378.  
  8379. const a16 = document.createElement('a');
  8380. a16.className = 'context-menu-a';
  8381. a16.style.width = 'initial';
  8382. const span23 = document.createElement('span');
  8383. span23.className = 'video-contextmenu-icon';
  8384. a16.append(span23);
  8385. const span24 = document.createElement('span');
  8386.  
  8387. (e => refreshSession.addCallback(() => e.textContent = polyfill.series[1] ? polyfill.series[1].title : '找不到'))(span24);
  8388.  
  8389. a16.append(span24);
  8390. li15.append(a16);
  8391. ul4.append(li15);
  8392. li13.append(ul4);
  8393. ul1.append(li13);
  8394. const li16 = document.createElement('li');
  8395. li16.className = 'context-menu-function';
  8396.  
  8397. li16.onclick = () => BiliPolyfill.openMinimizedPlayer();
  8398.  
  8399. const a17 = document.createElement('a');
  8400. a17.className = 'context-menu-a';
  8401. const span25 = document.createElement('span');
  8402. span25.className = 'video-contextmenu-icon';
  8403. a17.append(span25);
  8404. a17.append(' \u5C0F\u7A97\u64AD\u653E');
  8405. li16.append(a17);
  8406. ul1.append(li16);
  8407. const li17 = document.createElement('li');
  8408. li17.className = 'context-menu-function';
  8409.  
  8410. li17.onclick = () => this.displayOptionDiv();
  8411.  
  8412. const a18 = document.createElement('a');
  8413. a18.className = 'context-menu-a';
  8414. const span26 = document.createElement('span');
  8415. span26.className = 'video-contextmenu-icon';
  8416. a18.append(span26);
  8417. a18.append(' \u8BBE\u7F6E/\u5E2E\u52A9/\u5173\u4E8E');
  8418. li17.append(a18);
  8419. ul1.append(li17);
  8420. const li18 = document.createElement('li');
  8421. li18.className = 'context-menu-function';
  8422.  
  8423. li18.onclick = () => polyfill.saveUserdata();
  8424.  
  8425. const a19 = document.createElement('a');
  8426. a19.className = 'context-menu-a';
  8427. const span27 = document.createElement('span');
  8428. span27.className = 'video-contextmenu-icon';
  8429. a19.append(span27);
  8430. a19.append(' (\u6D4B)\u7ACB\u5373\u4FDD\u5B58\u6570\u636E');
  8431. li18.append(a19);
  8432. ul1.append(li18);
  8433. const li19 = document.createElement('li');
  8434. li19.className = 'context-menu-function';
  8435.  
  8436. li19.onclick = () => {
  8437. BiliPolyfill.clearAllUserdata(playerWin);
  8438. polyfill.retrieveUserdata();
  8439. };
  8440.  
  8441. const a20 = document.createElement('a');
  8442. a20.className = 'context-menu-a';
  8443. const span28 = document.createElement('span');
  8444. span28.className = 'video-contextmenu-icon';
  8445. a20.append(span28);
  8446. a20.append(' (\u6D4B)\u5F3A\u5236\u6E05\u7A7A\u6570\u636E');
  8447. li19.append(a20);
  8448. ul1.append(li19);
  8449. li.append(ul1);
  8450. return li;
  8451. }
  8452.  
  8453. buildOptionDiv(twin = this.twin) {
  8454. const div = UI.genDiv();
  8455.  
  8456. div.append(this.buildMonkeyOptionTable(), this.buildPolyfillOptionTable(), this.buildUIOptionTable(), (() => {
  8457. const table1 = document.createElement('table');
  8458. table1.style.width = '100%';
  8459. table1.style.lineHeight = '2em';
  8460. const tr1 = document.createElement('tr');
  8461. const td1 = document.createElement('td');
  8462. td1.textContent = '\u8BBE\u7F6E\u81EA\u52A8\u4FDD\u5B58\uFF0C\u5237\u65B0\u540E\u751F\u6548\u3002';
  8463. tr1.append(td1);
  8464. table1.append(tr1);
  8465. const tr2 = document.createElement('tr');
  8466. const td2 = document.createElement('td');
  8467. td2.textContent = '\u89C6\u9891\u4E0B\u8F7D\u7EC4\u4EF6\u7684\u7F13\u5B58\u529F\u80FD\u53EA\u5728Windows+Chrome\u6D4B\u8BD5\u8FC7\uFF0C\u5982\u679C\u51FA\u73B0\u95EE\u9898\uFF0C\u8BF7\u5173\u95ED\u7F13\u5B58\u3002';
  8468. tr2.append(td2);
  8469. table1.append(tr2);
  8470. const tr3 = document.createElement('tr');
  8471. const td3 = document.createElement('td');
  8472. td3.textContent = '\u529F\u80FD\u589E\u5F3A\u7EC4\u4EF6\u5C3D\u91CF\u4FDD\u8BC1\u4E86\u517C\u5BB9\u6027\u3002\u4F46\u5982\u679C\u6709\u540C\u529F\u80FD\u811A\u672C/\u63D2\u4EF6\uFF0C\u8BF7\u5173\u95ED\u672C\u63D2\u4EF6\u7684\u5BF9\u5E94\u529F\u80FD\u3002';
  8473. tr3.append(td3);
  8474. table1.append(tr3);
  8475. const tr4 = document.createElement('tr');
  8476. const td4 = document.createElement('td');
  8477. td4.textContent = '\u8FD9\u4E2A\u811A\u672C\u4E43\u201C\u6309\u539F\u6837\u201D\u63D0\u4F9B\uFF0C\u4E0D\u9644\u5E26\u4EFB\u4F55\u660E\u793A\uFF0C\u6697\u793A\u6216\u6CD5\u5B9A\u7684\u4FDD\u8BC1\uFF0C\u5305\u62EC\u4F46\u4E0D\u9650\u4E8E\u5176\u6CA1\u6709\u7F3A\u9677\uFF0C\u9002\u5408\u7279\u5B9A\u76EE\u7684\u6216\u975E\u4FB5\u6743\u3002';
  8478. tr4.append(td4);
  8479. table1.append(tr4);
  8480. const tr5 = document.createElement('tr');
  8481. const td5 = document.createElement('td');
  8482. const a1 = document.createElement('a');
  8483. a1.href = 'https://greasyfork.org/zh-CN/scripts/27819';
  8484. a1.target = '_blank';
  8485. a1.textContent = '\u66F4\u65B0/\u8BA8\u8BBA';
  8486. td5.append(a1);
  8487. td5.append(' ');
  8488. const a2 = document.createElement('a');
  8489. a2.href = 'https://github.com/liqi0816/bilitwin/';
  8490. a2.target = '_blank';
  8491. a2.textContent = 'GitHub';
  8492. td5.append(a2);
  8493. td5.append(' ');
  8494. td5.append('Author: qli5. Copyright: qli5, 2014+, \u7530\u751F, grepmusic');
  8495. tr5.append(td5);
  8496. table1.append(tr5);
  8497. return table1;
  8498. })(), (() => {
  8499. const button = document.createElement('button');
  8500. button.style.padding = '0.5em';
  8501. button.style.margin = '0.2em';
  8502.  
  8503. button.onclick = () => div.style.display = 'none';
  8504.  
  8505. button.textContent = '\u5173\u95ED';
  8506. return button;
  8507. })(), (() => {
  8508. const button = document.createElement('button');
  8509. button.style.padding = '0.5em';
  8510. button.style.margin = '0.2em';
  8511.  
  8512. button.onclick = () => top.location.reload();
  8513.  
  8514. button.textContent = '\u4FDD\u5B58\u5E76\u5237\u65B0';
  8515. return button;
  8516. })(), (() => {
  8517. const button = document.createElement('button');
  8518. button.style.padding = '0.5em';
  8519. button.style.margin = '0.2em';
  8520.  
  8521. button.onclick = () => twin.resetOption() && top.location.reload();
  8522.  
  8523. button.textContent = '\u91CD\u7F6E\u5E76\u5237\u65B0';
  8524. return button;
  8525. })());
  8526.  
  8527. return this.dom.optionDiv = div;
  8528. }
  8529.  
  8530. buildMonkeyOptionTable(twin = this.twin, BiliMonkey = this.twin.BiliMonkey) {
  8531. const table = document.createElement('table');
  8532. {
  8533. table.style.width = '100%';
  8534. table.style.lineHeight = '2em';
  8535. const tr1 = document.createElement('tr');
  8536. const td1 = document.createElement('td');
  8537. td1.style = 'text-align:center';
  8538. td1.textContent = 'BiliMonkey\uFF08\u89C6\u9891\u6293\u53D6\u7EC4\u4EF6\uFF09';
  8539. tr1.append(td1);
  8540. table.append(tr1);
  8541. const tr2 = document.createElement('tr');
  8542. const td2 = document.createElement('td');
  8543. td2.style = 'text-align:center';
  8544. td2.textContent = '\u56E0\u4E3A\u4F5C\u8005\u5077\u61D2\u4E86\uFF0C\u7F13\u5B58\u7684\u4E09\u4E2A\u9009\u9879\u6700\u597D\u8981\u4E48\u5168\u5F00\uFF0C\u8981\u4E48\u5168\u5173\u3002\u6700\u597D\u3002';
  8545. tr2.append(td2);
  8546. table.append(tr2);
  8547. }
  8548.  
  8549. table.append(...BiliMonkey.optionDescriptions.map(([name, description]) => {
  8550. const tr1 = document.createElement('tr');
  8551. const label = document.createElement('label');
  8552. const input = document.createElement('input');
  8553. input.type = 'checkbox';
  8554. input.checked = twin.option[name];
  8555.  
  8556. input.onchange = e => {
  8557. twin.option[name] = e.target.checked;
  8558. twin.saveOption(twin.option);
  8559. };
  8560.  
  8561. label.append(input);
  8562. label.append(description);
  8563. tr1.append(label);
  8564. return tr1;
  8565. }));
  8566.  
  8567. return table;
  8568. }
  8569.  
  8570. buildPolyfillOptionTable(twin = this.twin, BiliPolyfill = this.twin.BiliPolyfill) {
  8571. const table = document.createElement('table');
  8572. {
  8573. table.style.width = '100%';
  8574. table.style.lineHeight = '2em';
  8575. const tr1 = document.createElement('tr');
  8576. const td1 = document.createElement('td');
  8577. td1.style = 'text-align:center';
  8578. td1.textContent = 'BiliPolyfill\uFF08\u529F\u80FD\u589E\u5F3A\u7EC4\u4EF6\uFF09';
  8579. tr1.append(td1);
  8580. table.append(tr1);
  8581. const tr2 = document.createElement('tr');
  8582. const td2 = document.createElement('td');
  8583. td2.style = 'text-align:center';
  8584. td2.textContent = '\u61D2\u9B3C\u4F5C\u8005\u8FD8\u5728\u6D4B\u8BD5\u7684\u65F6\u5019\uFF0CB\u7AD9\u5DF2\u7ECF\u4E0A\u7EBF\u4E86\u539F\u751F\u7684\u7A0D\u540E\u518D\u770B(\u0E51\u2022\u0300\u3142\u2022\u0301)\u0648\u2727';
  8585. tr2.append(td2);
  8586. table.append(tr2);
  8587. }
  8588.  
  8589. table.append(...BiliPolyfill.optionDescriptions.map(([name, description, disabled]) => {
  8590. const tr1 = document.createElement('tr');
  8591. const label = document.createElement('label');
  8592. label.style.textDecoration = disabled == 'disabled' ? 'line-through' : undefined;
  8593. const input = document.createElement('input');
  8594. input.type = 'checkbox';
  8595. input.checked = twin.option[name];
  8596.  
  8597. input.onchange = e => {
  8598. twin.option[name] = e.target.checked;
  8599. twin.saveOption(twin.option);
  8600. };
  8601.  
  8602. input.disabled = disabled == 'disabled';
  8603. label.append(input);
  8604. label.append(description);
  8605. tr1.append(label);
  8606. return tr1;
  8607. }));
  8608.  
  8609. return table;
  8610. }
  8611.  
  8612. buildUIOptionTable(twin = this.twin) {
  8613. const table = document.createElement('table');
  8614. {
  8615. table.style.width = '100%';
  8616. table.style.lineHeight = '2em';
  8617. const tr1 = document.createElement('tr');
  8618. const td1 = document.createElement('td');
  8619. td1.style = 'text-align:center';
  8620. td1.textContent = 'UI\uFF08\u7528\u6237\u754C\u9762\uFF09';
  8621. tr1.append(td1);
  8622. table.append(tr1);
  8623. }
  8624.  
  8625. table.append(...UI.optionDescriptions.map(([name, description]) => {
  8626. const tr1 = document.createElement('tr');
  8627. const label = document.createElement('label');
  8628. const input = document.createElement('input');
  8629. input.type = 'checkbox';
  8630. input.checked = twin.option[name];
  8631.  
  8632. input.onchange = e => {
  8633. twin.option[name] = e.target.checked;
  8634. twin.saveOption(twin.option);
  8635. };
  8636.  
  8637. label.append(input);
  8638. label.append(description);
  8639. tr1.append(label);
  8640. return tr1;
  8641. }));
  8642.  
  8643. return table;
  8644. }
  8645.  
  8646. displayOptionDiv(optionDiv = this.dom.optionDiv) {
  8647. if (!optionDiv) {
  8648. optionDiv = this.buildOptionDiv();
  8649. document.body.append(optionDiv);
  8650. }
  8651. optionDiv.style.display = '';
  8652. return optionDiv;
  8653. }
  8654.  
  8655. buildPolyfillDataDiv(polyfill = this.twin.polyfill) {
  8656. const textarea = document.createElement('textarea');
  8657.  
  8658. textarea.style.resize = 'vertical';
  8659. textarea.style.width = '100%';
  8660. textarea.style.height = '200px';
  8661. textarea.textContent = `
  8662. ${JSON.stringify(polyfill.userdata.oped).replace(/{/, '{\n').replace(/}/, '\n}').replace(/],/g, '],\n')}
  8663. `;
  8664. const div = UI.genDiv();
  8665.  
  8666. div.append((() => {
  8667. const p = document.createElement('p');
  8668. p.style.margin = '0.3em';
  8669. p.textContent = '\u8FD9\u91CC\u662F\u811A\u672C\u50A8\u5B58\u7684\u6570\u636E\u3002\u6240\u6709\u6570\u636E\u90FD\u53EA\u5B58\u5728\u6D4F\u89C8\u5668\u91CC\uFF0C\u522B\u4EBA\u4E0D\u77E5\u9053\uFF0CB\u7AD9\u4E5F\u4E0D\u77E5\u9053\uFF0C\u811A\u672C\u4F5C\u8005\u66F4\u4E0D\u77E5\u9053(\u8FD9\u4E2A\u5BB6\u4F19\u8FDE\u670D\u52A1\u5668\u90FD\u79DF\u4E0D\u8D77 \u6454';
  8670. return p;
  8671. })(), (() => {
  8672. const p = document.createElement('p');
  8673. p.style.margin = '0.3em';
  8674. p.textContent = 'B\u7AD9\u5DF2\u4E0A\u7EBF\u539F\u751F\u7684\u7A0D\u540E\u89C2\u770B\u529F\u80FD\u3002';
  8675. return p;
  8676. })(), (() => {
  8677. const p = document.createElement('p');
  8678. p.style.margin = '0.3em';
  8679. p.textContent = '\u8FD9\u91CC\u662F\u7247\u5934\u7247\u5C3E\u3002\u683C\u5F0F\u662F\uFF0Cav\u53F7\u6216\u756A\u5267\u53F7:[\u7247\u5934\u5F00\u59CB(\u9ED8\u8BA4=0),\u7247\u5934\u7ED3\u675F(\u9ED8\u8BA4=\u4E0D\u8DF3),\u7247\u5C3E\u5F00\u59CB(\u9ED8\u8BA4=\u4E0D\u8DF3),\u7247\u5C3E\u7ED3\u675F(\u9ED8\u8BA4=\u65E0\u7A77\u5927)]\u3002\u53EF\u4EE5\u4EFB\u610F\u586B\u5199null\uFF0C\u811A\u672C\u4F1A\u81EA\u52A8\u91C7\u7528\u9ED8\u8BA4\u503C\u3002';
  8680. return p;
  8681. })(), textarea, (() => {
  8682. const p = document.createElement('p');
  8683. p.style.margin = '0.3em';
  8684. p.textContent = '\u5F53\u7136\u53EF\u4EE5\u76F4\u63A5\u6E05\u7A7A\u5566\u3002\u53EA\u5220\u9664\u5176\u4E2D\u7684\u4E00\u4E9B\u884C\u7684\u8BDD\uFF0C\u4E00\u5B9A\u8981\u8BB0\u5F97\u5220\u6389\u591A\u4F59\u7684\u9017\u53F7\u3002';
  8685. return p;
  8686. })(), (() => {
  8687. const button = document.createElement('button');
  8688. button.style.padding = '0.5em';
  8689. button.style.margin = '0.2em';
  8690.  
  8691. button.onclick = () => div.remove();
  8692.  
  8693. button.textContent = '\u5173\u95ED';
  8694. return button;
  8695. })(), (() => {
  8696. const button = document.createElement('button');
  8697. button.style.padding = '0.5em';
  8698. button.style.margin = '0.2em';
  8699.  
  8700. button.onclick = e => {
  8701. if (!textarea.value) textarea.value = '{\n\n}';
  8702. textarea.value = textarea.value.replace(/,(\s|\n)*}/, '\n}').replace(/,(\s|\n),/g, ',\n').replace(/,(\s|\n)*]/g, ']');
  8703. const userdata = {};
  8704. try {
  8705. userdata.oped = JSON.parse(textarea.value);
  8706. } catch (e) {
  8707. alert('片头片尾: ' + e);throw e;
  8708. }
  8709. e.target.textContent = '格式没有问题!';
  8710. return userdata;
  8711. };
  8712.  
  8713. button.textContent = '\u9A8C\u8BC1\u683C\u5F0F';
  8714. return button;
  8715. })(), (() => {
  8716. const button = document.createElement('button');
  8717. button.style.padding = '0.5em';
  8718. button.style.margin = '0.2em';
  8719.  
  8720. button.onclick = e => {
  8721. polyfill.userdata = e.target.previousElementSibling.onclick({ target: e.target.previousElementSibling });
  8722. polyfill.saveUserdata();
  8723. e.target.textContent = '保存成功';
  8724. };
  8725.  
  8726. button.textContent = '\u5C1D\u8BD5\u4FDD\u5B58';
  8727. return button;
  8728. })());
  8729.  
  8730. return div;
  8731. }
  8732.  
  8733. displayPolyfillDataDiv(polyfill) {
  8734. const div = this.buildPolyfillDataDiv();
  8735. document.body.append(div);
  8736. div.style.display = 'block';
  8737.  
  8738. return div;
  8739. }
  8740.  
  8741. // Common
  8742. static buildDownloadAllPageDefaultFormatsBody(ret) {
  8743. const table = document.createElement('table');
  8744.  
  8745. table.onclick = e => e.stopPropagation();
  8746.  
  8747. for (const i of ret) {
  8748. table.append((() => {
  8749. const tr1 = document.createElement('tr');
  8750. const td1 = document.createElement('td');
  8751. td1.textContent = `
  8752. ${i.name}
  8753. `;
  8754. tr1.append(td1);
  8755. const td2 = document.createElement('td');
  8756. const a1 = document.createElement('a');
  8757. a1.href = i.durl[0];
  8758. a1.download = '';
  8759. a1.setAttribute('referrerpolicy', 'origin');
  8760. a1.textContent = i.durl[0];
  8761. td2.append(a1);
  8762. tr1.append(td2);
  8763. const td3 = document.createElement('td');
  8764. const a2 = document.createElement('a');
  8765. a2.href = i.danmuku;
  8766. a2.download = `${i.outputName}.ass`;
  8767. a2.setAttribute('referrerpolicy', 'origin');
  8768. a2.textContent = i.danmuku;
  8769. td3.append(a2);
  8770. tr1.append(td3);
  8771. return tr1;
  8772. })(), ...i.durl.slice(1).map(href => {
  8773. const tr1 = document.createElement('tr');
  8774. const td1 = document.createElement('td');
  8775. td1.textContent = `
  8776. `;
  8777. tr1.append(td1);
  8778. const td2 = document.createElement('td');
  8779. const a1 = document.createElement('a');
  8780. a1.href = href;
  8781. a1.download = '';
  8782. a1.setAttribute('referrerpolicy', 'origin');
  8783. a1.textContent = href;
  8784. td2.append(a1);
  8785. tr1.append(td2);
  8786. const td3 = document.createElement('td');
  8787. td3.textContent = `
  8788. `;
  8789. tr1.append(td3);
  8790. return tr1;
  8791. }));
  8792. }
  8793.  
  8794. const fragment = document.createDocumentFragment();
  8795. const style1 = document.createElement('style');
  8796. style1.textContent = `
  8797. table {
  8798. width: 100%;
  8799. table-layout: fixed;
  8800. }
  8801. td {
  8802. overflow: hidden;
  8803. white-space: nowrap;
  8804. text-overflow: ellipsis;
  8805. text-align: center;
  8806. }
  8807. `;
  8808. fragment.append(style1);
  8809. const h1 = document.createElement('h1');
  8810. h1.textContent = '(\u6D4B\u8BD5) \u6279\u91CF\u6293\u53D6';
  8811. fragment.append(h1);
  8812. const ul1 = document.createElement('ul');
  8813. const li = document.createElement('li');
  8814. const p = document.createElement('p');
  8815. p.textContent = '\u53EA\u6293\u53D6\u9ED8\u8BA4\u6E05\u6670\u5EA6';
  8816. li.append(p);
  8817. ul1.append(li);
  8818. const li1 = document.createElement('li');
  8819. const p1 = document.createElement('p');
  8820. p1.textContent = '\u590D\u5236\u94FE\u63A5\u5730\u5740\u65E0\u6548\uFF0C\u8BF7\u5DE6\u952E\u5355\u51FB/\u53F3\u952E\u53E6\u5B58\u4E3A/\u53F3\u952E\u8C03\u7528\u4E0B\u8F7D\u5DE5\u5177';
  8821. li1.append(p1);
  8822. const p2 = document.createElement('p');
  8823. const em = document.createElement('em');
  8824. em.textContent = '\u5F00\u53D1\u8005\uFF1A\u9700\u8981\u6821\u9A8Creferrer\u548Cuser agent';
  8825. p2.append(em);
  8826. li1.append(p2);
  8827. ul1.append(li1);
  8828. const li2 = document.createElement('li');
  8829. const p3 = document.createElement('p');
  8830. p3.append('flv\u5408\u5E76');
  8831. const a1 = document.createElement('a');
  8832. a1.href = 'http://www.flvcd.com/teacher2.htm';
  8833. a1.textContent = '\u7855\u9F20';
  8834. p3.append(a1);
  8835. li2.append(p3);
  8836. const p4 = document.createElement('p');
  8837. p4.textContent = '\u6279\u91CF\u5408\u5E76\u5BF9\u5355\u6807\u7B7E\u9875\u8D1F\u8377\u592A\u5927';
  8838. li2.append(p4);
  8839. const p5 = document.createElement('p');
  8840. const em1 = document.createElement('em');
  8841. em1.textContent = '\u5F00\u53D1\u8005\uFF1A\u53EF\u4EE5\u7528webworker\uFF0C\u4F46\u662F\u6211\u6CA1\u9700\u6C42\uFF0C\u53C8\u61D2';
  8842. p5.append(em1);
  8843. li2.append(p5);
  8844. ul1.append(li2);
  8845. fragment.append(ul1);
  8846. fragment.append(table);
  8847. return fragment;
  8848. }
  8849.  
  8850. static displayDownloadAllPageDefaultFormatsBody(ret) {
  8851. top.document.open();
  8852. top.document.close();
  8853.  
  8854. top.document.body.append(UI.buildDownloadAllPageDefaultFormatsBody(ret));
  8855. return ret;
  8856. }
  8857.  
  8858. static genDiv() {
  8859. const div1 = document.createElement('div');
  8860. div1.style.position = 'fixed';
  8861. div1.style.zIndex = '10036';
  8862. div1.style.top = '50%';
  8863. div1.style.marginTop = '-200px';
  8864. div1.style.left = '50%';
  8865. div1.style.marginLeft = '-320px';
  8866. div1.style.width = '540px';
  8867. div1.style.maxHeight = '400px';
  8868. div1.style.overflowY = 'auto';
  8869. div1.style.padding = '30px 50px';
  8870. div1.style.backgroundColor = 'white';
  8871. div1.style.borderRadius = '6px';
  8872. div1.style.boxShadow = 'rgba(0, 0, 0, 0.6) 1px 1px 40px 0px';
  8873. div1.style.display = 'none';
  8874. div1.addEventListener('click', e => e.stopPropagation());
  8875. div1.className = 'bilitwin';
  8876.  
  8877. return div1;
  8878. }
  8879.  
  8880. static requestH5Player() {
  8881. const h = document.querySelector('div.tminfo');
  8882. h.prepend('[[脚本需要HTML5播放器(弹幕列表右上角三个点的按钮切换)]] ');
  8883. }
  8884.  
  8885. static allowDrag(e) {
  8886. e.stopPropagation();
  8887. e.preventDefault();
  8888. }
  8889.  
  8890. static beforeUnloadHandler(e) {
  8891. return e.returnValue = '脚本还没做完工作,真的要退出吗?';
  8892. }
  8893.  
  8894. static hintInfo(text, playerWin) {
  8895. const div = document.createElement('div');
  8896. {
  8897. div.className = 'bilibili-player-video-toast-bottom';
  8898. const div1 = document.createElement('div');
  8899. div1.className = 'bilibili-player-video-toast-item';
  8900. const div2 = document.createElement('div');
  8901. div2.className = 'bilibili-player-video-toast-item-text';
  8902. const span = document.createElement('span');
  8903. span.textContent = text;
  8904. div2.append(span);
  8905. div1.append(div2);
  8906. div.append(div1);
  8907. }
  8908. playerWin.document.getElementsByClassName('bilibili-player-video-toast-wrp')[0].append(div);
  8909. setTimeout(() => div.remove(), 3000);
  8910. }
  8911.  
  8912. static get optionDescriptions() {
  8913. return [
  8914. // 1. automation
  8915. ['autoDanmaku', '下载视频也触发下载弹幕'],
  8916.  
  8917. // 2. user interface
  8918. ['title', '在视频标题旁添加链接'], ['menu', '在视频菜单栏添加链接'],
  8919.  
  8920. // 3. download
  8921. ['aria2', '导出aria2'], ['aria2RPC', '发送到aria2 RPC'], ['m3u8', '(限VLC兼容播放器)导出m3u8'], ['clipboard', '(测)(请自行解决referrer)强制导出剪贴板']];
  8922. }
  8923.  
  8924. static get optionDefaults() {
  8925. return {
  8926. // 1. automation
  8927. autoDanmaku: false,
  8928.  
  8929. // 2. user interface
  8930. title: true,
  8931. menu: true,
  8932.  
  8933. // 3. download
  8934. aria2: false,
  8935. aria2RPC: false,
  8936. m3u8: false,
  8937. clipboard: false
  8938. };
  8939. }
  8940. }
  8941.  
  8942. /***
  8943. * Copyright (C) 2018 Qli5. All Rights Reserved.
  8944. *
  8945. * @author qli5 <goodlq11[at](163|gmail).com>
  8946. *
  8947. * This Source Code Form is subject to the terms of the Mozilla Public
  8948. * License, v. 2.0. If a copy of the MPL was not distributed with this
  8949. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8950. */
  8951.  
  8952. let debugOption = { debug: 1 };
  8953.  
  8954. class BiliTwin extends BiliUserJS {
  8955. static get debugOption() {
  8956. return debugOption;
  8957. }
  8958.  
  8959. static set debugOption(option) {
  8960. debugOption = option;
  8961. }
  8962.  
  8963. constructor(option = {}, ui) {
  8964. super();
  8965. this.BiliMonkey = BiliMonkey;
  8966. this.BiliPolyfill = BiliPolyfill;
  8967. this.playerWin = null;
  8968. this.monkey = null;
  8969. this.polifill = null;
  8970. this.ui = ui || new UI(this);
  8971. this.option = option;
  8972. }
  8973.  
  8974. async runCidSession() {
  8975. // 1. playerWin and option
  8976. try {
  8977. // you know what? it is a race, data race for jq! try not to yield to others!
  8978. this.playerWin = BiliUserJS.tryGetPlayerWinSync() || await BiliTwin.getPlayerWin();
  8979. }
  8980. catch (e) {
  8981. if (e == 'Need H5 Player') UI.requestH5Player();
  8982. throw e;
  8983. }
  8984. const href = location.href;
  8985. this.option = this.getOption();
  8986. if (this.option.debug) {
  8987. if (top.console) top.console.clear();
  8988. }
  8989.  
  8990. // 2. monkey and polyfill
  8991. this.monkey = new BiliMonkey(this.playerWin, this.option);
  8992. this.polyfill = new BiliPolyfill(this.playerWin, this.option, t => UI.hintInfo(t, this.playerWin));
  8993. await Promise.all([this.monkey.execOptions(), this.polyfill.setFunctions()]);
  8994.  
  8995. // 3. async consistent => render UI
  8996. const cidRefresh = BiliTwin.getCidRefreshPromise(this.playerWin);
  8997. if (href == location.href) {
  8998. this.ui.option = this.option;
  8999. this.ui.cidSessionRender();
  9000. }
  9001. else {
  9002. cidRefresh.resolve();
  9003. }
  9004.  
  9005. // 4. debug
  9006. if (this.option.debug) {
  9007. [(top.unsafeWindow || top).monkey, (top.unsafeWindow || top).polyfill] = [this.monkey, this.polyfill];
  9008. }
  9009.  
  9010. // 5. refresh => session expire
  9011. await cidRefresh;
  9012. this.monkey.destroy();
  9013. this.polyfill.destroy();
  9014. this.ui.cidSessionDestroy();
  9015. }
  9016.  
  9017. async mergeFLVFiles(files) {
  9018. return URL.createObjectURL(await FLV.mergeBlobs(files));
  9019. }
  9020.  
  9021. async clearCacheDB(cache) {
  9022. if (cache) return cache.deleteEntireDB();
  9023. }
  9024.  
  9025. resetOption(option = this.option) {
  9026. option.setStorage('BiliTwin', JSON.stringify({}));
  9027. return this.option = {};
  9028. }
  9029.  
  9030. getOption(playerWin = this.playerWin) {
  9031. let rawOption = null;
  9032. try {
  9033. rawOption = JSON.parse(playerWin.localStorage.getItem('BiliTwin'));
  9034. }
  9035. catch (e) { }
  9036. finally {
  9037. if (!rawOption) rawOption = {};
  9038. rawOption.setStorage = (n, i) => playerWin.localStorage.setItem(n, i);
  9039. rawOption.getStorage = n => playerWin.localStorage.getItem(n);
  9040. return Object.assign(
  9041. {},
  9042. BiliMonkey.optionDefaults,
  9043. BiliPolyfill.optionDefaults,
  9044. UI.optionDefaults,
  9045. rawOption,
  9046. BiliTwin.debugOption,
  9047. );
  9048. }
  9049. }
  9050.  
  9051. saveOption(option = this.option) {
  9052. return option.setStorage('BiliTwin', JSON.stringify(option));
  9053. }
  9054.  
  9055. static async init() {
  9056. if (!document.body) return;
  9057. BiliTwin.outdatedEngineClearance();
  9058. BiliTwin.firefoxClearance();
  9059.  
  9060. const twin = new BiliTwin();
  9061.  
  9062. while (1) {
  9063. await twin.runCidSession();
  9064. }
  9065. }
  9066.  
  9067. static outdatedEngineClearance() {
  9068. if (typeof Promise != 'function' || typeof MutationObserver != 'function') {
  9069. alert('这个浏览器实在太老了,脚本决定罢工。');
  9070. throw 'BiliTwin: browser outdated: Promise or MutationObserver unsupported';
  9071. }
  9072. }
  9073.  
  9074. static firefoxClearance() {
  9075. if (navigator.userAgent.includes('Firefox')) {
  9076. BiliTwin.debugOption.proxy = false;
  9077. if (!window.navigator.temporaryStorage && !window.navigator.mozTemporaryStorage) window.navigator.temporaryStorage = { queryUsageAndQuota: func => func(-1048576, 10484711424) };
  9078. }
  9079. }
  9080.  
  9081. static xpcWrapperClearance() {
  9082. if (top.unsafeWindow) {
  9083. Object.defineProperty(window, 'cid', {
  9084. configurable: true,
  9085. get: () => String(unsafeWindow.cid)
  9086. });
  9087. Object.defineProperty(window, 'player', {
  9088. configurable: true,
  9089. get: () => ({ destroy: unsafeWindow.player.destroy, reloadAccess: unsafeWindow.player.reloadAccess })
  9090. });
  9091. Object.defineProperty(window, 'jQuery', {
  9092. configurable: true,
  9093. get: () => unsafeWindow.jQuery,
  9094. });
  9095. Object.defineProperty(window, 'fetch', {
  9096. configurable: true,
  9097. get: () => unsafeWindow.fetch.bind(unsafeWindow),
  9098. set: _fetch => unsafeWindow.fetch = _fetch.bind(unsafeWindow)
  9099. });
  9100. }
  9101. }
  9102. }
  9103.  
  9104. BiliTwin.domContentLoadedThen(BiliTwin.init);