bilibili merged flv+mp4+ass+enhance

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

目前為 2020-03-27 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name bilibili merged flv+mp4+ass+enhance
  3. // @namespace http://qli5.tk/
  4. // @homepageURL https://github.com/Xmader/bilitwin/
  5. // @supportURL https://github.com/Xmader/bilitwin/issues
  6. // @description bilibili/哔哩哔哩:超清FLV下载,FLV合并,原生MP4下载,弹幕ASS下载,CC字幕转码ASS下载,AAC音频下载,MKV打包,播放体验增强,原生appsecret,不借助其他网站
  7. // @match *://www.bilibili.com/video/av*
  8. // @match *://www.bilibili.com/video/bv*
  9. // @match *://www.bilibili.com/video/BV*
  10. // @match *://bangumi.bilibili.com/anime/*/play*
  11. // @match *://www.bilibili.com/bangumi/play/ep*
  12. // @match *://www.bilibili.com/bangumi/play/ss*
  13. // @match *://www.bilibili.com/bangumi/media/md*
  14. // @match *://www.biligame.com/detail/*
  15. // @match *://vc.bilibili.com/video/*
  16. // @match *://www.bilibili.com/watchlater/
  17. // @version 1.23.13
  18. // @author qli5
  19. // @copyright qli5, 2014+, 田生, grepmusic, zheng qian, ryiwamoto, xmader
  20. // @license Mozilla Public License 2.0; http://www.mozilla.org/MPL/2.0/
  21. // @grant none
  22. // @run-at document-start
  23. // ==/UserScript==
  24.  
  25. /***
  26. *
  27. * @author qli5 <goodlq11[at](163|gmail).com>
  28. *
  29. * BiliTwin consists of two parts - BiliMonkey and BiliPolyfill.
  30. * They are bundled because I am too lazy to write two user interfaces.
  31. *
  32. * So what is the difference between BiliMonkey and BiliPolyfill?
  33. *
  34. * BiliMonkey deals with network. It is a (naIve) Service Worker.
  35. * This is also why it uses IndexedDB instead of localStorage.
  36. * BiliPolyfill deals with experience. It is more a "user script".
  37. * Everything it can do can be done by hand.
  38. *
  39. * BiliPolyfill will be pointless in the long run - I believe bilibili
  40. * will finally provide these functions themselves.
  41. *
  42. * This Source Code Form is subject to the terms of the Mozilla Public
  43. * License, v. 2.0. If a copy of the MPL was not distributed with this
  44. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  45. *
  46. * Covered Software is provided under this License on an “as is” basis,
  47. * without warranty of any kind, either expressed, implied, or statutory,
  48. * including, without limitation, warranties that the Covered Software
  49. * is free of defects, merchantable, fit for a particular purpose or
  50. * non-infringing. The entire risk as to the quality and performance of
  51. * the Covered Software is with You. Should any Covered Software prove
  52. * defective in any respect, You (not any Contributor) assume the cost
  53. * of any necessary servicing, repair, or correction. This disclaimer
  54. * of warranty constitutes an essential part of this License. No use of
  55. * any Covered Software is authorized under this License except under
  56. * this disclaimer.
  57. *
  58. * Under no circumstances and under no legal theory, whether tort
  59. * (including negligence), contract, or otherwise, shall any Contributor,
  60. * or anyone who distributes Covered Software as permitted above, be
  61. * liable to You for any direct, indirect, special, incidental, or
  62. * consequential damages of any character including, without limitation,
  63. * damages for lost profits, loss of goodwill, work stoppage, computer
  64. * failure or malfunction, or any and all other commercial damages or
  65. * losses, even if such party shall have been informed of the possibility
  66. * of such damages. This limitation of liability shall not apply to
  67. * liability for death or personal injury resulting from such party’s
  68. * negligence to the extent applicable law prohibits such limitation.
  69. * Some jurisdictions do not allow the exclusion or limitation of
  70. * incidental or consequential damages, so this exclusion and limitation
  71. * may not apply to You.
  72. */
  73.  
  74. /***
  75. * This is a bundled code. While it is not uglified, it may still be too
  76. * complex for reviewing. Please refer to
  77. * https://github.com/Xmader/bilitwin/
  78. * for source code.
  79. */
  80.  
  81. /***
  82. * Copyright (C) 2018 Qli5. All Rights Reserved.
  83. *
  84. * @author qli5 <goodlq11[at](163|gmail).com>
  85. *
  86. * This Source Code Form is subject to the terms of the Mozilla Public
  87. * License, v. 2.0. If a copy of the MPL was not distributed with this
  88. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  89. */
  90.  
  91. /**
  92. * Basically a Promise that exposes its resolve and reject callbacks
  93. */
  94. class AsyncContainer {
  95. /***
  96. * The thing is, if we cannot cancel a promise, we should at least be able to
  97. * explicitly mark a promise as garbage collectible.
  98. *
  99. * Yes, this is something like cancelable Promise. But I insist they are different.
  100. */
  101. constructor(callback) {
  102. // 1. primary promise
  103. this.primaryPromise = new Promise((s, j) => {
  104. this.resolve = arg => { s(arg); return arg; };
  105. this.reject = arg => { j(arg); return arg; };
  106. });
  107.  
  108. // 2. hang promise
  109. this.hangReturn = Symbol();
  110. this.hangPromise = new Promise(s => this.hang = () => s(this.hangReturn));
  111. this.destroiedThen = this.hangPromise.then.bind(this.hangPromise);
  112. this.primaryPromise.then(() => this.state = 'fulfilled');
  113. this.primaryPromise.catch(() => this.state = 'rejected');
  114. this.hangPromise.then(() => this.state = 'hanged');
  115.  
  116. // 4. race
  117. this.promise = Promise
  118. .race([this.primaryPromise, this.hangPromise])
  119. .then(s => s == this.hangReturn ? new Promise(() => { }) : s);
  120.  
  121. // 5. inherit
  122. this.then = this.promise.then.bind(this.promise);
  123. this.catch = this.promise.catch.bind(this.promise);
  124. this.finally = this.promise.finally.bind(this.promise);
  125.  
  126. // 6. optional callback
  127. if (typeof callback == 'function') callback(this.resolve, this.reject);
  128. }
  129.  
  130. /***
  131. * Memory leak notice:
  132. *
  133. * The V8 implementation of Promise requires
  134. * 1. the resolve handler of a Promise
  135. * 2. the reject handler of a Promise
  136. * 3. !! the Promise object itself !!
  137. * to be garbage collectible to correctly free Promise runtime contextes
  138. *
  139. * This piece of code will work
  140. * void (async () => {
  141. * const buf = new Uint8Array(1024 * 1024 * 1024);
  142. * for (let i = 0; i < buf.length; i++) buf[i] = i;
  143. * await new Promise(() => { });
  144. * return buf;
  145. * })();
  146. * if (typeof gc == 'function') gc();
  147. *
  148. * This piece of code will cause a Promise context mem leak
  149. * const deadPromise = new Promise(() => { });
  150. * void (async () => {
  151. * const buf = new Uint8Array(1024 * 1024 * 1024);
  152. * for (let i = 0; i < buf.length; i++) buf[i] = i;
  153. * await deadPromise;
  154. * return buf;
  155. * })();
  156. * if (typeof gc == 'function') gc();
  157. *
  158. * In other words, do NOT directly inherit from promise. You will need to
  159. * dereference it on destroying.
  160. */
  161. destroy() {
  162. this.hang();
  163. this.resolve = () => { };
  164. this.reject = this.resolve;
  165. this.hang = this.resolve;
  166. this.primaryPromise = null;
  167. this.hangPromise = null;
  168. this.promise = null;
  169. this.then = this.resolve;
  170. this.catch = this.resolve;
  171. this.finally = this.resolve;
  172. this.destroiedThen = f => f();
  173. /***
  174. * For ease of debug, do not dereference hangReturn
  175. *
  176. * If run from console, mysteriously this tiny symbol will help correct gc
  177. * before a console.clear
  178. */
  179. //this.hangReturn = null;
  180. }
  181.  
  182. static _UNIT_TEST() {
  183. const containers = [];
  184. async function foo() {
  185. const buf = new Uint8Array(600 * 1024 * 1024);
  186. for (let i = 0; i < buf.length; i++) buf[i] = i;
  187. const ac = new AsyncContainer();
  188. ac.destroiedThen(() => console.log('asyncContainer destroied'));
  189. containers.push(ac);
  190. await ac;
  191. return buf;
  192. }
  193. const foos = [foo(), foo(), foo()];
  194. containers.forEach(e => e.destroy());
  195. console.warn('Check your RAM usage. I allocated 1.8GB in three dead-end promises.');
  196. return [foos, containers];
  197. }
  198. }
  199.  
  200. /***
  201. * Copyright (C) 2018 Qli5. All Rights Reserved.
  202. *
  203. * @author qli5 <goodlq11[at](163|gmail).com>
  204. *
  205. * This Source Code Form is subject to the terms of the Mozilla Public
  206. * License, v. 2.0. If a copy of the MPL was not distributed with this
  207. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  208. */
  209.  
  210. /**
  211. * Provides common util for all bilibili user scripts
  212. */
  213. class BiliUserJS {
  214. static async getIframeWin() {
  215. if (document.querySelector('#bofqi > iframe').contentDocument.getElementById('bilibiliPlayer')) {
  216. return document.querySelector('#bofqi > iframe').contentWindow;
  217. }
  218. else {
  219. return new Promise(resolve => {
  220. document.querySelector('#bofqi > iframe').addEventListener('load', () => {
  221. resolve(document.querySelector('#bofqi > iframe').contentWindow);
  222. }, { once: true });
  223. });
  224. }
  225. }
  226.  
  227. static async getPlayerWin() {
  228. if (location.href.includes('/watchlater/#/list')) {
  229. await new Promise(resolve => {
  230. window.addEventListener('hashchange', () => resolve(location.href), { once: true });
  231. });
  232. }
  233. if (!document.getElementById('bofqi')) {
  234. if (document.querySelector("video")) {
  235. top.location.reload(); // 刷新
  236. } else {
  237. await new Promise(resolve => {
  238. const observer = new MutationObserver(() => {
  239. if (document.getElementById('bofqi')) {
  240. resolve(document.getElementById('bofqi'));
  241. observer.disconnect();
  242. }
  243. });
  244. observer.observe(document, { childList: true, subtree: true });
  245. });
  246. }
  247. }
  248. if (document.getElementById('bilibiliPlayer')) {
  249. return window;
  250. }
  251. else if (document.querySelector('#bofqi > iframe')) {
  252. return BiliUserJS.getIframeWin();
  253. }
  254. else if (document.querySelector('#bofqi > object')) {
  255. throw 'Need H5 Player';
  256. }
  257. else {
  258. return new Promise(resolve => {
  259. const observer = new MutationObserver(() => {
  260. if (document.getElementById('bilibiliPlayer')) {
  261. observer.disconnect();
  262. resolve(window);
  263. }
  264. else if (document.querySelector('#bofqi > iframe')) {
  265. observer.disconnect();
  266. resolve(BiliUserJS.getIframeWin());
  267. }
  268. else if (document.querySelector('#bofqi > object')) {
  269. observer.disconnect();
  270. throw 'Need H5 Player';
  271. }
  272. });
  273. observer.observe(document.getElementById('bofqi'), { childList: true });
  274. });
  275. }
  276. }
  277.  
  278. static tryGetPlayerWinSync() {
  279. if (document.getElementById('bilibiliPlayer')) {
  280. return window;
  281. }
  282. else if (document.querySelector('#bofqi > object')) {
  283. throw 'Need H5 Player';
  284. }
  285. }
  286.  
  287. static getCidRefreshPromise(playerWin) {
  288. /***********
  289. * !!!Race condition!!!
  290. * We must finish everything within one microtask queue!
  291. *
  292. * bilibili script:
  293. * videoElement.remove() -> setTimeout(0) -> [[microtask]] -> load playurl
  294. * \- synchronous macrotask -/ || \- synchronous
  295. * ||
  296. * the only position to inject monkey.sniffDefaultFormat
  297. */
  298. const cidRefresh = new AsyncContainer();
  299.  
  300. // 1. no active video element in document => cid refresh
  301. const observer = new MutationObserver(() => {
  302. if (!playerWin.document.getElementsByTagName('video')[0]) {
  303. observer.disconnect();
  304. cidRefresh.resolve();
  305. }
  306. });
  307. observer.observe(playerWin.document.getElementById('bilibiliPlayer'), { childList: true });
  308.  
  309. // 2. playerWin unload => cid refresh
  310. playerWin.addEventListener('unload', () => Promise.resolve().then(() => cidRefresh.resolve()));
  311.  
  312. return cidRefresh;
  313. }
  314.  
  315. static async domContentLoadedThen(func) {
  316. if (document.readyState == 'loading') {
  317. return new Promise(resolve => {
  318. document.addEventListener('DOMContentLoaded', () => resolve(func()), { once: true });
  319. })
  320. }
  321. else {
  322. return func();
  323. }
  324. }
  325. }
  326.  
  327. /**
  328. * Copyright (C) 2018 Xmader.
  329. * @author Xmader
  330. */
  331.  
  332. /**
  333. * @template T
  334. * @param {Promise<T>} promise
  335. * @param {number} ms
  336. * @returns {Promise< T | null >}
  337. */
  338. const setTimeoutDo = (promise, ms) => {
  339. /** @type {Promise<null>} */
  340. const t = new Promise((resolve) => {
  341. setTimeout(() => resolve(null), ms);
  342. });
  343. return Promise.race([promise, t])
  344. };
  345.  
  346. /***
  347. * Copyright (C) 2018 Qli5. All Rights Reserved.
  348. *
  349. * @author qli5 <goodlq11[at](163|gmail).com>
  350. *
  351. * This Source Code Form is subject to the terms of the Mozilla Public
  352. * License, v. 2.0. If a copy of the MPL was not distributed with this
  353. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  354. */
  355.  
  356. /**
  357. * A promisified indexedDB with large file(>100MB) support
  358. */
  359. class CacheDB {
  360. constructor(dbName = 'biliMonkey', osName = 'flv', keyPath = 'name', maxItemSize = 100 * 1024 * 1024) {
  361. // Neither Chrome or Firefox can handle item size > 100M
  362. this.dbName = dbName;
  363. this.osName = osName;
  364. this.keyPath = keyPath;
  365. this.maxItemSize = maxItemSize;
  366. this.db = null;
  367. }
  368.  
  369. async getDB() {
  370. if (this.db) return this.db;
  371. this.db = await new Promise((resolve, reject) => {
  372. const openRequest = indexedDB.open(this.dbName);
  373. openRequest.onupgradeneeded = e => {
  374. const db = e.target.result;
  375. if (!db.objectStoreNames.contains(this.osName)) {
  376. db.createObjectStore(this.osName, { keyPath: this.keyPath });
  377. }
  378. };
  379. openRequest.onsuccess = e => {
  380. return resolve(e.target.result);
  381. };
  382. openRequest.onerror = reject;
  383. });
  384. return this.db;
  385. }
  386.  
  387. async addData(item, name = item.name, data = item.data || item) {
  388. if (!data instanceof Blob) throw 'CacheDB: data must be a Blob';
  389. const itemChunks = [];
  390. const numChunks = Math.ceil(data.size / this.maxItemSize);
  391. for (let i = 0; i < numChunks; i++) {
  392. itemChunks.push({
  393. name: `${name}/part_${i}`,
  394. numChunks,
  395. data: data.slice(i * this.maxItemSize, (i + 1) * this.maxItemSize)
  396. });
  397. }
  398.  
  399. const reqCascade = new Promise(async (resolve, reject) => {
  400. const db = await this.getDB();
  401. const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
  402. const onsuccess = e => {
  403. const chunk = itemChunks.pop();
  404. if (!chunk) return resolve(e);
  405. const req = objectStore.add(chunk);
  406. req.onerror = reject;
  407. req.onsuccess = onsuccess;
  408. };
  409. onsuccess();
  410. });
  411.  
  412. return reqCascade;
  413. }
  414.  
  415. async putData(item, name = item.name, data = item.data || item) {
  416. if (!data instanceof Blob) throw 'CacheDB: data must be a Blob';
  417. const itemChunks = [];
  418. const numChunks = Math.ceil(data.size / this.maxItemSize);
  419. for (let i = 0; i < numChunks; i++) {
  420. itemChunks.push({
  421. name: `${name}/part_${i}`,
  422. numChunks,
  423. data: data.slice(i * this.maxItemSize, (i + 1) * this.maxItemSize)
  424. });
  425. }
  426.  
  427. const reqCascade = new Promise(async (resolve, reject) => {
  428. const db = await this.getDB();
  429. const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
  430. const onsuccess = e => {
  431. const chunk = itemChunks.pop();
  432. if (!chunk) return resolve(e);
  433. const req = objectStore.put(chunk);
  434. req.onerror = reject;
  435. req.onsuccess = onsuccess;
  436. };
  437. onsuccess();
  438. });
  439.  
  440. return reqCascade;
  441. }
  442.  
  443. async getData(name) {
  444. const reqCascade = new Promise(async (resolve, reject) => {
  445. const dataChunks = [];
  446. const db = await this.getDB(); // 浏览器默认在隐私浏览模式中禁用 IndexedDB ,这一步会超时
  447. const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
  448. const probe = objectStore.get(`${name}/part_0`);
  449. probe.onerror = reject;
  450. probe.onsuccess = e => {
  451. // 1. Probe fails => key does not exist
  452. if (!probe.result) return resolve(null);
  453.  
  454. // 2. How many chunks to retrieve?
  455. const { numChunks } = probe.result;
  456.  
  457. // 3. Cascade on the remaining chunks
  458. const onsuccess = e => {
  459. dataChunks.push(e.target.result.data);
  460. if (dataChunks.length == numChunks) return resolve(dataChunks);
  461. const req = objectStore.get(`${name}/part_${dataChunks.length}`);
  462. req.onerror = reject;
  463. req.onsuccess = onsuccess;
  464. };
  465. onsuccess(e);
  466. };
  467. });
  468.  
  469. // 浏览器默认在隐私浏览模式中禁用 IndexedDB ,添加超时
  470. const dataChunks = await setTimeoutDo(reqCascade, 5 * 1000);
  471.  
  472. return dataChunks ? { name, data: new Blob(dataChunks) } : null;
  473. }
  474.  
  475. async deleteData(name) {
  476. const reqCascade = new Promise(async (resolve, reject) => {
  477. let currentChunkNum = 0;
  478. const db = await this.getDB();
  479. const objectStore = db.transaction([this.osName], 'readwrite').objectStore(this.osName);
  480. const probe = objectStore.get(`${name}/part_0`);
  481. probe.onerror = reject;
  482. probe.onsuccess = e => {
  483. // 1. Probe fails => key does not exist
  484. if (!probe.result) return resolve(null);
  485.  
  486. // 2. How many chunks to delete?
  487. const { numChunks } = probe.result;
  488.  
  489. // 3. Cascade on the remaining chunks
  490. const onsuccess = e => {
  491. const req = objectStore.delete(`${name}/part_${currentChunkNum}`);
  492. req.onerror = reject;
  493. req.onsuccess = onsuccess;
  494. currentChunkNum++;
  495. if (currentChunkNum == numChunks) return resolve(e);
  496. };
  497. onsuccess();
  498. };
  499. });
  500.  
  501. return reqCascade;
  502. }
  503.  
  504. async deleteEntireDB() {
  505. const req = indexedDB.deleteDatabase(this.dbName);
  506. return new Promise((resolve, reject) => {
  507. req.onsuccess = () => resolve(this.db = null);
  508. req.onerror = reject;
  509. });
  510. }
  511.  
  512. static async _UNIT_TEST() {
  513. let db = new CacheDB();
  514. console.warn('Storing 201MB...');
  515. console.log(await db.putData(new Blob([new ArrayBuffer(201 * 1024 * 1024)]), 'test'));
  516. console.warn('Deleting 201MB...');
  517. console.log(await db.deleteData('test'));
  518. }
  519. }
  520.  
  521. /***
  522. * Copyright (C) 2018 Qli5. All Rights Reserved.
  523. *
  524. * @author qli5 <goodlq11[at](163|gmail).com>
  525. *
  526. * This Source Code Form is subject to the terms of the Mozilla Public
  527. * License, v. 2.0. If a copy of the MPL was not distributed with this
  528. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  529. */
  530.  
  531. /**
  532. * A more powerful fetch with
  533. * 1. onprogress handler
  534. * 2. partial response getter
  535. */
  536. class DetailedFetchBlob {
  537. constructor(input, init = {}, onprogress = init.onprogress, onabort = init.onabort, onerror = init.onerror, fetch = init.fetch || top.fetch) {
  538. // Fire in the Fox fix
  539. if (this.firefoxConstructor(input, init, onprogress, onabort, onerror)) return;
  540. // Now I know why standardizing cancelable Promise is that difficult
  541. // PLEASE refactor me!
  542. this.onprogress = onprogress;
  543. this.onabort = onabort;
  544. this.onerror = onerror;
  545. this.abort = null;
  546. this.loaded = init.cacheLoaded || 0;
  547. this.total = init.cacheLoaded || 0;
  548. this.lengthComputable = false;
  549. this.buffer = [];
  550. this.blob = null;
  551. this.reader = null;
  552. this.blobPromise = fetch(input, init).then(/** @param {Response} res */ res => {
  553. if (this.reader == 'abort') return res.body.getReader().cancel().then(() => null);
  554. if (!res.ok) throw `HTTP Error ${res.status}: ${res.statusText}`;
  555. this.lengthComputable = res.headers.has('Content-Length');
  556. this.total += parseInt(res.headers.get('Content-Length')) || Infinity;
  557. if (this.lengthComputable) {
  558. this.reader = res.body.getReader();
  559. return this.blob = this.consume();
  560. }
  561. else {
  562. if (this.onprogress) this.onprogress(this.loaded, this.total, this.lengthComputable);
  563. return this.blob = res.blob();
  564. }
  565. });
  566. this.blobPromise.then(() => this.abort = () => { });
  567. this.blobPromise.catch(e => this.onerror({ target: this, type: e }));
  568. this.promise = Promise.race([
  569. this.blobPromise,
  570. new Promise(resolve => this.abort = () => {
  571. this.onabort({ target: this, type: 'abort' });
  572. resolve('abort');
  573. this.buffer = [];
  574. this.blob = null;
  575. if (this.reader) this.reader.cancel();
  576. else this.reader = 'abort';
  577. })
  578. ]).then(s => s == 'abort' ? new Promise(() => { }) : s);
  579. this.then = this.promise.then.bind(this.promise);
  580. this.catch = this.promise.catch.bind(this.promise);
  581. }
  582.  
  583. getPartialBlob() {
  584. return new Blob(this.buffer);
  585. }
  586.  
  587. async getBlob() {
  588. return this.promise;
  589. }
  590.  
  591. async pump() {
  592. while (true) {
  593. let { done, value } = await this.reader.read();
  594. if (done) return this.loaded;
  595. this.loaded += value.byteLength;
  596. this.buffer.push(new Blob([value]));
  597. if (this.onprogress) this.onprogress(this.loaded, this.total, this.lengthComputable);
  598. }
  599. }
  600.  
  601. async consume() {
  602. await this.pump();
  603. this.blob = new Blob(this.buffer);
  604. this.buffer = null;
  605. return this.blob;
  606. }
  607.  
  608. firefoxConstructor(input, init = {}, onprogress = init.onprogress, onabort = init.onabort, onerror = init.onerror) {
  609. if (!top.navigator.userAgent.includes('Firefox')) return false;
  610.  
  611. const firefoxVersionM = top.navigator.userAgent.match(/Firefox\/(\d+)/);
  612. const firefoxVersion = firefoxVersionM && +firefoxVersionM[1];
  613. if (firefoxVersion >= 65) {
  614. // xhr.responseType "moz-chunked-arraybuffer" is deprecated since Firefox 68
  615. // but res.body is implemented since Firefox 65
  616. return false
  617. }
  618.  
  619. this.onprogress = onprogress;
  620. this.onabort = onabort;
  621. this.onerror = onerror;
  622. this.abort = null;
  623. this.loaded = init.cacheLoaded || 0;
  624. this.total = init.cacheLoaded || 0;
  625. this.lengthComputable = false;
  626. this.buffer = [];
  627. this.blob = null;
  628. this.reader = undefined;
  629. this.blobPromise = new Promise((resolve, reject) => {
  630. let xhr = new XMLHttpRequest();
  631. xhr.responseType = 'moz-chunked-arraybuffer';
  632. xhr.onload = () => { resolve(this.blob = new Blob(this.buffer)); this.buffer = null; };
  633. let cacheLoaded = this.loaded;
  634. xhr.onprogress = e => {
  635. this.loaded = e.loaded + cacheLoaded;
  636. this.total = e.total + cacheLoaded;
  637. this.lengthComputable = e.lengthComputable;
  638. this.buffer.push(new Blob([xhr.response]));
  639. if (this.onprogress) this.onprogress(this.loaded, this.total, this.lengthComputable);
  640. };
  641. xhr.onabort = e => this.onabort({ target: this, type: 'abort' });
  642. xhr.onerror = e => { this.onerror({ target: this, type: e.type }); reject(e); };
  643. this.abort = xhr.abort.bind(xhr);
  644. xhr.open(init.method || 'get', input);
  645. if (init.headers) {
  646. Object.entries(init.headers).forEach(([header, value]) => {
  647. xhr.setRequestHeader(header, value);
  648. });
  649. }
  650. xhr.send();
  651. });
  652. this.promise = this.blobPromise;
  653. this.then = this.promise.then.bind(this.promise);
  654. this.catch = this.promise.catch.bind(this.promise);
  655. return true;
  656. }
  657. }
  658.  
  659. /***
  660. * Copyright (C) 2018 Qli5. All Rights Reserved.
  661. *
  662. * @author qli5 <goodlq11[at](163|gmail).com>
  663. *
  664. * This Source Code Form is subject to the terms of the Mozilla Public
  665. * License, v. 2.0. If a copy of the MPL was not distributed with this
  666. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  667. */
  668.  
  669. /**
  670. * A simple emulation of pthread_mutex
  671. */
  672. class Mutex {
  673. constructor() {
  674. this.queueTail = Promise.resolve();
  675. this.resolveHead = null;
  676. }
  677.  
  678. /**
  679. * await mutex.lock = pthread_mutex_lock
  680. * @returns a promise to be resolved when the mutex is available
  681. */
  682. async lock() {
  683. let myResolve;
  684. let _queueTail = this.queueTail;
  685. this.queueTail = new Promise(resolve => myResolve = resolve);
  686. await _queueTail;
  687. this.resolveHead = myResolve;
  688. return;
  689. }
  690.  
  691. /**
  692. * mutex.unlock = pthread_mutex_unlock
  693. */
  694. unlock() {
  695. this.resolveHead();
  696. return;
  697. }
  698.  
  699. /**
  700. * lock, ret = await async, unlock, return ret
  701. * @param {(Function|Promise)} promise async thing to wait for
  702. */
  703. async lockAndAwait(promise) {
  704. await this.lock();
  705. let ret;
  706. try {
  707. if (typeof promise == 'function') promise = promise();
  708. ret = await promise;
  709. }
  710. finally {
  711. this.unlock();
  712. }
  713. return ret;
  714. }
  715.  
  716. static _UNIT_TEST() {
  717. let m = new Mutex();
  718. function sleep(time) {
  719. return new Promise(r => setTimeout(r, time));
  720. }
  721. m.lockAndAwait(() => {
  722. console.warn('Check message timestamps.');
  723. console.warn('Bad:');
  724. console.warn('1 1 1 1 1:5s');
  725. console.warn(' 1 1 1 1 1:10s');
  726. console.warn('Good:');
  727. console.warn('1 1 1 1 1:5s');
  728. console.warn(' 1 1 1 1 1:10s');
  729. });
  730. m.lockAndAwait(async () => {
  731. await sleep(1000);
  732. await sleep(1000);
  733. await sleep(1000);
  734. await sleep(1000);
  735. await sleep(1000);
  736. });
  737. m.lockAndAwait(async () => console.log('5s!'));
  738. m.lockAndAwait(async () => {
  739. await sleep(1000);
  740. await sleep(1000);
  741. await sleep(1000);
  742. await sleep(1000);
  743. await sleep(1000);
  744. });
  745. m.lockAndAwait(async () => console.log('10s!'));
  746. }
  747. }
  748.  
  749. /**
  750. * @typedef DanmakuColor
  751. * @property {number} r
  752. * @property {number} g
  753. * @property {number} b
  754. */
  755. /**
  756. * @typedef Danmaku
  757. * @property {string} text
  758. * @property {number} time
  759. * @property {string} mode
  760. * @property {number} size
  761. * @property {DanmakuColor} color
  762. * @property {boolean} bottom
  763. * @property {string=} sender
  764. */
  765.  
  766. const parser = {};
  767.  
  768. /**
  769. * @param {Danmaku} danmaku
  770. * @returns {boolean}
  771. */
  772. const danmakuFilter = danmaku => {
  773. if (!danmaku) return false;
  774. if (!danmaku.text) return false;
  775. if (!danmaku.mode) return false;
  776. if (!danmaku.size) return false;
  777. if (danmaku.time < 0 || danmaku.time >= 360000) return false;
  778. return true;
  779. };
  780.  
  781. const parseRgb256IntegerColor = color => {
  782. const rgb = parseInt(color, 10);
  783. const r = (rgb >>> 4) & 0xff;
  784. const g = (rgb >>> 2) & 0xff;
  785. const b = (rgb >>> 0) & 0xff;
  786. return { r, g, b };
  787. };
  788.  
  789. const parseNiconicoColor = mail => {
  790. const colorTable = {
  791. red: { r: 255, g: 0, b: 0 },
  792. pink: { r: 255, g: 128, b: 128 },
  793. orange: { r: 255, g: 184, b: 0 },
  794. yellow: { r: 255, g: 255, b: 0 },
  795. green: { r: 0, g: 255, b: 0 },
  796. cyan: { r: 0, g: 255, b: 255 },
  797. blue: { r: 0, g: 0, b: 255 },
  798. purple: { r: 184, g: 0, b: 255 },
  799. black: { r: 0, g: 0, b: 0 },
  800. };
  801. const defaultColor = { r: 255, g: 255, b: 255 };
  802. const line = mail.toLowerCase().split(/\s+/);
  803. const color = Object.keys(colorTable).find(color => line.includes(color));
  804. return color ? colorTable[color] : defaultColor;
  805. };
  806.  
  807. const parseNiconicoMode = mail => {
  808. const line = mail.toLowerCase().split(/\s+/);
  809. if (line.includes('ue')) return 'TOP';
  810. if (line.includes('shita')) return 'BOTTOM';
  811. return 'RTL';
  812. };
  813.  
  814. const parseNiconicoSize = mail => {
  815. const line = mail.toLowerCase().split(/\s+/);
  816. if (line.includes('big')) return 36;
  817. if (line.includes('small')) return 16;
  818. return 25;
  819. };
  820.  
  821. /**
  822. * @param {string|ArrayBuffer} content
  823. * @return {{ cid: number, danmaku: Array<Danmaku> }}
  824. */
  825. parser.bilibili = function (content) {
  826. const text = typeof content === 'string' ? content : new TextDecoder('utf-8').decode(content);
  827. const clean = text.replace(/(?:[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g, '').replace(/.*?\?>/,"");
  828. const data = (new DOMParser()).parseFromString(clean, 'text/xml');
  829. const cid = +data.querySelector('chatid,oid').textContent;
  830. /** @type {Array<Danmaku>} */
  831. const danmaku = Array.from(data.querySelectorAll('d')).map(d => {
  832. const p = d.getAttribute('p');
  833. const [time, mode, size, color, create, bottom, sender, id] = p.split(',');
  834. return {
  835. text: d.textContent,
  836. time: +time,
  837. // We do not support ltr mode
  838. mode: [null, 'RTL', 'RTL', 'RTL', 'BOTTOM', 'TOP'][+mode],
  839. size: +size,
  840. color: parseRgb256IntegerColor(color),
  841. bottom: bottom > 0,
  842. sender,
  843. };
  844. }).filter(danmakuFilter);
  845. return { cid, danmaku };
  846. };
  847.  
  848. /**
  849. * @param {string|ArrayBuffer} content
  850. * @return {{ cid: number, danmaku: Array<Danmaku> }}
  851. */
  852. parser.acfun = function (content) {
  853. const text = typeof content === 'string' ? content : new TextDecoder('utf-8').decode(content);
  854. const data = JSON.parse(text);
  855. const list = data.reduce((x, y) => x.concat(y), []);
  856. const danmaku = list.map(line => {
  857. const [time, color, mode, size, sender, create, uuid] = line.c.split(','), text = line.m;
  858. return {
  859. text,
  860. time: +time,
  861. color: parseRgb256IntegerColor(+color),
  862. mode: [null, 'RTL', null, null, 'BOTTOM', 'TOP'][mode],
  863. size: +size,
  864. bottom: false,
  865. uuid,
  866. };
  867. }).filter(danmakuFilter);
  868. return { danmaku };
  869. };
  870.  
  871. /**
  872. * @param {string|ArrayBuffer} content
  873. * @return {{ cid: number, danmaku: Array<Danmaku> }}
  874. */
  875. parser.niconico = function (content) {
  876. const text = typeof content === 'string' ? content : new TextDecoder('utf-8').decode(content);
  877. const data = JSON.parse(text);
  878. const list = data.map(item => item.chat).filter(x => x);
  879. const { thread } = list.find(comment => comment.thread);
  880. const danmaku = list.map(comment => {
  881. if (!comment.content || !(comment.vpos >= 0) || !comment.no) return null;
  882. const { vpos, mail = '', content, no } = comment;
  883. return {
  884. text: content,
  885. time: vpos / 100,
  886. color: parseNiconicoColor(mail),
  887. mode: parseNiconicoMode(mail),
  888. size: parseNiconicoSize(mail),
  889. bottom: false,
  890. id: no,
  891. };
  892. }).filter(danmakuFilter);
  893. return { thread, danmaku };
  894. };
  895.  
  896. const font = {};
  897.  
  898. // Meansure using canvas
  899. font.textByCanvas = function () {
  900. const canvas = document.createElement('canvas');
  901. const context = canvas.getContext('2d');
  902. return function (fontname, text, fontsize) {
  903. context.font = `bold ${fontsize}px ${fontname}`;
  904. return Math.ceil(context.measureText(text).width);
  905. };
  906. };
  907.  
  908. // Meansure using <div>
  909. font.textByDom = function () {
  910. const container = document.createElement('div');
  911. container.setAttribute('style', 'all: initial !important');
  912. const content = document.createElement('div');
  913. content.setAttribute('style', [
  914. 'top: -10000px', 'left: -10000px',
  915. 'width: auto', 'height: auto', 'position: absolute',
  916. ].map(item => item + ' !important;').join(' '));
  917. const active = () => { document.body.parentNode.appendChild(content); };
  918. if (!document.body) document.addEventListener('DOMContentLoaded', active);
  919. else active();
  920. return (fontname, text, fontsize) => {
  921. content.textContent = text;
  922. content.style.font = `bold ${fontsize}px ${fontname}`;
  923. return content.clientWidth;
  924. };
  925. };
  926.  
  927. font.text = (function () {
  928. // https://bugzilla.mozilla.org/show_bug.cgi?id=561361
  929. if (/linux/i.test(navigator.platform)) {
  930. return font.textByDom();
  931. } else {
  932. return font.textByCanvas();
  933. }
  934. }());
  935.  
  936. font.valid = (function () {
  937. const cache = new Map();
  938. const textWidth = font.text;
  939. // Use following texts for checking
  940. const sampleText = [
  941. 'The quick brown fox jumps over the lazy dog',
  942. '7531902468', ',.!-', ',。:!',
  943. '天地玄黄', '則近道矣',
  944. 'あいうえお', 'アイウエオガパ', 'アイウエオガパ',
  945. ].join('');
  946. // Some given font family is avaliable iff we can meansure different width compared to other fonts
  947. const sampleFont = [
  948. 'monospace', 'sans-serif', 'sans',
  949. 'Symbol', 'Arial', 'Comic Sans MS', 'Fixed', 'Terminal',
  950. 'Times', 'Times New Roman',
  951. 'SimSum', 'Microsoft YaHei', 'PingFang SC', 'Heiti SC', 'WenQuanYi Micro Hei',
  952. 'Pmingliu', 'Microsoft JhengHei', 'PingFang TC', 'Heiti TC',
  953. 'MS Gothic', 'Meiryo', 'Hiragino Kaku Gothic Pro', 'Hiragino Mincho Pro',
  954. ];
  955. const diffFont = function (base, test) {
  956. const baseSize = textWidth(base, sampleText, 72);
  957. const testSize = textWidth(test + ',' + base, sampleText, 72);
  958. return baseSize !== testSize;
  959. };
  960. const validFont = function (test) {
  961. if (cache.has(test)) return cache.get(test);
  962. const result = sampleFont.some(base => diffFont(base, test));
  963. cache.set(test, result);
  964. return result;
  965. };
  966. return validFont;
  967. }());
  968.  
  969. const rtlCanvas = function (options) {
  970. const {
  971. resolutionX: wc, // width of canvas
  972. resolutionY: hc, // height of canvas
  973. bottomReserved: b, // reserved bottom height for subtitle
  974. rtlDuration: u, // duration appeared on screen
  975. maxDelay: maxr, // max allowed delay
  976. } = options;
  977.  
  978. // Initial canvas border
  979. let used = [
  980. // p: top
  981. // m: bottom
  982. // tf: time completely enter screen
  983. // td: time completely leave screen
  984. // b: allow conflict with subtitle
  985. // add a fake danmaku for describe top of screen
  986. { p: -Infinity, m: 0, tf: Infinity, td: Infinity, b: false },
  987. // add a fake danmaku for describe bottom of screen
  988. { p: hc, m: Infinity, tf: Infinity, td: Infinity, b: false },
  989. // add a fake danmaku for placeholder of subtitle
  990. { p: hc - b, m: hc, tf: Infinity, td: Infinity, b: true },
  991. ];
  992. // Find out some position is available
  993. const available = (hv, t0s, t0l, b) => {
  994. const suggestion = [];
  995. // Upper edge of candidate position should always be bottom of other danmaku (or top of screen)
  996. used.forEach(i => {
  997. if (i.m + hv >= hc) return;
  998. const p = i.m;
  999. const m = p + hv;
  1000. let tas = t0s;
  1001. let tal = t0l;
  1002. // and left border should be right edge of others
  1003. used.forEach(j => {
  1004. if (j.p >= m) return;
  1005. if (j.m <= p) return;
  1006. if (j.b && b) return;
  1007. tas = Math.max(tas, j.tf);
  1008. tal = Math.max(tal, j.td);
  1009. });
  1010. const r = Math.max(tas - t0s, tal - t0l);
  1011. if (r > maxr) return;
  1012. // save a candidate position
  1013. suggestion.push({ p, r });
  1014. });
  1015. // sorted by its vertical position
  1016. suggestion.sort((x, y) => x.p - y.p);
  1017. let mr = maxr;
  1018. // the bottom and later choice should be ignored
  1019. const filtered = suggestion.filter(i => {
  1020. if (i.r >= mr) return false;
  1021. mr = i.r;
  1022. return true;
  1023. });
  1024. return filtered;
  1025. };
  1026. // mark some area as used
  1027. let use = (p, m, tf, td) => {
  1028. used.push({ p, m, tf, td, b: false });
  1029. };
  1030. // remove danmaku not needed anymore by its time
  1031. const syn = (t0s, t0l) => {
  1032. used = used.filter(i => i.tf > t0s || i.td > t0l);
  1033. };
  1034. // give a score in range [0, 1) for some position
  1035. const score = i => {
  1036. if (i.r > maxr) return -Infinity;
  1037. return 1 - Math.hypot(i.r / maxr, i.p / hc) * Math.SQRT1_2;
  1038. };
  1039. // add some danmaku
  1040. return line => {
  1041. const {
  1042. time: t0s, // time sent (start to appear if no delay)
  1043. width: wv, // width of danmaku
  1044. height: hv, // height of danmaku
  1045. bottom: b, // is subtitle
  1046. } = line;
  1047. const t0l = wc / (wv + wc) * u + t0s; // time start to leave
  1048. syn(t0s, t0l);
  1049. const al = available(hv, t0s, t0l, b);
  1050. if (!al.length) return null;
  1051. const scored = al.map(i => [score(i), i]);
  1052. const best = scored.reduce((x, y) => {
  1053. return x[0] > y[0] ? x : y;
  1054. })[1];
  1055. const ts = t0s + best.r; // time start to enter
  1056. const tf = wv / (wv + wc) * u + ts; // time complete enter
  1057. const td = u + ts; // time complete leave
  1058. use(best.p, best.p + hv, tf, td);
  1059. return {
  1060. top: best.p,
  1061. time: ts,
  1062. };
  1063. };
  1064. };
  1065.  
  1066. const fixedCanvas = function (options) {
  1067. const {
  1068. resolutionY: hc,
  1069. bottomReserved: b,
  1070. fixDuration: u,
  1071. maxDelay: maxr,
  1072. } = options;
  1073. let used = [
  1074. { p: -Infinity, m: 0, td: Infinity, b: false },
  1075. { p: hc, m: Infinity, td: Infinity, b: false },
  1076. { p: hc - b, m: hc, td: Infinity, b: true },
  1077. ];
  1078. // Find out some available position
  1079. const fr = (p, m, t0s, b) => {
  1080. let tas = t0s;
  1081. used.forEach(j => {
  1082. if (j.p >= m) return;
  1083. if (j.m <= p) return;
  1084. if (j.b && b) return;
  1085. tas = Math.max(tas, j.td);
  1086. });
  1087. const r = tas - t0s;
  1088. if (r > maxr) return null;
  1089. return { r, p, m };
  1090. };
  1091. // layout for danmaku at top
  1092. const top = (hv, t0s, b) => {
  1093. const suggestion = [];
  1094. used.forEach(i => {
  1095. if (i.m + hv >= hc) return;
  1096. suggestion.push(fr(i.m, i.m + hv, t0s, b));
  1097. });
  1098. return suggestion.filter(x => x);
  1099. };
  1100. // layout for danmaku at bottom
  1101. const bottom = (hv, t0s, b) => {
  1102. const suggestion = [];
  1103. used.forEach(i => {
  1104. if (i.p - hv <= 0) return;
  1105. suggestion.push(fr(i.p - hv, i.p, t0s, b));
  1106. });
  1107. return suggestion.filter(x => x);
  1108. };
  1109. const use = (p, m, td) => {
  1110. used.push({ p, m, td, b: false });
  1111. };
  1112. const syn = t0s => {
  1113. used = used.filter(i => i.td > t0s);
  1114. };
  1115. // Score every position
  1116. const score = (i, is_top) => {
  1117. if (i.r > maxr) return -Infinity;
  1118. const f = p => is_top ? p : (hc - p);
  1119. return 1 - (i.r / maxr * (31 / 32) + f(i.p) / hc * (1 / 32));
  1120. };
  1121. return function (line) {
  1122. const { time: t0s, height: hv, bottom: b } = line;
  1123. const is_top = line.mode === 'TOP';
  1124. syn(t0s);
  1125. const al = (is_top ? top : bottom)(hv, t0s, b);
  1126. if (!al.length) return null;
  1127. const scored = al.map(function (i) { return [score(i, is_top), i]; });
  1128. const best = scored.reduce(function (x, y) {
  1129. return x[0] > y[0] ? x : y;
  1130. }, [-Infinity, null])[1];
  1131. if (!best) return null;
  1132. use(best.p, best.m, best.r + t0s + u);
  1133. return { top: best.p, time: best.r + t0s };
  1134. };
  1135. };
  1136.  
  1137. const placeDanmaku = function (options) {
  1138. const layers = options.maxOverlap;
  1139. const normal = Array(layers).fill(null).map(x => rtlCanvas(options));
  1140. const fixed = Array(layers).fill(null).map(x => fixedCanvas(options));
  1141. return function (line) {
  1142. line.fontSize = Math.round(line.size * options.fontSize);
  1143. line.height = line.fontSize;
  1144. line.width = line.width || font.text(options.fontFamily, line.text, line.fontSize) || 1;
  1145.  
  1146. if (line.mode === 'RTL') {
  1147. const pos = normal.reduce((pos, layer) => pos || layer(line), null);
  1148. if (!pos) return null;
  1149. const { top, time } = pos;
  1150. line.layout = {
  1151. type: 'Rtl',
  1152. start: {
  1153. x: options.resolutionX + line.width / 2,
  1154. y: top + line.height,
  1155. time,
  1156. },
  1157. end: {
  1158. x: -line.width / 2,
  1159. y: top + line.height,
  1160. time: options.rtlDuration + time,
  1161. },
  1162. };
  1163. } else if (['TOP', 'BOTTOM'].includes(line.mode)) {
  1164. const pos = fixed.reduce((pos, layer) => pos || layer(line), null);
  1165. if (!pos) return null;
  1166. const { top, time } = pos;
  1167. line.layout = {
  1168. type: 'Fix',
  1169. start: {
  1170. x: Math.round(options.resolutionX / 2),
  1171. y: top + line.height,
  1172. time,
  1173. },
  1174. end: {
  1175. time: options.fixDuration + time,
  1176. },
  1177. };
  1178. }
  1179. return line;
  1180. };
  1181. };
  1182.  
  1183. // main layout algorithm
  1184. const layout = async function (danmaku, optionGetter) {
  1185. const options = JSON.parse(JSON.stringify(optionGetter));
  1186. const sorted = danmaku.slice(0).sort(({ time: x }, { time: y }) => x - y);
  1187. const place = placeDanmaku(options);
  1188. const result = Array(sorted.length);
  1189. let length = 0;
  1190. for (let i = 0, l = sorted.length; i < l; i++) {
  1191. let placed = place(sorted[i]);
  1192. if (placed) result[length++] = placed;
  1193. if ((i + 1) % 1000 === 0) {
  1194. await new Promise(resolve => setTimeout(resolve, 0));
  1195. }
  1196. }
  1197. result.length = length;
  1198. result.sort((x, y) => x.layout.start.time - y.layout.start.time);
  1199. return result;
  1200. };
  1201.  
  1202. // escape string for ass
  1203. const textEscape = s => (
  1204. // VSFilter do not support escaped "{" or "}"; we use full-width version instead
  1205. s.replace(/{/g, '{').replace(/}/g, '}').replace(/\s/g, ' ')
  1206. );
  1207.  
  1208. const formatColorChannel = v => (v & 255).toString(16).toUpperCase().padStart(2, '0');
  1209.  
  1210. // format color
  1211. const formatColor = color => '&H' + (
  1212. [color.b, color.g, color.r].map(formatColorChannel).join('')
  1213. );
  1214.  
  1215. // format timestamp
  1216. const formatTimestamp = time => {
  1217. const value = Math.round(time * 100) * 10;
  1218. const rem = value % 3600000;
  1219. const hour = (value - rem) / 3600000;
  1220. const fHour = hour.toFixed(0).padStart(2, '0');
  1221. const fRem = new Date(rem).toISOString().slice(-11, -2);
  1222. return fHour + fRem;
  1223. };
  1224.  
  1225. // test is default color
  1226. const isDefaultColor = ({ r, g, b }) => r === 255 && g === 255 && b === 255;
  1227. // test is dark color
  1228. const isDarkColor = ({ r, g, b }) => r * 0.299 + g * 0.587 + b * 0.114 < 0x30;
  1229.  
  1230. // Ass header
  1231. const header = info => [
  1232. '[Script Info]',
  1233. `Title: ${info.title}`,
  1234. `Original Script: ${info.original}`,
  1235. 'ScriptType: v4.00+',
  1236. 'Collisions: Normal',
  1237. `PlayResX: ${info.playResX}`,
  1238. `PlayResY: ${info.playResY}`,
  1239. 'Timer: 100.0000',
  1240. '',
  1241. '[V4+ Styles]',
  1242. 'Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding',
  1243. `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`,
  1244. `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`,
  1245. '',
  1246. '[Events]',
  1247. 'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
  1248. ];
  1249.  
  1250. // Set color of text
  1251. const lineColor = ({ color }) => {
  1252. let output = [];
  1253. if (!isDefaultColor(color)) output.push(`\\c${formatColor(color)}`);
  1254. if (isDarkColor(color)) output.push(`\\3c&HFFFFFF`);
  1255. return output.join('');
  1256. };
  1257.  
  1258. // Set fontsize
  1259. let defaultFontSize;
  1260. const lineFontSize = ({ size }) => {
  1261. if (size === defaultFontSize) return '';
  1262. return `\\fs${size}`;
  1263. };
  1264. const getCommonFontSize = list => {
  1265. const count = new Map();
  1266. let commonCount = 0, common = 1;
  1267. list.forEach(({ size }) => {
  1268. let value = 1;
  1269. if (count.has(size)) value = count.get(size) + 1;
  1270. count.set(size, value);
  1271. if (value > commonCount) {
  1272. commonCount = value;
  1273. common = size;
  1274. }
  1275. });
  1276. defaultFontSize = common;
  1277. return common;
  1278. };
  1279.  
  1280. // Add animation of danmaku
  1281. const lineMove = ({ layout: { type, start = null, end = null } }) => {
  1282. if (type === 'Rtl' && start && end) return `\\move(${start.x},${start.y},${end.x},${end.y})`;
  1283. if (type === 'Fix' && start) return `\\pos(${start.x},${start.y})`;
  1284. return '';
  1285. };
  1286.  
  1287. // format one line
  1288. const formatLine = line => {
  1289. const start = formatTimestamp(line.layout.start.time);
  1290. const end = formatTimestamp(line.layout.end.time);
  1291. const type = line.layout.type;
  1292. const color = lineColor(line);
  1293. const fontSize = lineFontSize(line);
  1294. const move = lineMove(line);
  1295. const format = `${color}${fontSize}${move}`;
  1296. const text = textEscape(line.text);
  1297. return `Dialogue: 0,${start},${end},${type},,20,20,2,,{${format}}${text}`;
  1298. };
  1299.  
  1300. const ass = (danmaku, options) => {
  1301. const info = {
  1302. title: danmaku.meta.name,
  1303. original: `Generated by tiansh/ass-danmaku (embedded in liqi0816/bilitwin) based on ${danmaku.meta.url}`,
  1304. playResX: options.resolutionX,
  1305. playResY: options.resolutionY,
  1306. fontFamily: options.fontFamily.split(",")[0],
  1307. fontSize: getCommonFontSize(danmaku.layout),
  1308. alpha: formatColorChannel(0xFF * (100 - options.textOpacity * 100) / 100),
  1309. bold: options.bold? -1 : 0,
  1310. };
  1311. return [
  1312. ...header(info),
  1313. ...danmaku.layout.map(formatLine).filter(x => x),
  1314. ].join('\r\n');
  1315. };
  1316.  
  1317. /**
  1318. * @file Common works for reading / writing optinos
  1319. */
  1320.  
  1321. /**
  1322. * @returns {string}
  1323. */
  1324. const predefFontFamily = () => {
  1325. // const sc = ['Microsoft YaHei', 'PingFang SC', 'Noto Sans CJK SC'];
  1326. // replaced with bilibili defaults
  1327. 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'"];
  1328. const tc = ['Microsoft JhengHei', 'PingFang TC', 'Noto Sans CJK TC'];
  1329. const ja = ['MS PGothic', 'Hiragino Kaku Gothic Pro', 'Noto Sans CJK JP'];
  1330. const lang = navigator.language;
  1331. const fonts = /^ja/.test(lang) ? ja : /^zh(?!.*Hans).*(?:TW|HK|MO)/.test(lang) ? tc : sc;
  1332. const chosed = fonts.find(font$$1 => font.valid(font$$1)) || fonts[0];
  1333. return chosed;
  1334. };
  1335.  
  1336. const attributes = [
  1337. { name: 'resolutionX', type: 'number', min: 480, predef: 560 },
  1338. { name: 'resolutionY', type: 'number', min: 360, predef: 420 },
  1339. { name: 'bottomReserved', type: 'number', min: 0, predef: 60 },
  1340. { name: 'fontFamily', type: 'string', predef: predefFontFamily(), valid: font$$1 => font.valid(font$$1) },
  1341. { name: 'fontSize', type: 'number', min: 0, predef: 1, step: 0.01 },
  1342. { name: 'textSpace', type: 'number', min: 0, predef: 0 },
  1343. { name: 'rtlDuration', type: 'number', min: 0.1, predef: 8, step: 0.1 },
  1344. { name: 'fixDuration', type: 'number', min: 0.1, predef: 4, step: 0.1 },
  1345. { name: 'maxDelay', type: 'number', min: 0, predef: 6, step: 0.1 },
  1346. { name: 'textOpacity', type: 'number', min: 0.1, max: 1, predef: 0.6 },
  1347. { name: 'maxOverlap', type: 'number', min: 1, max: 20, predef: 1 },
  1348. { name: 'bold', type: 'boolean', predef: true },
  1349. ];
  1350.  
  1351. const attrNormalize = (option, { name, type, min = -Infinity, max = Infinity, step = 1, predef, valid }) => {
  1352. let value = option;
  1353. if (type === 'number') value = +value;
  1354. else if (type === 'string') value = '' + value;
  1355. else if (type === 'boolean') value = !!value;
  1356. if (valid && !valid(value)) value = predef;
  1357. if (type === 'number') {
  1358. if (Number.isNaN(value)) value = predef;
  1359. if (value < min) value = min;
  1360. if (value > max) value = max;
  1361. if (name !='textOpacity') value = Math.round((value - min) / step) * step + min;
  1362. }
  1363. return value;
  1364. };
  1365.  
  1366. /**
  1367. * @param {ExtOption} option
  1368. * @returns {ExtOption}
  1369. */
  1370. const normalize = function (option) {
  1371. return Object.assign({},
  1372. ...attributes.map(attr => ({ [attr.name]: attrNormalize(option[attr.name], attr) }))
  1373. );
  1374. };
  1375.  
  1376. /**
  1377. * Convert file content to Blob which describe the file
  1378. * @param {string} content
  1379. * @returns {Blob}
  1380. */
  1381. const convertToBlob = content => {
  1382. const encoder = new TextEncoder();
  1383. // Add a BOM to make some ass parser library happier
  1384. const bom = '\ufeff';
  1385. const encoded = encoder.encode(bom + content);
  1386. const blob = new Blob([encoded], { type: 'application/octet-stream' });
  1387. return blob;
  1388. };
  1389.  
  1390. /***
  1391. * Copyright (C) 2018 Qli5. All Rights Reserved.
  1392. *
  1393. * @author qli5 <goodlq11[at](163|gmail).com>
  1394. *
  1395. * This Source Code Form is subject to the terms of the Mozilla Public
  1396. * License, v. 2.0. If a copy of the MPL was not distributed with this
  1397. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  1398. */
  1399.  
  1400. /**
  1401. * An API wrapper of tiansh/ass-danmaku for liqi0816/bilitwin
  1402. */
  1403. class ASSConverter {
  1404. /**
  1405. * @typedef {ExtOption}
  1406. * @property {number} resolutionX canvas width for drawing danmaku (px)
  1407. * @property {number} resolutionY canvas height for drawing danmaku (px)
  1408. * @property {number} bottomReserved reserved height at bottom for drawing danmaku (px)
  1409. * @property {string} fontFamily danmaku font family
  1410. * @property {number} fontSize danmaku font size (ratio)
  1411. * @property {number} textSpace space between danmaku (px)
  1412. * @property {number} rtlDuration duration of right to left moving danmaku appeared on screen (s)
  1413. * @property {number} fixDuration duration of keep bottom / top danmaku appeared on screen (s)
  1414. * @property {number} maxDelay // maxinum amount of allowed delay (s)
  1415. * @property {number} textOpacity // opacity of text, in range of [0, 1]
  1416. * @property {number} maxOverlap // maxinum layers of danmaku
  1417. */
  1418.  
  1419. /**
  1420. * @param {ExtOption} option tiansh/ass-danmaku compatible option
  1421. */
  1422. constructor(option = {}) {
  1423. this.option = option;
  1424. }
  1425.  
  1426. get option() {
  1427. return this.normalizedOption;
  1428. }
  1429.  
  1430. set option(e) {
  1431. return this.normalizedOption = normalize(e);
  1432. }
  1433.  
  1434. /**
  1435. * @param {Danmaku[]} danmaku use ASSConverter.parseXML
  1436. * @param {string} title
  1437. * @param {string} originalURL
  1438. */
  1439. async genASS(danmaku, title = 'danmaku', originalURL = 'anonymous xml') {
  1440. const layout$$1 = await layout(danmaku, this.option);
  1441. const ass$$1 = ass({
  1442. content: danmaku,
  1443. layout: layout$$1,
  1444. meta: {
  1445. name: title,
  1446. url: originalURL
  1447. }
  1448. }, this.option);
  1449. return ass$$1;
  1450. }
  1451.  
  1452. async genASSBlob(danmaku, title = 'danmaku', originalURL = 'anonymous xml') {
  1453. return convertToBlob(await this.genASS(danmaku, title, originalURL));
  1454. }
  1455.  
  1456. /**
  1457. * @typedef DanmakuColor
  1458. * @property {number} r
  1459. * @property {number} g
  1460. * @property {number} b
  1461. */
  1462.  
  1463. /**
  1464. * @typedef Danmaku
  1465. * @property {string} text
  1466. * @property {number} time
  1467. * @property {string} mode
  1468. * @property {number} size
  1469. * @property {DanmakuColor} color
  1470. * @property {boolean} bottom
  1471. * @property {string=} sender
  1472. */
  1473.  
  1474. /**
  1475. * @param {string} xml bilibili danmaku xml
  1476. * @returns {Danmaku[]}
  1477. */
  1478. static parseXML(xml) {
  1479. return parser.bilibili(xml).danmaku;
  1480. }
  1481.  
  1482.  
  1483. static _UNIT_TEST() {
  1484. const e = new ASSConverter();
  1485. 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>`;
  1486. console.log(window.ass = e.genASSBlob(ASSConverter.parseXML(xml)));
  1487. }
  1488. }
  1489.  
  1490. /***
  1491. * Copyright (C) 2018 Qli5. All Rights Reserved.
  1492. *
  1493. * @author qli5 <goodlq11[at](163|gmail).com>
  1494. *
  1495. * This Source Code Form is subject to the terms of the Mozilla Public
  1496. * License, v. 2.0. If a copy of the MPL was not distributed with this
  1497. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  1498. */
  1499.  
  1500. /**
  1501. * A util to hook a function
  1502. */
  1503. class HookedFunction extends Function {
  1504. constructor(...init) {
  1505. // 1. init parameter
  1506. const { raw, pre, post } = HookedFunction.parseParameter(...init);
  1507.  
  1508. // 2. build bundle
  1509. const self = function (...args) {
  1510. const { raw, pre, post } = self;
  1511. const context = { args, target: raw, ret: undefined, hook: self };
  1512. pre.forEach(e => e.call(this, context));
  1513. if (context.target) context.ret = context.target.apply(this, context.args);
  1514. post.forEach(e => e.call(this, context));
  1515. return context.ret;
  1516. };
  1517. Object.setPrototypeOf(self, HookedFunction.prototype);
  1518. self.raw = raw;
  1519. self.pre = pre;
  1520. self.post = post;
  1521.  
  1522. // 3. cheat babel - it complains about missing super(), even if it is actual valid
  1523. try {
  1524. return self;
  1525. } catch (e) {
  1526. super();
  1527. return self;
  1528. }
  1529. }
  1530.  
  1531. addPre(...func) {
  1532. this.pre.push(...func);
  1533. }
  1534.  
  1535. addPost(...func) {
  1536. this.post.push(...func);
  1537. }
  1538.  
  1539. addCallback(...func) {
  1540. this.addPost(...func);
  1541. }
  1542.  
  1543. removePre(func) {
  1544. this.pre = this.pre.filter(e => e != func);
  1545. }
  1546.  
  1547. removePost(func) {
  1548. this.post = this.post.filter(e => e != func);
  1549. }
  1550.  
  1551. removeCallback(func) {
  1552. this.removePost(func);
  1553. }
  1554.  
  1555. static parseParameter(...init) {
  1556. // 1. clone init
  1557. init = init.slice();
  1558.  
  1559. // 2. default
  1560. let raw = null;
  1561. let pre = [];
  1562. let post = [];
  1563.  
  1564. // 3. (raw, ...others)
  1565. if (typeof init[0] === 'function') raw = init.shift();
  1566.  
  1567. // 4. iterate through parameters
  1568. for (const e of init) {
  1569. if (!e) {
  1570. continue;
  1571. }
  1572. else if (Array.isArray(e)) {
  1573. pre = post;
  1574. post = e;
  1575. }
  1576. else if (typeof e == 'object') {
  1577. if (typeof e.raw == 'function') raw = e.raw;
  1578. if (typeof e.pre == 'function') pre.push(e.pre);
  1579. if (typeof e.post == 'function') post.push(e.post);
  1580. if (Array.isArray(e.pre)) pre = e.pre;
  1581. if (Array.isArray(e.post)) post = e.post;
  1582. }
  1583. else if (typeof e == 'function') {
  1584. post.push(e);
  1585. }
  1586. else {
  1587. throw new TypeError(`HookedFunction: cannot recognize paramter ${e} of type ${typeof e}`);
  1588. }
  1589. }
  1590. return { raw, pre, post };
  1591. }
  1592.  
  1593. static hook(...init) {
  1594. // 1. init parameter
  1595. const { raw, pre, post } = HookedFunction.parseParameter(...init);
  1596.  
  1597. // 2 wrap
  1598. // 2.1 already wrapped => concat
  1599. if (raw instanceof HookedFunction) {
  1600. raw.pre.push(...pre);
  1601. raw.post.push(...post);
  1602. return raw;
  1603. }
  1604.  
  1605. // 2.2 otherwise => new
  1606. else {
  1607. return new HookedFunction({ raw, pre, post });
  1608. }
  1609. }
  1610.  
  1611. static hookDebugger(raw, pre = true, post = false) {
  1612. // 1. init hook
  1613. if (!HookedFunction.hookDebugger.hook) HookedFunction.hookDebugger.hook = function (ctx) { debugger };
  1614.  
  1615. // 2 wrap
  1616. // 2.1 already wrapped => concat
  1617. if (raw instanceof HookedFunction) {
  1618. if (pre && !raw.pre.includes(HookedFunction.hookDebugger.hook)) {
  1619. raw.pre.push(HookedFunction.hookDebugger.hook);
  1620. }
  1621. if (post && !raw.post.includes(HookedFunction.hookDebugger.hook)) {
  1622. raw.post.push(HookedFunction.hookDebugger.hook);
  1623. }
  1624. return raw;
  1625. }
  1626.  
  1627. // 2.2 otherwise => new
  1628. else {
  1629. return new HookedFunction({
  1630. raw,
  1631. pre: pre && HookedFunction.hookDebugger.hook || undefined,
  1632. post: post && HookedFunction.hookDebugger.hook || undefined,
  1633. });
  1634. }
  1635. }
  1636. }
  1637.  
  1638. /***
  1639. * BiliMonkey
  1640. * A bilibili user script
  1641. * Copyright (C) 2018 Qli5. All Rights Reserved.
  1642. *
  1643. * @author qli5 <goodlq11[at](163|gmail).com>
  1644. *
  1645. * This Source Code Form is subject to the terms of the Mozilla Public
  1646. * License, v. 2.0. If a copy of the MPL was not distributed with this
  1647. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  1648. *
  1649. * The FLV merge utility is a Javascript translation of
  1650. * https://github.com/grepmusic/flvmerge
  1651. * by grepmusic
  1652. *
  1653. * The ASS convert utility is a fork of
  1654. * https://github.com/tiansh/ass-danmaku
  1655. * by tiansh
  1656. *
  1657. * The FLV demuxer is from
  1658. * https://github.com/Bilibili/flv.js/
  1659. * by zheng qian
  1660. *
  1661. * The EMBL builder is from
  1662. * <https://www.npmjs.com/package/simple-ebml-builder>
  1663. * by ryiwamoto
  1664. */
  1665.  
  1666. class BiliMonkey {
  1667. constructor(playerWin, option = BiliMonkey.optionDefaults) {
  1668. this.playerWin = playerWin;
  1669. this.protocol = playerWin.location.protocol;
  1670. this.cid = null;
  1671. this.flvs = null;
  1672. this.mp4 = null;
  1673. this.ass = null;
  1674. this.flvFormatName = null;
  1675. this.mp4FormatName = null;
  1676. this.fallbackFormatName = null;
  1677. this.cidAsyncContainer = new AsyncContainer();
  1678. this.cidAsyncContainer.then(cid => { this.cid = cid; /** this.ass = this.getASS(); */ });
  1679. if (typeof top.cid === 'string') this.cidAsyncContainer.resolve(top.cid);
  1680.  
  1681. /***
  1682. * cache + proxy = Service Worker
  1683. * Hope bilibili will have a SW as soon as possible.
  1684. * partial = Stream
  1685. * Hope the fetch API will be stabilized as soon as possible.
  1686. * If you are using your grandpa's browser, do not enable these functions.
  1687. */
  1688. this.cache = option.cache;
  1689. this.partial = option.partial;
  1690. this.proxy = option.proxy;
  1691. this.blocker = option.blocker;
  1692. this.font = option.font;
  1693. this.option = option;
  1694. if (this.cache && (!(this.cache instanceof CacheDB))) this.cache = new CacheDB('biliMonkey', 'flv', 'name');
  1695.  
  1696. this.flvsDetailedFetch = [];
  1697. this.flvsBlob = [];
  1698.  
  1699. this.defaultFormatPromise = null;
  1700. this.queryInfoMutex = new Mutex();
  1701.  
  1702. this.destroy = new HookedFunction();
  1703. }
  1704.  
  1705. /***
  1706. * Guide: for ease of debug, please use format name(flv720) instead of format value(64) unless necessary
  1707. * Guide: for ease of html concat, please use string format value('64') instead of number(parseInt('64'))
  1708. */
  1709. lockFormat(format) {
  1710. // null => uninitialized
  1711. // async pending => another one is working on it
  1712. // async resolve => that guy just finished work
  1713. // sync value => someone already finished work
  1714. const toast = this.playerWin.document.getElementsByClassName('bilibili-player-video-toast-top')[0];
  1715. if (toast) toast.style.visibility = 'hidden';
  1716. if (format == this.fallbackFormatName) return null;
  1717. switch (format) {
  1718. // Single writer is not a must.
  1719. // Plus, if one writer fail, others should be able to overwrite its garbage.
  1720. case 'flv_p60':
  1721. case 'flv720_p60':
  1722. case 'hdflv2':
  1723. case 'flv':
  1724. case 'flv720':
  1725. case 'flv480':
  1726. case 'flv360':
  1727. //if (this.flvs) return this.flvs;
  1728. return this.flvs = new AsyncContainer();
  1729. case 'hdmp4':
  1730. case 'mp4':
  1731. //if (this.mp4) return this.mp4;
  1732. return this.mp4 = new AsyncContainer();
  1733. default:
  1734. throw `lockFormat error: ${format} is a unrecognizable format`;
  1735. }
  1736. }
  1737.  
  1738. resolveFormat(res, shouldBe) {
  1739. const toast = this.playerWin.document.getElementsByClassName('bilibili-player-video-toast-top')[0];
  1740. if (toast) {
  1741. toast.style.visibility = '';
  1742. if (toast.children.length) toast.children[0].style.visibility = 'hidden';
  1743. const video = this.playerWin.document.getElementsByTagName('video')[0];
  1744. if (video) {
  1745. const h = () => {
  1746. if (toast.children.length) toast.children[0].style.visibility = 'hidden';
  1747. };
  1748. video.addEventListener('emptied', h, { once: true });
  1749. setTimeout(() => video.removeEventListener('emptied', h), 500);
  1750. }
  1751.  
  1752. }
  1753. if (res.format == this.fallbackFormatName) return null;
  1754. switch (res.format) {
  1755. case 'flv_p60':
  1756. case 'flv720_p60':
  1757. case 'hdflv2':
  1758. case 'flv':
  1759. case 'flv720':
  1760. case 'flv480':
  1761. case 'flv360':
  1762. if (shouldBe && shouldBe != res.format) {
  1763. this.flvs = null;
  1764. throw `URL interface error: response is not ${shouldBe}`;
  1765. }
  1766. return this.flvs = this.flvs.resolve(res.durl.map(e => e.url.replace('http:', this.protocol)));
  1767. case 'hdmp4':
  1768. case 'mp4':
  1769. if (shouldBe && shouldBe != res.format) {
  1770. this.mp4 = null;
  1771. throw `URL interface error: response is not ${shouldBe}`;
  1772. }
  1773. return this.mp4 = this.mp4.resolve(res.durl[0].url.replace('http:', this.protocol));
  1774. default:
  1775. throw `resolveFormat error: ${res.format} is a unrecognizable format`;
  1776. }
  1777. }
  1778.  
  1779. getVIPStatus() {
  1780. const data = this.playerWin.sessionStorage.getItem('bili_login_status');
  1781. try {
  1782. return JSON.parse(data).some(e => e instanceof Object && e.vipStatus);
  1783. }
  1784. catch (e) {
  1785. return false;
  1786. }
  1787. }
  1788.  
  1789. async getASS() {
  1790. if (this.ass) return this.ass;
  1791. this.ass = await new Promise(async resolve => {
  1792. // 1. cid
  1793. if (!this.cid) this.cid = this.playerWin.cid;
  1794.  
  1795. // 2. options
  1796. const bilibili_player_settings = this.playerWin.localStorage.bilibili_player_settings && JSON.parse(this.playerWin.localStorage.bilibili_player_settings);
  1797.  
  1798. // 2.1 blocker
  1799. let danmaku = await BiliMonkey.fetchDanmaku(this.cid);
  1800. if (bilibili_player_settings && this.blocker) {
  1801. const i = bilibili_player_settings.block.list.map(e => e.v).join('|');
  1802. if (i) {
  1803. const regexp = new RegExp(i);
  1804. danmaku = danmaku.filter(e => !regexp.test(e.text) && !regexp.test(e.sender));
  1805. }
  1806. }
  1807.  
  1808. // 2.2 font
  1809. const option = bilibili_player_settings && this.font && {
  1810. 'fontFamily': bilibili_player_settings.setting_config['fontfamily'] != 'custom' ? bilibili_player_settings.setting_config['fontfamily'].split(/, ?/) : bilibili_player_settings.setting_config['fontfamilycustom'].split(/, ?/),
  1811. 'fontSize': parseFloat(bilibili_player_settings.setting_config['fontsize']),
  1812. 'textOpacity': parseFloat(bilibili_player_settings.setting_config['opacity']),
  1813. 'bold': bilibili_player_settings.setting_config['bold'] ? 1 : 0,
  1814. } || undefined;
  1815.  
  1816. // 2.3 resolution
  1817. if (this.option.resolution) {
  1818. Object.assign(option, {
  1819. 'resolutionX': +this.option.resolutionX || 560,
  1820. 'resolutionY': +this.option.resolutionY || 420
  1821. });
  1822. }
  1823.  
  1824. // 3. generate
  1825. const data = await new ASSConverter(option).genASSBlob(
  1826. danmaku, top.document.title, top.location.href
  1827. );
  1828. resolve(top.URL.createObjectURL(data));
  1829. });
  1830. return this.ass;
  1831. }
  1832.  
  1833. async queryInfo(format) {
  1834. return this.queryInfoMutex.lockAndAwait(async () => {
  1835. switch (format) {
  1836. case 'video':
  1837. if (this.flvs)
  1838. return this.video_format;
  1839.  
  1840. const isBangumi = location.pathname.includes("bangumi") || location.hostname.includes("bangumi");
  1841. const apiPath = isBangumi ? "/pgc/player/web/playurl" : "/x/player/playurl";
  1842.  
  1843. const qn = (this.option.enableVideoMaxResolution && this.option.videoMaxResolution) || "120";
  1844. const api_url = `https://api.bilibili.com${apiPath}?avid=${aid}&cid=${cid}&otype=json&qn=${qn}`;
  1845.  
  1846. const re = await fetch(api_url, { credentials: 'include' });
  1847. const apiJson = await re.json();
  1848.  
  1849. let data = apiJson.data || apiJson.result;
  1850. // console.log(data)
  1851. let durls = data && data.durl;
  1852.  
  1853. if (!durls) {
  1854. const _zc = window.Gc || window.zc ||
  1855. Object.values(window).filter(
  1856. x => typeof x == "string" && x.includes("[Info]")
  1857. )[0];
  1858.  
  1859. data = JSON.parse(
  1860. _zc.split("\n").filter(
  1861. x => x.startsWith("{")
  1862. ).pop()
  1863. );
  1864.  
  1865. const _data_X = data.Y || data.X ||
  1866. Object.values(data).filter(
  1867. x => typeof x == "object" && Object.prototype.toString.call(x) == "[object Object]"
  1868. )[0];
  1869.  
  1870. durls = _data_X.segments || [_data_X];
  1871. }
  1872.  
  1873. // console.log(data)
  1874.  
  1875. let flvs = durls.map(url_obj => url_obj.url.replace("http://", "https://"));
  1876.  
  1877. this.flvs = flvs;
  1878.  
  1879. let video_format = data.format && (data.format.match(/mp4|flv/) || [])[0];
  1880.  
  1881. this.video_format = video_format;
  1882.  
  1883. return video_format
  1884. case 'ass':
  1885. if (this.ass)
  1886. return this.ass;
  1887. else
  1888. return this.getASS(this.flvFormatName);
  1889. default:
  1890. throw `Bilimonkey: What is format ${format}?`;
  1891. }
  1892. });
  1893. }
  1894.  
  1895. hangPlayer() {
  1896. this.playerWin.document.getElementsByTagName('video')[0].src = "data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAsxtZGF0AAACrgYF//+q3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE0OCByMjY0MyA1YzY1NzA0IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxNSAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDExMyBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MSBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTEgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAgZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz0zIGJfcHlyYW1pZD0yIGJfYWRhcHQ9MSBiX2JpYXM9MCBkaXJlY3Q9MSB3ZWlnaHRiPTEgb3Blbl9nb3A9MCB3ZWlnaHRwPTIga2V5aW50PTI1MCBrZXlpbnRfbWluPTI1IHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NDAgcmM9Y3JmIG1idHJlZT0xIGNyZj0yMy4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAAADmWIhABf/qcv4FM6/0nHAAAC7G1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAoAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIWdHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAQAAAAEAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAKAAAAAAAAQAAAAABjm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAMgAAAAIAFccAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAATltaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAD5c3RibAAAAJVzdHNkAAAAAAAAAAEAAACFYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAQABAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC9hdmNDAWQACv/hABZnZAAKrNlehAAAAwAEAAADAMg8SJZYAQAGaOvjyyLAAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAIAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAsQAAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAABidWR0YQAAAFptZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAAC1pbHN0AAAAJal0b28AAAAdZGF0YQAAAAEAAAAATGF2ZjU2LjQwLjEwMQ==";
  1897. }
  1898.  
  1899. async loadFLVFromCache(index) {
  1900. if (!this.cache) return;
  1901. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  1902. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  1903. let item = await this.cache.getData(name);
  1904. if (!item) return;
  1905. return this.flvsBlob[index] = item.data;
  1906. }
  1907.  
  1908. async loadPartialFLVFromCache(index) {
  1909. if (!this.cache) return;
  1910. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  1911. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  1912. name = 'PC_' + name;
  1913. let item = await this.cache.getData(name);
  1914. if (!item) return;
  1915. return item.data;
  1916. }
  1917.  
  1918. async loadAllFLVFromCache() {
  1919. if (!this.cache) return;
  1920. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  1921.  
  1922. let promises = [];
  1923. for (let i = 0; i < this.flvs.length; i++) promises.push(this.loadFLVFromCache(i));
  1924.  
  1925. return Promise.all(promises);
  1926. }
  1927.  
  1928. async saveFLVToCache(index, blob) {
  1929. if (!this.cache) return;
  1930. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  1931. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  1932. return this.cache.addData({ name, data: blob });
  1933. }
  1934.  
  1935. async savePartialFLVToCache(index, blob) {
  1936. if (!this.cache) return;
  1937. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  1938. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  1939. name = 'PC_' + name;
  1940. return this.cache.putData({ name, data: blob });
  1941. }
  1942.  
  1943. async cleanPartialFLVInCache(index) {
  1944. if (!this.cache) return;
  1945. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  1946. let name = this.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  1947. name = 'PC_' + name;
  1948. return this.cache.deleteData(name);
  1949. }
  1950.  
  1951. async getFLV(index, progressHandler) {
  1952. if (this.flvsBlob[index]) return this.flvsBlob[index];
  1953.  
  1954. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  1955. this.flvsBlob[index] = (async () => {
  1956. let cache = await this.loadFLVFromCache(index);
  1957. if (cache) return this.flvsBlob[index] = cache;
  1958. let partialFLVFromCache = await this.loadPartialFLVFromCache(index);
  1959.  
  1960. let burl = this.flvs[index];
  1961. if (partialFLVFromCache) burl += `&bstart=${partialFLVFromCache.size}`;
  1962. let opt = {
  1963. fetch: this.playerWin.fetch,
  1964. method: 'GET',
  1965. mode: 'cors',
  1966. cache: 'default',
  1967. referrerPolicy: 'no-referrer-when-downgrade',
  1968. cacheLoaded: partialFLVFromCache ? partialFLVFromCache.size : 0,
  1969. headers: partialFLVFromCache && (!burl.includes('wsTime')) ? { Range: `bytes=${partialFLVFromCache.size}-` } : undefined
  1970. };
  1971. opt.onprogress = progressHandler;
  1972. opt.onerror = opt.onabort = ({ target, type }) => {
  1973. let partialFLV = target.getPartialBlob();
  1974. if (partialFLVFromCache) partialFLV = new Blob([partialFLVFromCache, partialFLV]);
  1975. this.savePartialFLVToCache(index, partialFLV);
  1976. };
  1977.  
  1978. let fch = new DetailedFetchBlob(burl, opt);
  1979. this.flvsDetailedFetch[index] = fch;
  1980. let fullFLV = await fch.getBlob();
  1981. this.flvsDetailedFetch[index] = undefined;
  1982. if (partialFLVFromCache) {
  1983. fullFLV = new Blob([partialFLVFromCache, fullFLV]);
  1984. this.cleanPartialFLVInCache(index);
  1985. }
  1986. this.saveFLVToCache(index, fullFLV);
  1987. return (this.flvsBlob[index] = fullFLV);
  1988. })();
  1989. return this.flvsBlob[index];
  1990. }
  1991.  
  1992. async abortFLV(index) {
  1993. if (this.flvsDetailedFetch[index]) return this.flvsDetailedFetch[index].abort();
  1994. }
  1995.  
  1996. async getAllFLVs(progressHandler) {
  1997. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  1998. let promises = [];
  1999. for (let i = 0; i < this.flvs.length; i++) promises.push(this.getFLV(i, progressHandler));
  2000. return Promise.all(promises);
  2001. }
  2002.  
  2003. async cleanAllFLVsInCache() {
  2004. if (!this.cache) return;
  2005. if (!this.flvs) throw 'BiliMonkey: info uninitialized';
  2006.  
  2007. let ret = [];
  2008. for (let flv of this.flvs) {
  2009. let name = flv.match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  2010. ret.push(await this.cache.deleteData(name));
  2011. ret.push(await this.cache.deleteData('PC_' + name));
  2012. }
  2013.  
  2014. return ret;
  2015. }
  2016.  
  2017. async setupProxy(res, onsuccess) {
  2018. if (!this.setupProxy._fetch) {
  2019. const _fetch = this.setupProxy._fetch = this.playerWin.fetch;
  2020. this.playerWin.fetch = function (input, init) {
  2021. if (!input.slice || input.slice(0, 5) != 'blob:') {
  2022. return _fetch(input, init);
  2023. }
  2024. let bstart = input.indexOf('?bstart=');
  2025. if (bstart < 0) {
  2026. return _fetch(input, init);
  2027. }
  2028. if (!init.headers instanceof Headers) init.headers = new Headers(init.headers || {});
  2029. init.headers.set('Range', `bytes=${input.slice(bstart + 8)}-`);
  2030. return _fetch(input.slice(0, bstart), init)
  2031. };
  2032. this.destroy.addCallback(() => this.playerWin.fetch = _fetch);
  2033. }
  2034.  
  2035. await this.loadAllFLVFromCache();
  2036. let resProxy = Object.assign({}, res);
  2037. for (let i = 0; i < this.flvsBlob.length; i++) {
  2038. if (this.flvsBlob[i]) resProxy.durl[i].url = this.playerWin.URL.createObjectURL(this.flvsBlob[i]);
  2039. }
  2040. return onsuccess(resProxy);
  2041. }
  2042.  
  2043. static async fetchDanmaku(cid) {
  2044. return ASSConverter.parseXML(
  2045. await new Promise((resolve, reject) => {
  2046. const e = new XMLHttpRequest();
  2047. e.onload = () => resolve(e.responseText);
  2048. e.onerror = reject;
  2049. e.open('get', `https://comment.bilibili.com/${cid}.xml`);
  2050. e.send();
  2051. })
  2052. );
  2053. }
  2054.  
  2055. static async getAllPageDefaultFormats(playerWin = top, monkey) {
  2056. /** @returns {Promise<{cid: number; page: number; part?: string; }[]>} */
  2057. const getPartsList = async () => {
  2058. const r = await fetch(`https://api.bilibili.com/x/player/pagelist?aid=${aid}`);
  2059. const json = await r.json();
  2060. return json.data
  2061. };
  2062.  
  2063. const list = await getPartsList();
  2064.  
  2065. const queryInfoMutex = new Mutex();
  2066.  
  2067. const _getDataList = () => {
  2068. const _zc = playerWin.Gc || playerWin.zc ||
  2069. Object.values(playerWin).filter(
  2070. x => typeof x == "string" && x.includes("[Info]")
  2071. )[0];
  2072. return _zc.split("\n").filter(
  2073. x => x.startsWith("{")
  2074. )
  2075. };
  2076.  
  2077. // from the first page
  2078. playerWin.player.next(1);
  2079. const initialDataSize = new Set(_getDataList()).size;
  2080.  
  2081. const retPromises = list.map((x, n) => (async () => {
  2082. await queryInfoMutex.lock();
  2083.  
  2084. const cid = x.cid;
  2085. const danmuku = await new ASSConverter().genASSBlob(
  2086. await BiliMonkey.fetchDanmaku(cid), top.document.title, top.location.href
  2087. );
  2088.  
  2089. const isBangumi = location.pathname.includes("bangumi") || location.hostname.includes("bangumi");
  2090. const apiPath = isBangumi ? "/pgc/player/web/playurl" : "/x/player/playurl";
  2091.  
  2092. const qn = (monkey.option.enableVideoMaxResolution && monkey.option.videoMaxResolution) || "120";
  2093. const api_url = `https://api.bilibili.com${apiPath}?avid=${aid}&cid=${cid}&otype=json&qn=${qn}`;
  2094. const r = await fetch(api_url, { credentials: 'include' });
  2095.  
  2096. const apiJson = await r.json();
  2097. const res = apiJson.data || apiJson.result;
  2098.  
  2099. if (!res.durl) {
  2100. await new Promise(resolve => {
  2101. const i = setInterval(() => {
  2102. const dataSize = new Set(
  2103. _getDataList()
  2104. ).size;
  2105.  
  2106. if (list.length == 1 || dataSize == n + initialDataSize + 1) {
  2107. clearInterval(i);
  2108. resolve();
  2109. }
  2110. }, 100);
  2111. });
  2112.  
  2113. const data = JSON.parse(
  2114. _getDataList().pop()
  2115. );
  2116.  
  2117. const _data_X = data.Y || data.X ||
  2118. Object.values(data).filter(
  2119. x => typeof x == "object" && Object.prototype.toString.call(x) == "[object Object]"
  2120. )[0];
  2121.  
  2122. res.durl = _data_X.segments || [_data_X];
  2123. }
  2124.  
  2125. queryInfoMutex.unlock();
  2126. playerWin.player.next();
  2127.  
  2128. return ({
  2129. durl: res.durl.map(({ url }) => url.replace('http:', playerWin.location.protocol)),
  2130. danmuku,
  2131. name: x.part || x.index || playerWin.document.title.replace("_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili", ""),
  2132. outputName: res.durl[0].url.match(/\d+-\d+(?:\d|-|hd)*(?=\.flv)/) ?
  2133. /***
  2134. * see #28
  2135. * Firefox lookbehind assertion not implemented https://bugzilla.mozilla.org/show_bug.cgi?id=1225665
  2136. * try replace /-\d+(?=(?:\d|-|hd)*\.flv)/ => /(?<=\d+)-\d+(?=(?:\d|-|hd)*\.flv)/ in the future
  2137. */
  2138. res.durl[0].url.match(/\d+-\d+(?:\d|-|hd)*(?=\.flv)/)[0].replace(/-\d+(?=(?:\d|-|hd)*\.flv)/, '')
  2139. : res.durl[0].url.match(/\d(?:\d|-|hd)*(?=\.mp4)/) ?
  2140. res.durl[0].url.match(/\d(?:\d|-|hd)*(?=\.mp4)/)[0]
  2141. : cid,
  2142. cid,
  2143. res,
  2144. });
  2145. })());
  2146.  
  2147. const ret = await Promise.all(retPromises);
  2148.  
  2149. return ret;
  2150. }
  2151.  
  2152. static async getBiliShortVideoInfo() {
  2153. const video_id = location.pathname.match(/\/video\/(\d+)/)[1];
  2154. const api_url = `https://api.vc.bilibili.com/clip/v1/video/detail?video_id=${video_id}&need_playurl=1`;
  2155.  
  2156. const req = await fetch(api_url, { credentials: 'include' });
  2157. const data = (await req.json()).data;
  2158. const { video_playurl, first_pic: cover_img } = data.item;
  2159.  
  2160. return { video_playurl: video_playurl.replace("http://", "https://"), cover_img }
  2161. }
  2162.  
  2163. static formatToValue(format) {
  2164. if (format == 'does_not_exist') throw `formatToValue: cannot lookup does_not_exist`;
  2165. if (typeof BiliMonkey.formatToValue.dict == 'undefined') BiliMonkey.formatToValue.dict = {
  2166. 'hdflv2': '120',
  2167. 'flv_p60': '116',
  2168. 'flv720_p60': '74',
  2169. 'flv': '80',
  2170. 'flv720': '64',
  2171. 'flv480': '32',
  2172. 'flv360': '15',
  2173.  
  2174. // legacy - late 2017
  2175. 'hdflv2': '112',
  2176. 'hdmp4': '64', // data-value is still '64' instead of '48'. '48',
  2177. 'mp4': '16',
  2178. };
  2179. return BiliMonkey.formatToValue.dict[format] || null;
  2180. }
  2181.  
  2182. static valueToFormat(value) {
  2183. if (typeof BiliMonkey.valueToFormat.dict == 'undefined') BiliMonkey.valueToFormat.dict = {
  2184. '120': 'hdflv2',
  2185. '116': 'flv_p60',
  2186. '74': 'flv720_p60',
  2187. '80': 'flv',
  2188. '64': 'flv720',
  2189. '32': 'flv480',
  2190. '15': 'flv360',
  2191.  
  2192. // legacy - late 2017
  2193. '112': 'hdflv2',
  2194. '48': 'hdmp4',
  2195. '16': 'mp4',
  2196.  
  2197. // legacy - early 2017
  2198. '3': 'flv',
  2199. '2': 'hdmp4',
  2200. '1': 'mp4',
  2201. };
  2202. return BiliMonkey.valueToFormat.dict[value] || null;
  2203. }
  2204.  
  2205. static get optionDescriptions() {
  2206. return [
  2207. // 1. cache
  2208. ['cache', '关标签页不清缓存:保留完全下载好的分段到缓存,忘记另存为也没关系。'],
  2209. ['partial', '断点续传:点击“取消”保留部分下载的分段到缓存,忘记点击会弹窗确认。'],
  2210. ['proxy', '用缓存加速播放器:如果缓存里有完全下载好的分段,直接喂给网页播放器,不重新访问网络。小水管利器,播放只需500k流量。如果实在搞不清怎么播放ASS弹幕,也可以就这样用。'],
  2211.  
  2212. // 2. customizing
  2213. ['blocker', '弹幕过滤:在网页播放器里设置的屏蔽词也对下载的弹幕生效。'],
  2214. ['font', '自定义字体:在网页播放器里设置的字体、大小、加粗、透明度也对下载的弹幕生效。'],
  2215. ['resolution', '(测)自定义弹幕画布分辨率:仅对下载的弹幕生效。(默认值: 560 x 420)'],
  2216. ];
  2217. }
  2218.  
  2219. static get resolutionPreferenceOptions() {
  2220. return [
  2221. ['超清 4K (大会员)', '120'],
  2222. ['高清 1080P60 (大会员)', '116'],
  2223. ['高清 1080P+ (大会员)', '112'],
  2224. ['高清 720P60 (大会员)', '74'],
  2225. ['高清 1080P', '80'],
  2226. ['高清 720P', '64'],
  2227. ['清晰 480P', '32'],
  2228. ['流畅 360P', '16'],
  2229. ]
  2230. }
  2231.  
  2232. static get optionDefaults() {
  2233. return {
  2234. // 1. automation
  2235. autoDefault: true,
  2236. autoFLV: false,
  2237. autoMP4: false,
  2238.  
  2239. // 2. cache
  2240. cache: true,
  2241. partial: true,
  2242. proxy: true,
  2243.  
  2244. // 3. customizing
  2245. blocker: true,
  2246. font: true,
  2247. resolution: false,
  2248. resolutionX: 560,
  2249. resolutionY: 420,
  2250. videoMaxResolution: "120",
  2251. enableVideoMaxResolution: false,
  2252. }
  2253. }
  2254.  
  2255. static _UNIT_TEST() {
  2256. return (async () => {
  2257. let playerWin = await BiliUserJS.getPlayerWin();
  2258. window.m = new BiliMonkey(playerWin);
  2259.  
  2260. console.warn('data race test');
  2261. m.queryInfo('video');
  2262. console.log(m.queryInfo('video'));
  2263.  
  2264. //location.reload();
  2265. })();
  2266. }
  2267. }
  2268.  
  2269. /***
  2270. * BiliPolyfill
  2271. * A bilibili user script
  2272. * Copyright (C) 2018 Qli5. All Rights Reserved.
  2273. *
  2274. * @author qli5 <goodlq11[at](163|gmail).com>
  2275. *
  2276. * This Source Code Form is subject to the terms of the Mozilla Public
  2277. * License, v. 2.0. If a copy of the MPL was not distributed with this
  2278. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  2279. */
  2280.  
  2281. class BiliPolyfill {
  2282. /***
  2283. * Assumption: aid, cid, pageno does not change during lifecycle
  2284. * Create a new BiliPolyfill if assumption breaks
  2285. */
  2286. constructor(playerWin, option = BiliPolyfill.optionDefaults, hintInfo = () => { }) {
  2287. this.playerWin = playerWin;
  2288. this.option = option;
  2289. this.hintInfo = hintInfo;
  2290.  
  2291. this.video = null;
  2292.  
  2293. this.series = [];
  2294. this.userdata = { oped: {}, restore: {} };
  2295.  
  2296. this.destroy = new HookedFunction();
  2297. this.playerWin.addEventListener('beforeunload', this.destroy);
  2298. this.destroy.addCallback(() => this.playerWin.removeEventListener('beforeunload', this.destroy));
  2299.  
  2300. this.BiliDanmakuSettings =
  2301. class BiliDanmakuSettings {
  2302. static getPlayerSettings() {
  2303. return playerWin.localStorage.bilibili_player_settings && JSON.parse(playerWin.localStorage.bilibili_player_settings)
  2304. }
  2305. static get(key) {
  2306. const player_settings = BiliDanmakuSettings.getPlayerSettings();
  2307. return player_settings.setting_config && player_settings.setting_config[key]
  2308. }
  2309. static set(key, value) {
  2310. const player_settings = BiliDanmakuSettings.getPlayerSettings();
  2311. player_settings.setting_config[key] = value;
  2312. playerWin.localStorage.bilibili_player_settings = JSON.stringify(player_settings);
  2313. }
  2314. };
  2315. }
  2316.  
  2317. saveUserdata() {
  2318. this.option.setStorage('biliPolyfill', JSON.stringify(this.userdata));
  2319. }
  2320.  
  2321. retrieveUserdata() {
  2322. try {
  2323. this.userdata = this.option.getStorage('biliPolyfill');
  2324. if (this.userdata.length > 1073741824) top.alert('BiliPolyfill脚本数据已经快满了,在播放器上右键->BiliPolyfill->片头片尾->检视数据,删掉一些吧。');
  2325. this.userdata = JSON.parse(this.userdata);
  2326. }
  2327. catch (e) { }
  2328. finally {
  2329. if (!this.userdata) this.userdata = {};
  2330. if (!(this.userdata.oped instanceof Object)) this.userdata.oped = {};
  2331. if (!(this.userdata.restore instanceof Object)) this.userdata.restore = {};
  2332. }
  2333. }
  2334.  
  2335. async setFunctions({ videoRefresh = false } = {}) {
  2336. // 1. initialize
  2337. this.video = await this.getPlayerVideo();
  2338.  
  2339. if (!videoRefresh) {
  2340. this.retrieveUserdata();
  2341. }
  2342.  
  2343. // 2. if not enabled, run the process without real actions
  2344. if (!this.option.betabeta) return this.getPlayerMenu();
  2345.  
  2346. // 3. set up functions that are cid static
  2347. if (!videoRefresh) {
  2348. if (this.option.badgeWatchLater) {
  2349. await this.getWatchLaterBtn();
  2350. this.badgeWatchLater();
  2351. }
  2352. if (this.option.scroll) this.scrollToPlayer();
  2353.  
  2354. if (this.option.series) this.inferNextInSeries();
  2355.  
  2356. if (this.option.recommend) this.showRecommendTab();
  2357. if (this.option.focus) this.focusOnPlayer();
  2358. if (this.option.restorePrevent) this.restorePreventShade();
  2359. if (this.option.restoreDanmuku) this.restoreDanmukuSwitch();
  2360. if (this.option.restoreSpeed) this.restoreSpeed();
  2361. if (this.option.restoreWide) {
  2362. await this.getWideScreenBtn();
  2363. this.restoreWideScreen();
  2364. }
  2365. if (this.option.autoResume) this.autoResume();
  2366. if (this.option.autoPlay) this.autoPlay();
  2367. if (this.option.autoFullScreen) this.autoFullScreen();
  2368. if (this.option.limitedKeydown) this.limitedKeydownFullScreenPlay();
  2369. this.destroy.addCallback(() => this.saveUserdata());
  2370. }
  2371.  
  2372. // 4. set up functions that are binded to the video DOM
  2373. if (this.option.dblclick) this.dblclickFullScreen();
  2374. if (this.option.electric) this.reallocateElectricPanel();
  2375. if (this.option.oped) this.skipOPED();
  2376. this.video.addEventListener('emptied', () => this.setFunctions({ videoRefresh: true }), { once: true });
  2377.  
  2378. // 5. set up functions that require everything to be ready
  2379. await this.getPlayerMenu();
  2380. if (this.option.menuFocus) this.menuFocusOnPlayer();
  2381.  
  2382. // 6. set up experimental functions
  2383. if (this.option.speech) top.document.body.addEventListener('click', e => e.detail > 2 && this.speechRecognition());
  2384. }
  2385.  
  2386. async inferNextInSeries() {
  2387. // 1. find current title
  2388. const title = top.document.getElementsByTagName('h1')[0].textContent.replace(/\(\d+\)$/, '').trim();
  2389.  
  2390. // 2. find current ep number
  2391. const ep = title.match(/\d+(?=[^\d]*$)/);
  2392. if (!ep) return this.series = [];
  2393.  
  2394. // 3. current title - current ep number => series common title
  2395. const seriesTitle = title.slice(0, title.lastIndexOf(ep)).trim();
  2396.  
  2397. // 4. find sibling ep number
  2398. const epNumber = parseInt(ep);
  2399. const epSibling = ep[0] == '0' ?
  2400. [(epNumber - 1).toString().padStart(ep.length, '0'), (epNumber + 1).toString().padStart(ep.length, '0')] :
  2401. [(epNumber - 1).toString(), (epNumber + 1).toString()];
  2402.  
  2403. // 5. build search keywords
  2404. // [self, seriesTitle + epSibling, epSibling]
  2405. const keywords = [title, ...epSibling.map(e => seriesTitle + e), ...epSibling];
  2406.  
  2407. // 6. find mid
  2408. const midParent = top.document.querySelector('.u-info > .name') || top.document.getElementById('r-info-rank') || top.document.querySelector('.user');
  2409. if (!midParent) return this.series = [];
  2410. const mid = midParent.children[0].href.match(/\d+/)[0];
  2411.  
  2412. // 7. fetch query
  2413. const vlist = await Promise.all(keywords.map(keyword => new Promise((resolve, reject) => {
  2414. const req = new XMLHttpRequest();
  2415. req.onload = () => resolve((req.response.status && req.response.data.vlist) || []);
  2416. req.onerror = reject;
  2417. req.open('get', `https://space.bilibili.com/ajax/member/getSubmitVideos?mid=${mid}&keyword=${keyword}`);
  2418. req.responseType = 'json';
  2419. req.send();
  2420. })));
  2421.  
  2422. // 8. verify current video exists
  2423. vlist[0] = vlist[0].filter(e => e.title == title);
  2424. if (!vlist[0][0]) { console && console.warn('BiliPolyfill: inferNextInSeries: cannot find current video in mid space'); return this.series = []; }
  2425.  
  2426. // 9. if seriesTitle + epSibling qurey has reasonable results => pick
  2427. this.series = [vlist[1].find(e => e.created < vlist[0][0].created), vlist[2].reverse().find(e => e.created > vlist[0][0].created)];
  2428.  
  2429. // 10. fallback: if epSibling qurey has reasonable results => pick
  2430. if (!this.series[0]) this.series[0] = vlist[3].find(e => e.created < vlist[0][0].created);
  2431. if (!this.series[1]) this.series[1] = vlist[4].reverse().find(e => e.created > vlist[0][0].created);
  2432.  
  2433. return this.series;
  2434. }
  2435.  
  2436. badgeWatchLater() {
  2437. // 1. find watchlater button
  2438. 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]');
  2439. if (!li) return;
  2440.  
  2441. // 2. initialize watchlater panel
  2442. const observer = new MutationObserver(() => {
  2443.  
  2444. // 3. hide watchlater panel
  2445. observer.disconnect();
  2446. li.children[1].style.visibility = 'hidden';
  2447.  
  2448. // 4. loading => wait
  2449. if (li.children[1].children[0].children[0].className == 'm-w-loading') {
  2450. const observer = new MutationObserver(() => {
  2451.  
  2452. // 5. clean up watchlater panel
  2453. observer.disconnect();
  2454. li.dispatchEvent(new Event('mouseleave'));
  2455. setTimeout(() => li.children[1].style.visibility = '', 700);
  2456.  
  2457. // 6.1 empty list => do nothing
  2458. if (li.children[1].children[0].children[0].className == 'no-data') return;
  2459.  
  2460. // 6.2 otherwise => append div
  2461. const div = top.document.createElement('div');
  2462. div.className = 'num';
  2463. if (li.children[1].children[0].children[0].children.length > 5) {
  2464. div.textContent = '5+';
  2465. }
  2466. else {
  2467. div.textContent = li.children[1].children[0].children[0].children.length;
  2468. }
  2469. li.children[0].append(div);
  2470. this.destroy.addCallback(() => div.remove());
  2471. });
  2472. observer.observe(li.children[1].children[0], { childList: true });
  2473. }
  2474.  
  2475. // 4.2 otherwise => error
  2476. else {
  2477. throw 'badgeWatchLater: cannot find m-w-loading panel';
  2478. }
  2479. });
  2480. observer.observe(li, { childList: true });
  2481. li.dispatchEvent(new Event('mouseenter'));
  2482. }
  2483.  
  2484. dblclickFullScreen() {
  2485. this.video.addEventListener('dblclick', () =>
  2486. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click()
  2487. );
  2488. }
  2489.  
  2490. scrollToPlayer() {
  2491. if (top.scrollY < 200) top.document.getElementById('bofqi').scrollIntoView();
  2492. }
  2493.  
  2494. showRecommendTab() {
  2495. const h = this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-filter-btn-recommend');
  2496. if (h) h.click();
  2497. }
  2498.  
  2499. async getCoverImage() { // 番剧用原来的方法只能获取到番剧的封面,改用API可以获取到每集的封面
  2500. const viewUrl = "https://api.bilibili.com/x/web-interface/view?aid=" + aid;
  2501.  
  2502. try {
  2503. const res = await fetch(viewUrl);
  2504. const viewJson = await res.json();
  2505. return viewJson.data.pic.replace("http://", "https://")
  2506. }
  2507. catch (e) {
  2508. return null
  2509. }
  2510. }
  2511.  
  2512. reallocateElectricPanel() {
  2513. // 1. autopart == wait => ok
  2514. if (!this.playerWin.localStorage.bilibili_player_settings) return;
  2515. if (!this.playerWin.localStorage.bilibili_player_settings.includes('"autopart":1') && !this.option.electricSkippable) return;
  2516.  
  2517. // 2. wait for electric panel
  2518. this.video.addEventListener('ended', () => {
  2519. setTimeout(() => {
  2520. // 3. click skip
  2521. const electricPanel = this.playerWin.document.getElementsByClassName('bilibili-player-electric-panel')[0];
  2522. if (!electricPanel) return;
  2523. electricPanel.children[2].click();
  2524.  
  2525. // 4. but display a fake electric panel
  2526. electricPanel.style.display = 'block';
  2527. electricPanel.style.zIndex = 233;
  2528.  
  2529. // 5. and perform a fake countdown
  2530. let countdown = 5;
  2531. const h = setInterval(() => {
  2532. // 5.1 yield to next part hint
  2533. if (this.playerWin.document.getElementsByClassName('bilibili-player-video-toast-item-jump')[0]) electricPanel.style.zIndex = '';
  2534.  
  2535. // 5.2 countdown > 0 => update textContent
  2536. if (countdown > 0) {
  2537. electricPanel.children[2].children[0].textContent = `0${countdown}`;
  2538. countdown--;
  2539. }
  2540.  
  2541. // 5.3 countdown == 0 => clean up
  2542. else {
  2543. clearInterval(h);
  2544. electricPanel.remove();
  2545. }
  2546. }, 1000);
  2547. }, 0);
  2548. }, { once: true });
  2549. }
  2550.  
  2551. /**
  2552. * As of March 2018:
  2553. * opacity:
  2554. * bilibili_player_settings.setting_config.opacity
  2555. * persist :)
  2556. * preventshade:
  2557. * bilibili_player_settings.setting_config.preventshade
  2558. * will be overwritten
  2559. * bilibili has a broken setting roaming scheme where the preventshade default is always used
  2560. * type_bottom, type_scroll, type_top:
  2561. * bilibili_player_settings.setting_config.type_(bottom|scroll|top)
  2562. * sessionStorage ONLY
  2563. * not sure if it is a feature or a bug
  2564. * danmaku switch:
  2565. * not stored
  2566. * videospeed:
  2567. * bilibili_player_settings.video_status.videospeed
  2568. * sessionStorage ONLY
  2569. * same as above
  2570. * widescreen:
  2571. * same as above
  2572. */
  2573. restorePreventShade() {
  2574. // 1. restore option should be an array
  2575. if (!Array.isArray(this.userdata.restore.preventShade)) this.userdata.restore.preventShade = [];
  2576.  
  2577. // 2. find corresponding option index
  2578. const index = top.location.href.includes('bangumi') ? 0 : 1;
  2579.  
  2580. // 3. MUST initialize setting panel before click
  2581. let danmaku_btn = this.playerWin.document.querySelector('.bilibili-player-video-btn-danmaku, .bilibili-player-video-danmaku-setting');
  2582. if (!danmaku_btn) return;
  2583. danmaku_btn.dispatchEvent(new Event('mouseover'));
  2584.  
  2585. // 4. restore if true
  2586. const input = this.playerWin.document.querySelector(".bilibili-player-video-danmaku-setting-left-preventshade input");
  2587. if (this.userdata.restore.preventShade[index] && !input.checked) {
  2588. input.click();
  2589. }
  2590.  
  2591. // 5. clean up setting panel
  2592. danmaku_btn.dispatchEvent(new Event('mouseout'));
  2593.  
  2594. // 6. memorize option
  2595. this.destroy.addCallback(() => {
  2596. this.userdata.restore.preventShade[index] = input.checked;
  2597. });
  2598. }
  2599.  
  2600. restoreDanmukuSwitch() {
  2601. // 1. restore option should be an array
  2602. if (!Array.isArray(this.userdata.restore.danmukuSwitch)) this.userdata.restore.danmukuSwitch = [];
  2603. if (!Array.isArray(this.userdata.restore.danmukuScrollSwitch)) this.userdata.restore.danmukuScrollSwitch = [];
  2604. if (!Array.isArray(this.userdata.restore.danmukuTopSwitch)) this.userdata.restore.danmukuTopSwitch = [];
  2605. if (!Array.isArray(this.userdata.restore.danmukuBottomSwitch)) this.userdata.restore.danmukuBottomSwitch = [];
  2606. if (!Array.isArray(this.userdata.restore.danmukuColorSwitch)) this.userdata.restore.danmukuColorSwitch = [];
  2607. if (!Array.isArray(this.userdata.restore.danmukuSpecialSwitch)) this.userdata.restore.danmukuSpecialSwitch = [];
  2608.  
  2609. // 2. find corresponding option index
  2610. const index = top.location.href.includes('bangumi') ? 0 : 1;
  2611.  
  2612. // 3. MUST initialize setting panel before click
  2613. let danmaku_btn = this.playerWin.document.querySelector('.bilibili-player-video-btn-danmaku, .bilibili-player-video-danmaku-setting');
  2614. if (!danmaku_btn) return;
  2615. danmaku_btn.dispatchEvent(new Event('mouseover'));
  2616.  
  2617. // 4. restore if true
  2618. // 4.1 danmukuSwitch
  2619. const danmukuSwitchInput = this.playerWin.document.querySelector('.bilibili-player-video-danmaku-switch input');
  2620. if (this.userdata.restore.danmukuSwitch[index] && danmukuSwitchInput.checked) {
  2621. danmukuSwitchInput.click();
  2622. }
  2623.  
  2624. // 4.2 danmukuScrollSwitch danmukuTopSwitch danmukuBottomSwitch danmukuColorSwitch danmukuSpecialSwitch
  2625. const [danmukuScrollSwitchDiv, danmukuTopSwitchDiv, danmukuBottomSwitchDiv, danmukuColorSwitchDiv, danmukuSpecialSwitchDiv] = this.playerWin.document.querySelector('.bilibili-player-video-danmaku-setting-left-block-content').children;
  2626. if (this.userdata.restore.danmukuScrollSwitch[index] && !danmukuScrollSwitchDiv.classList.contains('disabled')) {
  2627. danmukuScrollSwitchDiv.click();
  2628. }
  2629. if (this.userdata.restore.danmukuTopSwitch[index] && !danmukuTopSwitchDiv.classList.contains('disabled')) {
  2630. danmukuTopSwitchDiv.click();
  2631. }
  2632. if (this.userdata.restore.danmukuBottomSwitch[index] && !danmukuBottomSwitchDiv.classList.contains('disabled')) {
  2633. danmukuBottomSwitchDiv.click();
  2634. }
  2635. if (this.userdata.restore.danmukuColorSwitch[index] && !danmukuColorSwitchDiv.classList.contains('disabled')) {
  2636. danmukuColorSwitchDiv.click();
  2637. }
  2638. if (this.userdata.restore.danmukuSpecialSwitch[index] && !danmukuSpecialSwitchDiv.classList.contains('disabled')) {
  2639. danmukuSpecialSwitchDiv.click();
  2640. }
  2641.  
  2642. // 5. clean up setting panel
  2643. danmaku_btn.dispatchEvent(new Event('mouseout'));
  2644.  
  2645. // 6. memorize final option
  2646. this.destroy.addCallback(() => {
  2647. this.userdata.restore.danmukuSwitch[index] = !danmukuSwitchInput.checked;
  2648. this.userdata.restore.danmukuScrollSwitch[index] = danmukuScrollSwitchDiv.classList.contains('disabled');
  2649. this.userdata.restore.danmukuTopSwitch[index] = danmukuTopSwitchDiv.classList.contains('disabled');
  2650. this.userdata.restore.danmukuBottomSwitch[index] = danmukuBottomSwitchDiv.classList.contains('disabled');
  2651. this.userdata.restore.danmukuColorSwitch[index] = danmukuColorSwitchDiv.classList.contains('disabled');
  2652. this.userdata.restore.danmukuSpecialSwitch[index] = danmukuSpecialSwitchDiv.classList.contains('disabled');
  2653. });
  2654. }
  2655.  
  2656. restoreSpeed() {
  2657. // 1. restore option should be an array
  2658. if (!Array.isArray(this.userdata.restore.speed)) this.userdata.restore.speed = [];
  2659.  
  2660. // 2. find corresponding option index
  2661. const index = top.location.href.includes('bangumi') ? 0 : 1;
  2662.  
  2663. // 3. restore if different
  2664. if (this.userdata.restore.speed[index] && this.userdata.restore.speed[index] != this.video.playbackRate) {
  2665. this.video.playbackRate = this.userdata.restore.speed[index];
  2666. }
  2667.  
  2668. // 4. memorize option
  2669. this.playerWin.player.addEventListener("video_before_destroy", () => this.saveSpeed());
  2670.  
  2671. const observer = new MutationObserver(() => {
  2672. const changeSpeedBtn = this.playerWin.document.querySelectorAll(".bilibili-player-contextmenu-subwrapp")[0];
  2673. if (changeSpeedBtn && !changeSpeedBtn._memorize_speed) {
  2674. changeSpeedBtn.addEventListener("click", () => this.saveSpeed());
  2675. changeSpeedBtn._memorize_speed = true;
  2676. }
  2677. });
  2678. observer.observe(this.playerWin.document.querySelector("#bilibiliPlayer"), { childList: true, subtree: true });
  2679. }
  2680.  
  2681. saveSpeed() {
  2682. if (this.option.restoreSpeed) {
  2683. // 1. restore option should be an array
  2684. if (!Array.isArray(this.userdata.restore.speed)) this.userdata.restore.speed = [];
  2685.  
  2686. // 2. find corresponding option index
  2687. const index = top.location.href.includes('bangumi') ? 0 : 1;
  2688.  
  2689. // 3. memorize
  2690. this.userdata.restore.speed[index] = this.video.playbackRate;
  2691. }
  2692. }
  2693.  
  2694. restoreWideScreen() {
  2695. // 1. restore option should be an array
  2696. if (!Array.isArray(this.userdata.restore.wideScreen)) this.userdata.restore.wideScreen = [];
  2697.  
  2698. // 2. find corresponding option index
  2699. const index = top.location.href.includes('bangumi') ? 0 : 1;
  2700.  
  2701. // 3. restore if different
  2702. const i = this.playerWin.document.querySelector('.bilibili-player-video-btn-widescreen');
  2703. if (this.userdata.restore.wideScreen[index] && !i.classList.contains('closed') && !i.firstElementChild.classList.contains('icon-24wideon')) {
  2704. i.click();
  2705. }
  2706.  
  2707. // 4. memorize option
  2708. this.destroy.addCallback(() => {
  2709. this.userdata.restore.wideScreen[index] = i.classList.contains('closed') || i.firstElementChild.classList.contains('icon-24wideon');
  2710. });
  2711. }
  2712.  
  2713. loadOffineSubtitles() {
  2714. // NO. NOBODY WILL NEED THIS。
  2715. // Hint: https://github.com/jamiees2/ass-to-vtt
  2716. throw 'Not implemented';
  2717. }
  2718.  
  2719. autoResume() {
  2720. // 1. wait for canplay => wait for resume popup
  2721. const h = () => {
  2722. // 2. parse resume popup
  2723. const span = this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom div.bilibili-player-video-toast-item-text span:nth-child(2)');
  2724. if (!span) return;
  2725. const [min, sec] = span.textContent.split(':');
  2726. if (!min || !sec) return;
  2727.  
  2728. // 3. parse last playback progress
  2729. const time = parseInt(min) * 60 + parseInt(sec);
  2730.  
  2731. // 3.1 still far from end => reasonable to resume => click
  2732. if (time < this.video.duration - 10) {
  2733. // 3.1.1 already playing => no need to pause => simply jump
  2734. if (!this.video.paused || this.video.autoplay) {
  2735. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom div.bilibili-player-video-toast-item-jump').click();
  2736. }
  2737.  
  2738. // 3.1.2 paused => should remain paused after jump => hook video.play
  2739. else {
  2740. const play = this.video.play;
  2741. this.video.play = () => setTimeout(() => {
  2742. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2743. this.video.play = play;
  2744. }, 0);
  2745. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom div.bilibili-player-video-toast-item-jump').click();
  2746. }
  2747. }
  2748.  
  2749. // 3.2 near end => silent popup
  2750. else {
  2751. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom div.bilibili-player-video-toast-item-close').click();
  2752. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-toast-bottom').children[0].style.visibility = 'hidden';
  2753. }
  2754. };
  2755. this.video.addEventListener('canplay', h, { once: true });
  2756. setTimeout(() => this.video && this.video.removeEventListener && this.video.removeEventListener('canplay', h), 3000);
  2757. }
  2758.  
  2759. autoPlay() {
  2760. this.video.autoplay = true;
  2761. setTimeout(() => {
  2762. if (this.video.paused) this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2763. }, 0);
  2764. }
  2765.  
  2766. autoFullScreen() {
  2767. if (this.playerWin.document.querySelector('#bilibiliPlayer div.video-state-fullscreen-off')) {
  2768. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click();
  2769. }
  2770. }
  2771.  
  2772. getCollectionId() {
  2773. if (aid) {
  2774. return `av${aid}`
  2775. }
  2776.  
  2777. return (top.location.pathname.match(/av\d+/) || top.location.hash.match(/av\d+/) || top.document.querySelector('div.bangumi-info a, .media-title').href).toString();
  2778. }
  2779.  
  2780. markOPEDPosition(index) {
  2781. const collectionId = this.getCollectionId();
  2782. if (!Array.isArray(this.userdata.oped[collectionId])) this.userdata.oped[collectionId] = [];
  2783. this.userdata.oped[collectionId][index] = this.video.currentTime;
  2784. this.saveUserdata();
  2785. }
  2786.  
  2787. clearOPEDPosition() {
  2788. const collectionId = this.getCollectionId();
  2789. this.userdata.oped[collectionId] = undefined;
  2790. }
  2791.  
  2792. skipOPED() {
  2793. // 1. find corresponding userdata
  2794. const collectionId = this.getCollectionId();
  2795. if (!Array.isArray(this.userdata.oped[collectionId]) || !this.userdata.oped[collectionId].length) return;
  2796.  
  2797. /**
  2798. * structure:
  2799. * listen for time update -> || <- skip -> || <- remove event listenner
  2800. */
  2801.  
  2802. // 2. | 0 <- opening -> oped[collectionId][1] | <- play --
  2803. if (!this.userdata.oped[collectionId][0] && this.userdata.oped[collectionId][1]) {
  2804. const h = () => {
  2805. if (this.video.currentTime >= this.userdata.oped[collectionId][1] - 1) {
  2806. this.video.removeEventListener('timeupdate', h);
  2807. }
  2808. else {
  2809. this.video.currentTime = this.userdata.oped[collectionId][1];
  2810. this.hintInfo('BiliPolyfill: 已跳过片头');
  2811. }
  2812. };
  2813. this.video.addEventListener('timeupdate', h);
  2814. }
  2815.  
  2816. // 3. | <- play -> | oped[collectionId][0] <- opening -> oped[collectionId][1] | <- play --
  2817. if (this.userdata.oped[collectionId][0] && this.userdata.oped[collectionId][1]) {
  2818. const h = () => {
  2819. if (this.video.currentTime >= this.userdata.oped[collectionId][1] - 1) {
  2820. this.video.removeEventListener('timeupdate', h);
  2821. }
  2822. else if (this.video.currentTime > this.userdata.oped[collectionId][0]) {
  2823. this.video.currentTime = this.userdata.oped[collectionId][1];
  2824. this.hintInfo('BiliPolyfill: 已跳过片头');
  2825. }
  2826. };
  2827. this.video.addEventListener('timeupdate', h);
  2828. }
  2829.  
  2830. // 4. -- play -> | oped[collectionId][2] <- ending -> end |
  2831. if (this.userdata.oped[collectionId][2] && !this.userdata.oped[collectionId][3]) {
  2832. const h = () => {
  2833. if (this.video.currentTime >= this.video.duration - 1) {
  2834. this.video.removeEventListener('timeupdate', h);
  2835. }
  2836. else if (this.video.currentTime > this.userdata.oped[collectionId][2]) {
  2837. this.video.currentTime = this.video.duration;
  2838. this.hintInfo('BiliPolyfill: 已跳过片尾');
  2839. }
  2840. };
  2841. this.video.addEventListener('timeupdate', h);
  2842. }
  2843.  
  2844. // 5.-- play -> | oped[collectionId][2] <- ending -> oped[collectionId][3] | <- play -> end |
  2845. if (this.userdata.oped[collectionId][2] && this.userdata.oped[collectionId][3]) {
  2846. const h = () => {
  2847. if (this.video.currentTime >= this.userdata.oped[collectionId][3] - 1) {
  2848. this.video.removeEventListener('timeupdate', h);
  2849. }
  2850. else if (this.video.currentTime > this.userdata.oped[collectionId][2]) {
  2851. this.video.currentTime = this.userdata.oped[collectionId][3];
  2852. this.hintInfo('BiliPolyfill: 已跳过片尾');
  2853. }
  2854. };
  2855. this.video.addEventListener('timeupdate', h);
  2856. }
  2857. }
  2858.  
  2859. setVideoSpeed(speed) {
  2860. if (speed < 0 || speed > 10) return;
  2861. this.video.playbackRate = speed;
  2862. this.saveSpeed();
  2863. }
  2864.  
  2865. focusOnPlayer() {
  2866. let player = this.playerWin.document.getElementsByClassName('bilibili-player-video-progress')[0];
  2867. if (player) player.click();
  2868. }
  2869.  
  2870. menuFocusOnPlayer() {
  2871. this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black')[0].addEventListener('click', () =>
  2872. setTimeout(() => this.focusOnPlayer(), 0)
  2873. );
  2874. }
  2875.  
  2876. limitedKeydownFullScreenPlay() {
  2877. // 1. listen for any user guesture
  2878. const h = e => {
  2879. // 2. not real user guesture => do nothing
  2880. if (!e.isTrusted) return;
  2881.  
  2882. // 3. key down is Enter => full screen play
  2883. if (e.key == 'Enter') {
  2884. // 3.1 full screen
  2885. if (this.playerWin.document.querySelector('#bilibiliPlayer div.video-state-fullscreen-off')) {
  2886. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click();
  2887. }
  2888.  
  2889. // 3.2 play
  2890. if (this.video.paused) {
  2891. if (this.video.readyState) {
  2892. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2893. }
  2894. else {
  2895. this.video.addEventListener('canplay', () => {
  2896. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2897. }, { once: true });
  2898. }
  2899. }
  2900. }
  2901.  
  2902. // 4. clean up listener
  2903. top.document.removeEventListener('keydown', h);
  2904. top.document.removeEventListener('click', h);
  2905. };
  2906. top.document.addEventListener('keydown', h);
  2907. top.document.addEventListener('click', h);
  2908. }
  2909.  
  2910. speechRecognition() {
  2911. // 1. polyfill
  2912. const SpeechRecognition = top.SpeechRecognition || top.webkitSpeechRecognition;
  2913. const SpeechGrammarList = top.SpeechGrammarList || top.webkitSpeechGrammarList;
  2914.  
  2915. // 2. give hint
  2916. alert('Yahaha! You found me!\nBiliTwin支持的语音命令: 播放 暂停 全屏 关闭 加速 减速 下一集\nChrome may support Cantonese or Hakka as well. See BiliPolyfill::speechRecognition.');
  2917. if (!SpeechRecognition || !SpeechGrammarList) alert('浏览器太旧啦~彩蛋没法运行~');
  2918.  
  2919. // 3. setup recognition
  2920. const player = ['播放', '暂停', '全屏', '关闭', '加速', '减速', '下一集'];
  2921. const grammar = '#JSGF V1.0; grammar player; public <player> = ' + player.join(' | ') + ' ;';
  2922. const recognition = new SpeechRecognition();
  2923. const speechRecognitionList = new SpeechGrammarList();
  2924. speechRecognitionList.addFromString(grammar, 1);
  2925. recognition.grammars = speechRecognitionList;
  2926. // cmn: Mandarin(Putonghua), yue: Cantonese, hak: Hakka
  2927. // See https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
  2928. recognition.lang = 'cmn';
  2929. recognition.continuous = true;
  2930. recognition.interimResults = false;
  2931. recognition.maxAlternatives = 1;
  2932. recognition.start();
  2933. recognition.onresult = e => {
  2934. const last = e.results.length - 1;
  2935. const transcript = e.results[last][0].transcript;
  2936. switch (transcript) {
  2937. case '播放':
  2938. if (this.video.paused) this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2939. this.hintInfo(`BiliPolyfill: 语音:播放`);
  2940. break;
  2941. case '暂停':
  2942. if (!this.video.paused) this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-start').click();
  2943. this.hintInfo(`BiliPolyfill: 语音:暂停`);
  2944. break;
  2945. case '全屏':
  2946. this.playerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click();
  2947. this.hintInfo(`BiliPolyfill: 语音:全屏`);
  2948. break;
  2949. case '关闭':
  2950. top.close();
  2951. break;
  2952. case '加速':
  2953. this.setVideoSpeed(2);
  2954. this.hintInfo(`BiliPolyfill: 语音:加速`);
  2955. break;
  2956. case '减速':
  2957. this.setVideoSpeed(0.5);
  2958. this.hintInfo(`BiliPolyfill: 语音:减速`);
  2959. break;
  2960. case '下一集':
  2961. this.video.dispatchEvent(new Event('ended'));
  2962. default:
  2963. this.hintInfo(`BiliPolyfill: 语音:"${transcript}"?`);
  2964. break;
  2965. }
  2966. typeof console == "object" && console.log(e.results);
  2967. typeof console == "object" && console.log(`transcript:${transcript} confidence:${e.results[0][0].confidence}`);
  2968. };
  2969. }
  2970.  
  2971. substitudeFullscreenPlayer(option) {
  2972. // 1. check param
  2973. if (!option) throw 'usage: substitudeFullscreenPlayer({cid, aid[, p][, ...otherOptions]})';
  2974. if (!option.cid) throw 'player init: cid missing';
  2975. if (!option.aid) throw 'player init: aid missing';
  2976.  
  2977. // 2. hook exitFullscreen
  2978. const playerDoc = this.playerWin.document;
  2979. const hook = [playerDoc.webkitExitFullscreen, playerDoc.mozExitFullScreen, playerDoc.msExitFullscreen, playerDoc.exitFullscreen];
  2980. playerDoc.webkitExitFullscreen = playerDoc.mozExitFullScreen = playerDoc.msExitFullscreen = playerDoc.exitFullscreen = () => { };
  2981.  
  2982. // 3. substitude player
  2983. this.playerWin.player.destroy();
  2984. this.playerWin.player = new bilibiliPlayer(option);
  2985. if (option.p) this.playerWin.callAppointPart(option.p);
  2986.  
  2987. // 4. restore exitFullscreen
  2988. [playerDoc.webkitExitFullscreen, playerDoc.mozExitFullScreen, playerDoc.msExitFullscreen, playerDoc.exitFullscreen] = hook;
  2989. }
  2990.  
  2991. async getPlayerVideo() {
  2992. if (this.playerWin.document.getElementsByTagName('video').length) {
  2993. return this.video = this.playerWin.document.getElementsByTagName('video')[0];
  2994. }
  2995. else {
  2996. return new Promise(resolve => {
  2997. const observer = new MutationObserver(() => {
  2998. if (this.playerWin.document.getElementsByTagName('video').length) {
  2999. observer.disconnect();
  3000. resolve(this.video = this.playerWin.document.getElementsByTagName('video')[0]);
  3001. }
  3002. });
  3003. observer.observe(this.playerWin.document.getElementById('bilibiliPlayer'), { childList: true });
  3004. });
  3005. }
  3006. }
  3007.  
  3008. async getPlayerMenu() {
  3009. if (this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black').length) {
  3010. return this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black')[0];
  3011. }
  3012. else {
  3013. return new Promise(resolve => {
  3014. const observer = new MutationObserver(() => {
  3015. if (this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black').length) {
  3016. observer.disconnect();
  3017. resolve(this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black')[0]);
  3018. }
  3019. });
  3020. observer.observe(this.playerWin.document.getElementById('bilibiliPlayer'), { childList: true });
  3021. });
  3022. }
  3023. }
  3024.  
  3025. async getWatchLaterBtn() {
  3026. let 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]');
  3027.  
  3028. if (!document.cookie.includes("DedeUserID")) return; // 未登录(不可用)
  3029.  
  3030. if (!li) {
  3031. return new Promise(resolve => {
  3032. const observer = new MutationObserver(() => {
  3033. 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]');
  3034. if (li) {
  3035. observer.disconnect();
  3036. resolve(li);
  3037. }
  3038. });
  3039. observer.observe(this.playerWin.document.getElementById('bilibiliPlayer'), { childList: true });
  3040. });
  3041. }
  3042. }
  3043.  
  3044. async getWideScreenBtn() {
  3045. let li = top.document.querySelector('.bilibili-player-video-btn-widescreen');
  3046.  
  3047. if (!li) {
  3048. return new Promise(resolve => {
  3049. const observer = new MutationObserver(() => {
  3050. li = top.document.querySelector('.bilibili-player-video-btn-widescreen');
  3051. if (li) {
  3052. observer.disconnect();
  3053. resolve(li);
  3054. }
  3055. });
  3056. observer.observe(this.playerWin.document.getElementById('bilibiliPlayer'), { childList: true });
  3057. });
  3058. }
  3059. }
  3060.  
  3061. static async openMinimizedPlayer(option = { cid: top.cid, aid: top.aid, playerWin: top }) {
  3062. // 1. check param
  3063. if (!option) throw 'usage: openMinimizedPlayer({cid[, aid]})';
  3064. if (!option.cid) throw 'player init: cid missing';
  3065. if (!option.aid) option.aid = top.aid;
  3066. if (!option.playerWin) option.playerWin = top;
  3067.  
  3068. // 2. open a new window
  3069. 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, ' ');
  3070.  
  3071. // 3. bangumi => request referrer must match => hook response of current page
  3072. const res = top.location.href.includes('bangumi') && await new Promise(resolve => {
  3073. const jq = option.playerWin.jQuery;
  3074. const _ajax = jq.ajax;
  3075.  
  3076. jq.ajax = function (a, c) {
  3077. 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?')) {
  3078. a.success = resolve;
  3079. jq.ajax = _ajax;
  3080. }
  3081. return _ajax.call(jq, a, c);
  3082. };
  3083. option.playerWin.player.reloadAccess();
  3084. });
  3085.  
  3086. // 4. wait for miniPlayerWin load
  3087. await new Promise(resolve => {
  3088. // 4.1 check for every500ms
  3089. const i = setInterval(() => miniPlayerWin.document.getElementById('bilibiliPlayer') && resolve(), 500);
  3090.  
  3091. // 4.2 explict event listener
  3092. miniPlayerWin.addEventListener('load', resolve, { once: true });
  3093.  
  3094. // 4.3 timeout after 6s
  3095. setTimeout(() => {
  3096. clearInterval(i);
  3097. miniPlayerWin.removeEventListener('load', resolve);
  3098. resolve();
  3099. }, 6000);
  3100. });
  3101. // 4.4 cannot find bilibiliPlayer => load timeout
  3102. const playerDiv = miniPlayerWin.document.getElementById('bilibiliPlayer');
  3103. if (!playerDiv) { console.warn('openMinimizedPlayer: document load timeout'); return; }
  3104.  
  3105. // 5. need to inject response => new bilibiliPlayer
  3106. if (res) {
  3107. await new Promise(resolve => {
  3108. const jq = miniPlayerWin.jQuery;
  3109. const _ajax = jq.ajax;
  3110.  
  3111. jq.ajax = function (a, c) {
  3112. 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?')) {
  3113. a.success(res);
  3114. jq.ajax = _ajax;
  3115. resolve();
  3116. }
  3117. else {
  3118. return _ajax.call(jq, a, c);
  3119. }
  3120. };
  3121. miniPlayerWin.player = new miniPlayerWin.bilibiliPlayer({ cid: option.cid, aid: option.aid });
  3122. // miniPlayerWin.eval(`player = new bilibiliPlayer({ cid: ${option.cid}, aid: ${option.aid} })`);
  3123. // console.log(`player = new bilibiliPlayer({ cid: ${option.cid}, aid: ${option.aid} })`);
  3124. });
  3125. }
  3126.  
  3127. // 6. wait for bilibiliPlayer load
  3128. await new Promise(resolve => {
  3129. if (miniPlayerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen')) resolve();
  3130. else {
  3131. const observer = new MutationObserver(() => {
  3132. if (miniPlayerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen')) {
  3133. observer.disconnect();
  3134. resolve();
  3135. }
  3136. });
  3137. observer.observe(playerDiv, { childList: true });
  3138. }
  3139. });
  3140.  
  3141. // 7. adopt full screen player style withour really trigger full screen
  3142. // 7.1 hook requestFullscreen
  3143. const hook = [playerDiv.webkitRequestFullscreen, playerDiv.mozRequestFullScreen, playerDiv.msRequestFullscreen, playerDiv.requestFullscreen];
  3144. playerDiv.webkitRequestFullscreen = playerDiv.mozRequestFullScreen = playerDiv.msRequestFullscreen = playerDiv.requestFullscreen = () => { };
  3145.  
  3146. // 7.2 adopt full screen player style
  3147. if (miniPlayerWin.document.querySelector('#bilibiliPlayer div.video-state-fullscreen-off'))
  3148. miniPlayerWin.document.querySelector('#bilibiliPlayer div.bilibili-player-video-btn-fullscreen').click();
  3149.  
  3150. // 7.3 restore requestFullscreen
  3151. [playerDiv.webkitRequestFullscreen, playerDiv.mozRequestFullScreen, playerDiv.msRequestFullscreen, playerDiv.requestFullscreen] = hook;
  3152. }
  3153.  
  3154. static async biligameInit() {
  3155. const game_id = location.href.match(/id=(\d+)/)[1];
  3156. const api_url = `https://line1-h5-pc-api.biligame.com/game/detail/gameinfo?game_base_id=${game_id}`;
  3157.  
  3158. const req = await fetch(api_url, { credentials: 'include' });
  3159. const data = (await req.json()).data;
  3160.  
  3161. const aid = data.video_url;
  3162. const video_url = `https://www.bilibili.com/video/av${aid}`;
  3163.  
  3164. const tabs = document.querySelector(".tab-head");
  3165. const tab = document.createElement("a");
  3166. tab.href = video_url;
  3167. tab.textContent = "查看视频";
  3168. tab.target = "_blank";
  3169. tabs.appendChild(tab);
  3170. }
  3171.  
  3172. static showBangumiCoverImage() {
  3173. const imgElement = document.querySelector(".media-preview img");
  3174. if (!imgElement) return;
  3175.  
  3176. imgElement.style.cursor = "pointer";
  3177.  
  3178. imgElement.onclick = () => {
  3179. const cover_img = imgElement.src.match(/.+?\.(png|jpg)/)[0];
  3180. top.window.open(cover_img, '_blank');
  3181. };
  3182. }
  3183.  
  3184. static secondToReadable(s) {
  3185. if (s > 60) return `${parseInt(s / 60)}分${parseInt(s % 60)}秒`;
  3186. else return `${parseInt(s % 60)}秒`;
  3187. }
  3188.  
  3189. static clearAllUserdata(playerWin = top) {
  3190. if (playerWin.GM_setValue) return GM_setValue('biliPolyfill', '');
  3191. if (playerWin.GM.setValue) return GM.setValue('biliPolyfill', '');
  3192. playerWin.localStorage.removeItem('biliPolyfill');
  3193. }
  3194.  
  3195. static get optionDescriptions() {
  3196. return [
  3197. ['betabeta', '增强组件总开关 <---------更加懒得测试了,反正以后B站也会自己提供这些功能。也许吧。'],
  3198.  
  3199. // 1. user interface
  3200. ['badgeWatchLater', '稍后再看添加数字角标'],
  3201. ['recommend', '弹幕列表换成相关视频'],
  3202. ['electric', '整合充电榜与换P倒计时'],
  3203. ['electricSkippable', '跳过充电榜', 'disabled'],
  3204.  
  3205. // 2. automation
  3206. ['scroll', '自动滚动到播放器'],
  3207. ['focus', '自动聚焦到播放器(新页面直接按空格会播放而不是向下滚动)'],
  3208. ['menuFocus', '关闭菜单后聚焦到播放器'],
  3209. ['restorePrevent', '记住防挡字幕'],
  3210. ['restoreDanmuku', '记住弹幕开关(顶端/底端/滚动/全部)'],
  3211. ['restoreSpeed', '记住播放速度'],
  3212. ['restoreWide', '记住宽屏'],
  3213. ['autoResume', '自动跳转上次看到'],
  3214. ['autoPlay', '自动播放(需要在浏览器站点权限设置中允许自动播放)'],
  3215. ['autoFullScreen', '自动全屏'],
  3216. ['oped', '标记后自动跳OP/ED'],
  3217. ['series', '尝试自动找上下集'],
  3218.  
  3219. // 3. interaction
  3220. ['limitedKeydown', '首次回车键可全屏自动播放(需要在脚本加载完毕后使用)'],
  3221. ['dblclick', '双击全屏'],
  3222.  
  3223. // 4. easter eggs
  3224. ['speech', '(彩蛋)(需墙外)任意三击鼠标左键开启语音识别'],
  3225. ];
  3226. }
  3227.  
  3228. static get optionDefaults() {
  3229. return {
  3230. betabeta: false,
  3231.  
  3232. // 1. user interface
  3233. badgeWatchLater: true,
  3234. recommend: true,
  3235. electric: true,
  3236. electricSkippable: false,
  3237.  
  3238. // 2. automation
  3239. scroll: true,
  3240. focus: false,
  3241. menuFocus: true,
  3242. restorePrevent: false,
  3243. restoreDanmuku: false,
  3244. restoreSpeed: true,
  3245. restoreWide: true,
  3246. autoResume: true,
  3247. autoPlay: false,
  3248. autoFullScreen: false,
  3249. oped: true,
  3250. series: true,
  3251.  
  3252. // 3. interaction
  3253. limitedKeydown: true,
  3254. dblclick: true,
  3255.  
  3256. // 4. easter eggs
  3257. speech: false,
  3258. }
  3259. }
  3260.  
  3261. static _UNIT_TEST() {
  3262. console.warn('This test is impossible.');
  3263. console.warn('You need to close the tab, reopen it, etc.');
  3264. console.warn('Maybe you also want to test between bideo parts, etc.');
  3265. console.warn('I am too lazy to find workarounds.');
  3266. }
  3267. }
  3268.  
  3269. /***
  3270. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3271. *
  3272. * @author qli5 <goodlq11[at](163|gmail).com>
  3273. *
  3274. * This Source Code Form is subject to the terms of the Mozilla Public
  3275. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3276. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3277. */
  3278.  
  3279. class Exporter {
  3280. static exportIDM(urls, referrer = top.location.origin) {
  3281. return urls.map(url => `<\r\n${url}\r\nreferer: ${referrer}\r\n>\r\n`).join('');
  3282. }
  3283.  
  3284. static exportM3U8(urls, referrer = top.location.origin, userAgent = top.navigator.userAgent) {
  3285. return '#EXTM3U\n' + urls.map(url => `#EXTVLCOPT:http-referrer=${referrer}\n#EXTVLCOPT:http-user-agent=${userAgent}\n#EXTINF:-1\n${url}\n`).join('');
  3286. }
  3287.  
  3288. static exportAria2(urls, referrer = top.location.origin) {
  3289. return urls.map(url => `${url}\r\n referer=${referrer}\r\n`).join('');
  3290. }
  3291.  
  3292. static async sendToAria2RPC(urls, referrer = top.location.origin, target = 'http://127.0.0.1:6800/jsonrpc') {
  3293. const h = 'referer';
  3294. const method = 'POST';
  3295.  
  3296. while (1) {
  3297. const token_array = target.match(/\/\/((.+)@)/);
  3298. const body = JSON.stringify(urls.map((url, id) => {
  3299. const params = [
  3300. [url],
  3301. { [h]: referrer }
  3302. ];
  3303.  
  3304. if (token_array) {
  3305. params.unshift(token_array[2]);
  3306. target = target.replace(token_array[1], "");
  3307. }
  3308.  
  3309. return ({
  3310. id,
  3311. jsonrpc: 2,
  3312. method: "aria2.addUri",
  3313. params
  3314. })
  3315. }));
  3316.  
  3317. try {
  3318. const res = await (await fetch(target, { method, body })).json();
  3319. if (res.error || res[0].error) {
  3320. throw new Error((res.error || res[0].error).message)
  3321. }
  3322. else {
  3323. return res;
  3324. }
  3325. }
  3326. catch (e) {
  3327. target = top.prompt(`Aria2 connection failed${!e.message.includes("fetch") ? `: ${e.message}.\n` : ". "}Please provide a valid server address:`, target);
  3328. if (!target) return null;
  3329. }
  3330. }
  3331. }
  3332.  
  3333. static copyToClipboard(text) {
  3334. const textarea = document.createElement('textarea');
  3335. document.body.appendChild(textarea);
  3336. textarea.value = text;
  3337. textarea.select();
  3338. document.execCommand('copy');
  3339. document.body.removeChild(textarea);
  3340. }
  3341. }
  3342.  
  3343. /***
  3344. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3345. *
  3346. * @author qli5 <goodlq11[at](163|gmail).com>
  3347. *
  3348. * This Source Code Form is subject to the terms of the Mozilla Public
  3349. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3350. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3351. */
  3352.  
  3353. class TwentyFourDataView extends DataView {
  3354. getUint24(byteOffset, littleEndian) {
  3355. if (littleEndian) throw 'littleEndian int24 not implemented';
  3356. return this.getUint32(byteOffset - 1) & 0x00FFFFFF;
  3357. }
  3358.  
  3359. setUint24(byteOffset, value, littleEndian) {
  3360. if (littleEndian) throw 'littleEndian int24 not implemented';
  3361. if (value > 0x00FFFFFF) throw 'setUint24: number out of range';
  3362. let msb = value >> 16;
  3363. let lsb = value & 0xFFFF;
  3364. this.setUint8(byteOffset, msb);
  3365. this.setUint16(byteOffset + 1, lsb);
  3366. }
  3367.  
  3368. indexOf(search, startOffset = 0, endOffset = this.byteLength - search.length + 1) {
  3369. // I know it is NAIVE
  3370. if (search.charCodeAt) {
  3371. for (let i = startOffset; i < endOffset; i++) {
  3372. if (this.getUint8(i) != search.charCodeAt(0)) continue;
  3373. let found = 1;
  3374. for (let j = 0; j < search.length; j++) {
  3375. if (this.getUint8(i + j) != search.charCodeAt(j)) {
  3376. found = 0;
  3377. break;
  3378. }
  3379. }
  3380. if (found) return i;
  3381. }
  3382. return -1;
  3383. }
  3384. else {
  3385. for (let i = startOffset; i < endOffset; i++) {
  3386. if (this.getUint8(i) != search[0]) continue;
  3387. let found = 1;
  3388. for (let j = 0; j < search.length; j++) {
  3389. if (this.getUint8(i + j) != search[j]) {
  3390. found = 0;
  3391. break;
  3392. }
  3393. }
  3394. if (found) return i;
  3395. }
  3396. return -1;
  3397. }
  3398. }
  3399. }
  3400.  
  3401. /***
  3402. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3403. *
  3404. * @author qli5 <goodlq11[at](163|gmail).com>
  3405. *
  3406. * This Source Code Form is subject to the terms of the Mozilla Public
  3407. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3408. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3409. */
  3410.  
  3411. class FLVTag {
  3412. constructor(dataView, currentOffset = 0) {
  3413. this.tagHeader = new TwentyFourDataView(dataView.buffer, dataView.byteOffset + currentOffset, 11);
  3414. this.tagData = new TwentyFourDataView(dataView.buffer, dataView.byteOffset + currentOffset + 11, this.dataSize);
  3415. this.previousSize = new TwentyFourDataView(dataView.buffer, dataView.byteOffset + currentOffset + 11 + this.dataSize, 4);
  3416. }
  3417.  
  3418. get tagType() {
  3419. return this.tagHeader.getUint8(0);
  3420. }
  3421.  
  3422. get dataSize() {
  3423. return this.tagHeader.getUint24(1);
  3424. }
  3425.  
  3426. get timestamp() {
  3427. return this.tagHeader.getUint24(4);
  3428. }
  3429.  
  3430. get timestampExtension() {
  3431. return this.tagHeader.getUint8(7);
  3432. }
  3433.  
  3434. get streamID() {
  3435. return this.tagHeader.getUint24(8);
  3436. }
  3437.  
  3438. stripKeyframesScriptData() {
  3439. let hasKeyframes = 'hasKeyframes\x01';
  3440. if (this.tagType != 0x12) throw 'can not strip non-scriptdata\'s keyframes';
  3441.  
  3442. let index;
  3443. index = this.tagData.indexOf(hasKeyframes);
  3444. if (index != -1) {
  3445. //0x0101 => 0x0100
  3446. this.tagData.setUint8(index + hasKeyframes.length, 0x00);
  3447. }
  3448.  
  3449. // Well, I think it is unnecessary
  3450. /*index = this.tagData.indexOf(keyframes)
  3451. if (index != -1) {
  3452. this.dataSize = index;
  3453. this.tagHeader.setUint24(1, index);
  3454. this.tagData = new TwentyFourDataView(this.tagData.buffer, this.tagData.byteOffset, index);
  3455. }*/
  3456. }
  3457.  
  3458. getDuration() {
  3459. if (this.tagType != 0x12) throw 'can not find non-scriptdata\'s duration';
  3460.  
  3461. let duration = 'duration\x00';
  3462. let index = this.tagData.indexOf(duration);
  3463. if (index == -1) throw 'can not get flv meta duration';
  3464.  
  3465. index += 9;
  3466. return this.tagData.getFloat64(index);
  3467. }
  3468.  
  3469. getDurationAndView() {
  3470. if (this.tagType != 0x12) throw 'can not find non-scriptdata\'s duration';
  3471.  
  3472. let duration = 'duration\x00';
  3473. let index = this.tagData.indexOf(duration);
  3474. if (index == -1) throw 'can not get flv meta duration';
  3475.  
  3476. index += 9;
  3477. return {
  3478. duration: this.tagData.getFloat64(index),
  3479. durationDataView: new TwentyFourDataView(this.tagData.buffer, this.tagData.byteOffset + index, 8)
  3480. };
  3481. }
  3482.  
  3483. getCombinedTimestamp() {
  3484. return (this.timestampExtension << 24 | this.timestamp);
  3485. }
  3486.  
  3487. setCombinedTimestamp(timestamp) {
  3488. if (timestamp < 0) throw 'timestamp < 0';
  3489. this.tagHeader.setUint8(7, timestamp >> 24);
  3490. this.tagHeader.setUint24(4, timestamp & 0x00FFFFFF);
  3491. }
  3492. }
  3493.  
  3494. /***
  3495. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3496. *
  3497. * @author qli5 <goodlq11[at](163|gmail).com>
  3498. *
  3499. * This Source Code Form is subject to the terms of the Mozilla Public
  3500. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3501. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3502. *
  3503. * The FLV merge utility is a Javascript translation of
  3504. * https://github.com/grepmusic/flvmerge
  3505. * by grepmusic
  3506. */
  3507.  
  3508. /**
  3509. * A simple flv parser
  3510. */
  3511. class FLV {
  3512. constructor(dataView) {
  3513. if (dataView.indexOf('FLV', 0, 1) != 0) throw 'Invalid FLV header';
  3514. this.header = new TwentyFourDataView(dataView.buffer, dataView.byteOffset, 9);
  3515. this.firstPreviousTagSize = new TwentyFourDataView(dataView.buffer, dataView.byteOffset + 9, 4);
  3516.  
  3517. this.tags = [];
  3518. let offset = this.headerLength + 4;
  3519. while (offset < dataView.byteLength) {
  3520. let tag = new FLVTag(dataView, offset);
  3521. // debug for script data tag
  3522. // if (tag.tagType != 0x08 && tag.tagType != 0x09)
  3523. offset += 11 + tag.dataSize + 4;
  3524. this.tags.push(tag);
  3525. }
  3526.  
  3527. if (offset != dataView.byteLength) throw 'FLV unexpected end of file';
  3528. }
  3529.  
  3530. get type() {
  3531. return 'FLV';
  3532. }
  3533.  
  3534. get version() {
  3535. return this.header.getUint8(3);
  3536. }
  3537.  
  3538. get typeFlag() {
  3539. return this.header.getUint8(4);
  3540. }
  3541.  
  3542. get headerLength() {
  3543. return this.header.getUint32(5);
  3544. }
  3545.  
  3546. static merge(flvs) {
  3547. if (flvs.length < 1) throw 'Usage: FLV.merge([flvs])';
  3548. let blobParts = [];
  3549. let basetimestamp = [0, 0];
  3550. let lasttimestamp = [0, 0];
  3551. let duration = 0.0;
  3552. let durationDataView;
  3553.  
  3554. blobParts.push(flvs[0].header);
  3555. blobParts.push(flvs[0].firstPreviousTagSize);
  3556.  
  3557. for (let flv of flvs) {
  3558. let bts = duration * 1000;
  3559. basetimestamp[0] = lasttimestamp[0];
  3560. basetimestamp[1] = lasttimestamp[1];
  3561. bts = Math.max(bts, basetimestamp[0], basetimestamp[1]);
  3562. let foundDuration = 0;
  3563. for (let tag of flv.tags) {
  3564. if (tag.tagType == 0x12 && !foundDuration) {
  3565. duration += tag.getDuration();
  3566. foundDuration = 1;
  3567. if (flv == flvs[0]) {
  3568. ({ duration, durationDataView } = tag.getDurationAndView());
  3569. tag.stripKeyframesScriptData();
  3570. blobParts.push(tag.tagHeader);
  3571. blobParts.push(tag.tagData);
  3572. blobParts.push(tag.previousSize);
  3573. }
  3574. }
  3575. else if (tag.tagType == 0x08 || tag.tagType == 0x09) {
  3576. lasttimestamp[tag.tagType - 0x08] = bts + tag.getCombinedTimestamp();
  3577. tag.setCombinedTimestamp(lasttimestamp[tag.tagType - 0x08]);
  3578. blobParts.push(tag.tagHeader);
  3579. blobParts.push(tag.tagData);
  3580. blobParts.push(tag.previousSize);
  3581. }
  3582. }
  3583. }
  3584. durationDataView.setFloat64(0, duration);
  3585.  
  3586. return new Blob(blobParts);
  3587. }
  3588.  
  3589. static async mergeBlobs(blobs) {
  3590. // Blobs can be swapped to disk, while Arraybuffers can not.
  3591. // This is a RAM saving workaround. Somewhat.
  3592. if (blobs.length < 1) throw 'Usage: FLV.mergeBlobs([blobs])';
  3593. let ret = [];
  3594. let basetimestamp = [0, 0];
  3595. let lasttimestamp = [0, 0];
  3596. let duration = 0.0;
  3597. let durationDataView;
  3598.  
  3599. for (let blob of blobs) {
  3600. let bts = duration * 1000;
  3601. basetimestamp[0] = lasttimestamp[0];
  3602. basetimestamp[1] = lasttimestamp[1];
  3603. bts = Math.max(bts, basetimestamp[0], basetimestamp[1]);
  3604. let foundDuration = 0;
  3605.  
  3606. let flv = await new Promise((resolve, reject) => {
  3607. let fr = new FileReader();
  3608. fr.onload = () => resolve(new FLV(new TwentyFourDataView(fr.result)));
  3609. fr.readAsArrayBuffer(blob);
  3610. fr.onerror = reject;
  3611. });
  3612.  
  3613. let modifiedMediaTags = [];
  3614. for (let tag of flv.tags) {
  3615. if (tag.tagType == 0x12 && !foundDuration) {
  3616. duration += tag.getDuration();
  3617. foundDuration = 1;
  3618. if (blob == blobs[0]) {
  3619. ret.push(flv.header, flv.firstPreviousTagSize);
  3620. ({ duration, durationDataView } = tag.getDurationAndView());
  3621. tag.stripKeyframesScriptData();
  3622. ret.push(tag.tagHeader);
  3623. ret.push(tag.tagData);
  3624. ret.push(tag.previousSize);
  3625. }
  3626. }
  3627. else if (tag.tagType == 0x08 || tag.tagType == 0x09) {
  3628. lasttimestamp[tag.tagType - 0x08] = bts + tag.getCombinedTimestamp();
  3629. tag.setCombinedTimestamp(lasttimestamp[tag.tagType - 0x08]);
  3630. modifiedMediaTags.push(tag.tagHeader, tag.tagData, tag.previousSize);
  3631. }
  3632. }
  3633. ret.push(new Blob(modifiedMediaTags));
  3634. }
  3635. durationDataView.setFloat64(0, duration);
  3636.  
  3637. return new Blob(ret);
  3638. }
  3639. }
  3640.  
  3641. var embeddedHTML = `<html>
  3642.  
  3643. <body>
  3644. <p>
  3645. 加载文件…… loading files...
  3646. <progress value="0" max="100" id="fileProgress"></progress>
  3647. </p>
  3648. <p>
  3649. 构建mkv…… building mkv...
  3650. <progress value="0" max="100" id="mkvProgress"></progress>
  3651. </p>
  3652. <p>
  3653. <a id="a" download="merged.mkv">merged.mkv</a>
  3654. </p>
  3655. <footer>
  3656. author qli5 &lt;goodlq11[at](163|gmail).com&gt;
  3657. </footer>
  3658. <script>
  3659. var FLVASS2MKV = (function () {
  3660. 'use strict';
  3661.  
  3662. /***
  3663. * Copyright (C) 2018 Qli5. All Rights Reserved.
  3664. *
  3665. * @author qli5 <goodlq11[at](163|gmail).com>
  3666. *
  3667. * This Source Code Form is subject to the terms of the Mozilla Public
  3668. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3669. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  3670. */
  3671.  
  3672. const _navigator = typeof navigator === 'object' && navigator || { userAgent: 'chrome' };
  3673.  
  3674. /** @type {typeof Blob} */
  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 {boolean} probeData.hasAudioTrack
  4512. * @param {boolean} probeData.hasVideoTrack
  4513. */
  4514. constructor(probeData) {
  4515. this.TAG = 'FLVDemuxer';
  4516.  
  4517. this._onError = null;
  4518. this._onMediaInfo = null;
  4519. this._onTrackMetadata = null;
  4520. this._onDataAvailable = null;
  4521.  
  4522. this._dataOffset = probeData.dataOffset;
  4523. this._firstParse = true;
  4524. this._dispatch = false;
  4525.  
  4526. this._hasAudio = probeData.hasAudioTrack;
  4527. this._hasVideo = probeData.hasVideoTrack;
  4528.  
  4529. this._hasAudioFlagOverrided = false;
  4530. this._hasVideoFlagOverrided = false;
  4531.  
  4532. this._audioInitialMetadataDispatched = false;
  4533. this._videoInitialMetadataDispatched = false;
  4534.  
  4535. this._mediaInfo = new MediaInfo();
  4536. this._mediaInfo.hasAudio = this._hasAudio;
  4537. this._mediaInfo.hasVideo = this._hasVideo;
  4538. this._metadata = null;
  4539. this._audioMetadata = null;
  4540. this._videoMetadata = null;
  4541.  
  4542. this._naluLengthSize = 4;
  4543. this._timestampBase = 0; // int32, in milliseconds
  4544. this._timescale = 1000;
  4545. this._duration = 0; // int32, in milliseconds
  4546. this._durationOverrided = false;
  4547. this._referenceFrameRate = {
  4548. fixed: true,
  4549. fps: 23.976,
  4550. fps_num: 23976,
  4551. fps_den: 1000
  4552. };
  4553.  
  4554. this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48000];
  4555.  
  4556. this._mpegSamplingRates = [
  4557. 96000, 88200, 64000, 48000, 44100, 32000,
  4558. 24000, 22050, 16000, 12000, 11025, 8000, 7350
  4559. ];
  4560.  
  4561. this._mpegAudioV10SampleRateTable = [44100, 48000, 32000, 0];
  4562. this._mpegAudioV20SampleRateTable = [22050, 24000, 16000, 0];
  4563. this._mpegAudioV25SampleRateTable = [11025, 12000, 8000, 0];
  4564.  
  4565. this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1];
  4566. this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1];
  4567. this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1];
  4568.  
  4569. this._videoTrack = { type: 'video', id: 1, sequenceNumber: 0, samples: [], length: 0 };
  4570. this._audioTrack = { type: 'audio', id: 2, sequenceNumber: 0, samples: [], length: 0 };
  4571.  
  4572. this._littleEndian = (function () {
  4573. let buf = new ArrayBuffer(2);
  4574. (new DataView(buf)).setInt16(0, 256, true); // little-endian write
  4575. return (new Int16Array(buf))[0] === 256; // platform-spec read, if equal then LE
  4576. })();
  4577. }
  4578.  
  4579. destroy() {
  4580. this._mediaInfo = null;
  4581. this._metadata = null;
  4582. this._audioMetadata = null;
  4583. this._videoMetadata = null;
  4584. this._videoTrack = null;
  4585. this._audioTrack = null;
  4586.  
  4587. this._onError = null;
  4588. this._onMediaInfo = null;
  4589. this._onTrackMetadata = null;
  4590. this._onDataAvailable = null;
  4591. }
  4592.  
  4593. /**
  4594. * Probe the flv data
  4595. * @param {ArrayBuffer} buffer
  4596. * @returns {Object} - probeData to be feed into constructor
  4597. */
  4598. static probe(buffer) {
  4599. let data = new Uint8Array(buffer);
  4600. let mismatch = { match: false };
  4601.  
  4602. if (data[0] !== 0x46 || data[1] !== 0x4C || data[2] !== 0x56 || data[3] !== 0x01) {
  4603. return mismatch;
  4604. }
  4605.  
  4606. let hasAudio = ((data[4] & 4) >>> 2) !== 0;
  4607. let hasVideo = (data[4] & 1) !== 0;
  4608.  
  4609. let offset = ReadBig32(data, 5);
  4610.  
  4611. if (offset < 9) {
  4612. return mismatch;
  4613. }
  4614.  
  4615. return {
  4616. match: true,
  4617. consumed: offset,
  4618. dataOffset: offset,
  4619. hasAudioTrack: hasAudio,
  4620. hasVideoTrack: hasVideo
  4621. };
  4622. }
  4623.  
  4624. bindDataSource(loader) {
  4625. loader.onDataArrival = this.parseChunks.bind(this);
  4626. return this;
  4627. }
  4628.  
  4629. // prototype: function(type: string, metadata: any): void
  4630. get onTrackMetadata() {
  4631. return this._onTrackMetadata;
  4632. }
  4633.  
  4634. set onTrackMetadata(callback) {
  4635. this._onTrackMetadata = callback;
  4636. }
  4637.  
  4638. // prototype: function(mediaInfo: MediaInfo): void
  4639. get onMediaInfo() {
  4640. return this._onMediaInfo;
  4641. }
  4642.  
  4643. set onMediaInfo(callback) {
  4644. this._onMediaInfo = callback;
  4645. }
  4646.  
  4647. // prototype: function(type: number, info: string): void
  4648. get onError() {
  4649. return this._onError;
  4650. }
  4651.  
  4652. set onError(callback) {
  4653. this._onError = callback;
  4654. }
  4655.  
  4656. // prototype: function(videoTrack: any, audioTrack: any): void
  4657. get onDataAvailable() {
  4658. return this._onDataAvailable;
  4659. }
  4660.  
  4661. set onDataAvailable(callback) {
  4662. this._onDataAvailable = callback;
  4663. }
  4664.  
  4665. // timestamp base for output samples, must be in milliseconds
  4666. get timestampBase() {
  4667. return this._timestampBase;
  4668. }
  4669.  
  4670. set timestampBase(base) {
  4671. this._timestampBase = base;
  4672. }
  4673.  
  4674. get overridedDuration() {
  4675. return this._duration;
  4676. }
  4677.  
  4678. // Force-override media duration. Must be in milliseconds, int32
  4679. set overridedDuration(duration) {
  4680. this._durationOverrided = true;
  4681. this._duration = duration;
  4682. this._mediaInfo.duration = duration;
  4683. }
  4684.  
  4685. // Force-override audio track present flag, boolean
  4686. set overridedHasAudio(hasAudio) {
  4687. this._hasAudioFlagOverrided = true;
  4688. this._hasAudio = hasAudio;
  4689. this._mediaInfo.hasAudio = hasAudio;
  4690. }
  4691.  
  4692. // Force-override video track present flag, boolean
  4693. set overridedHasVideo(hasVideo) {
  4694. this._hasVideoFlagOverrided = true;
  4695. this._hasVideo = hasVideo;
  4696. this._mediaInfo.hasVideo = hasVideo;
  4697. }
  4698.  
  4699. resetMediaInfo() {
  4700. this._mediaInfo = new MediaInfo();
  4701. }
  4702.  
  4703. _isInitialMetadataDispatched() {
  4704. if (this._hasAudio && this._hasVideo) { // both audio & video
  4705. return this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched;
  4706. }
  4707. if (this._hasAudio && !this._hasVideo) { // audio only
  4708. return this._audioInitialMetadataDispatched;
  4709. }
  4710. if (!this._hasAudio && this._hasVideo) { // video only
  4711. return this._videoInitialMetadataDispatched;
  4712. }
  4713. return false;
  4714. }
  4715.  
  4716. // function parseChunks(chunk: ArrayBuffer, byteStart: number): number;
  4717. parseChunks(chunk, byteStart) {
  4718. if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) {
  4719. throw new IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');
  4720. }
  4721.  
  4722. // qli5: fix nonzero byteStart
  4723. let offset = byteStart || 0;
  4724. let le = this._littleEndian;
  4725.  
  4726. if (byteStart === 0) { // buffer with FLV header
  4727. if (chunk.byteLength > 13) {
  4728. let probeData = FLVDemuxer.probe(chunk);
  4729. offset = probeData.dataOffset;
  4730. } else {
  4731. return 0;
  4732. }
  4733. }
  4734.  
  4735. if (this._firstParse) { // handle PreviousTagSize0 before Tag1
  4736. this._firstParse = false;
  4737. if (offset !== this._dataOffset) {
  4738. Log.w(this.TAG, 'First time parsing but chunk byteStart invalid!');
  4739. }
  4740.  
  4741. let v = new DataView(chunk, offset);
  4742. let prevTagSize0 = v.getUint32(0, !le);
  4743. if (prevTagSize0 !== 0) {
  4744. Log.w(this.TAG, 'PrevTagSize0 !== 0 !!!');
  4745. }
  4746. offset += 4;
  4747. }
  4748.  
  4749. while (offset < chunk.byteLength) {
  4750. this._dispatch = true;
  4751.  
  4752. let v = new DataView(chunk, offset);
  4753.  
  4754. if (offset + 11 + 4 > chunk.byteLength) {
  4755. // data not enough for parsing an flv tag
  4756. break;
  4757. }
  4758.  
  4759. let tagType = v.getUint8(0);
  4760. let dataSize = v.getUint32(0, !le) & 0x00FFFFFF;
  4761.  
  4762. if (offset + 11 + dataSize + 4 > chunk.byteLength) {
  4763. // data not enough for parsing actual data body
  4764. break;
  4765. }
  4766.  
  4767. if (tagType !== 8 && tagType !== 9 && tagType !== 18) {
  4768. Log.w(this.TAG, \`Unsupported tag type \${tagType}, skipped\`);
  4769. // consume the whole tag (skip it)
  4770. offset += 11 + dataSize + 4;
  4771. continue;
  4772. }
  4773.  
  4774. let ts2 = v.getUint8(4);
  4775. let ts1 = v.getUint8(5);
  4776. let ts0 = v.getUint8(6);
  4777. let ts3 = v.getUint8(7);
  4778.  
  4779. let timestamp = ts0 | (ts1 << 8) | (ts2 << 16) | (ts3 << 24);
  4780.  
  4781. let streamId = v.getUint32(7, !le) & 0x00FFFFFF;
  4782. if (streamId !== 0) {
  4783. Log.w(this.TAG, 'Meet tag which has StreamID != 0!');
  4784. }
  4785.  
  4786. let dataOffset = offset + 11;
  4787.  
  4788. switch (tagType) {
  4789. case 8: // Audio
  4790. this._parseAudioData(chunk, dataOffset, dataSize, timestamp);
  4791. break;
  4792. case 9: // Video
  4793. this._parseVideoData(chunk, dataOffset, dataSize, timestamp, byteStart + offset);
  4794. break;
  4795. case 18: // ScriptDataObject
  4796. this._parseScriptData(chunk, dataOffset, dataSize);
  4797. break;
  4798. }
  4799.  
  4800. let prevTagSize = v.getUint32(11 + dataSize, !le);
  4801. if (prevTagSize !== 11 + dataSize) {
  4802. Log.w(this.TAG, \`Invalid PrevTagSize \${prevTagSize}\`);
  4803. }
  4804.  
  4805. offset += 11 + dataSize + 4; // tagBody + dataSize + prevTagSize
  4806. }
  4807.  
  4808. // dispatch parsed frames to consumer (typically, the remuxer)
  4809. if (this._isInitialMetadataDispatched()) {
  4810. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4811. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4812. }
  4813. }
  4814.  
  4815. return offset; // consumed bytes, just equals latest offset index
  4816. }
  4817.  
  4818. _parseScriptData(arrayBuffer, dataOffset, dataSize) {
  4819. let scriptData = AMF.parseScriptData(arrayBuffer, dataOffset, dataSize);
  4820.  
  4821. if (scriptData.hasOwnProperty('onMetaData')) {
  4822. if (scriptData.onMetaData == null || typeof scriptData.onMetaData !== 'object') {
  4823. Log.w(this.TAG, 'Invalid onMetaData structure!');
  4824. return;
  4825. }
  4826. if (this._metadata) {
  4827. Log.w(this.TAG, 'Found another onMetaData tag!');
  4828. }
  4829. this._metadata = scriptData;
  4830. let onMetaData = this._metadata.onMetaData;
  4831.  
  4832. if (typeof onMetaData.hasAudio === 'boolean') { // hasAudio
  4833. if (this._hasAudioFlagOverrided === false) {
  4834. this._hasAudio = onMetaData.hasAudio;
  4835. this._mediaInfo.hasAudio = this._hasAudio;
  4836. }
  4837. }
  4838. if (typeof onMetaData.hasVideo === 'boolean') { // hasVideo
  4839. if (this._hasVideoFlagOverrided === false) {
  4840. this._hasVideo = onMetaData.hasVideo;
  4841. this._mediaInfo.hasVideo = this._hasVideo;
  4842. }
  4843. }
  4844. if (typeof onMetaData.audiodatarate === 'number') { // audiodatarate
  4845. this._mediaInfo.audioDataRate = onMetaData.audiodatarate;
  4846. }
  4847. if (typeof onMetaData.videodatarate === 'number') { // videodatarate
  4848. this._mediaInfo.videoDataRate = onMetaData.videodatarate;
  4849. }
  4850. if (typeof onMetaData.width === 'number') { // width
  4851. this._mediaInfo.width = onMetaData.width;
  4852. }
  4853. if (typeof onMetaData.height === 'number') { // height
  4854. this._mediaInfo.height = onMetaData.height;
  4855. }
  4856. if (typeof onMetaData.duration === 'number') { // duration
  4857. if (!this._durationOverrided) {
  4858. let duration = Math.floor(onMetaData.duration * this._timescale);
  4859. this._duration = duration;
  4860. this._mediaInfo.duration = duration;
  4861. }
  4862. } else {
  4863. this._mediaInfo.duration = 0;
  4864. }
  4865. if (typeof onMetaData.framerate === 'number') { // framerate
  4866. let fps_num = Math.floor(onMetaData.framerate * 1000);
  4867. if (fps_num > 0) {
  4868. let fps = fps_num / 1000;
  4869. this._referenceFrameRate.fixed = true;
  4870. this._referenceFrameRate.fps = fps;
  4871. this._referenceFrameRate.fps_num = fps_num;
  4872. this._referenceFrameRate.fps_den = 1000;
  4873. this._mediaInfo.fps = fps;
  4874. }
  4875. }
  4876. if (typeof onMetaData.keyframes === 'object') { // keyframes
  4877. this._mediaInfo.hasKeyframesIndex = true;
  4878. let keyframes = onMetaData.keyframes;
  4879. this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(keyframes);
  4880. onMetaData.keyframes = null; // keyframes has been extracted, remove it
  4881. } else {
  4882. this._mediaInfo.hasKeyframesIndex = false;
  4883. }
  4884. this._dispatch = false;
  4885. this._mediaInfo.metadata = onMetaData;
  4886. Log.v(this.TAG, 'Parsed onMetaData');
  4887. if (this._mediaInfo.isComplete()) {
  4888. this._onMediaInfo(this._mediaInfo);
  4889. }
  4890. }
  4891. }
  4892.  
  4893. _parseKeyframesIndex(keyframes) {
  4894. let times = [];
  4895. let filepositions = [];
  4896.  
  4897. // ignore first keyframe which is actually AVC Sequence Header (AVCDecoderConfigurationRecord)
  4898. for (let i = 1; i < keyframes.times.length; i++) {
  4899. let time = this._timestampBase + Math.floor(keyframes.times[i] * 1000);
  4900. times.push(time);
  4901. filepositions.push(keyframes.filepositions[i]);
  4902. }
  4903.  
  4904. return {
  4905. times: times,
  4906. filepositions: filepositions
  4907. };
  4908. }
  4909.  
  4910. _parseAudioData(arrayBuffer, dataOffset, dataSize, tagTimestamp) {
  4911. if (dataSize <= 1) {
  4912. Log.w(this.TAG, 'Flv: Invalid audio packet, missing SoundData payload!');
  4913. return;
  4914. }
  4915.  
  4916. if (this._hasAudioFlagOverrided === true && this._hasAudio === false) {
  4917. // If hasAudio: false indicated explicitly in MediaDataSource,
  4918. // Ignore all the audio packets
  4919. return;
  4920. }
  4921.  
  4922. let le = this._littleEndian;
  4923. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  4924.  
  4925. let soundSpec = v.getUint8(0);
  4926.  
  4927. let soundFormat = soundSpec >>> 4;
  4928. if (soundFormat !== 2 && soundFormat !== 10) { // MP3 or AAC
  4929. this._onError(DemuxErrors.CODEC_UNSUPPORTED, 'Flv: Unsupported audio codec idx: ' + soundFormat);
  4930. return;
  4931. }
  4932.  
  4933. let soundRate = 0;
  4934. let soundRateIndex = (soundSpec & 12) >>> 2;
  4935. if (soundRateIndex >= 0 && soundRateIndex <= 4) {
  4936. soundRate = this._flvSoundRateTable[soundRateIndex];
  4937. } else {
  4938. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid audio sample rate idx: ' + soundRateIndex);
  4939. return;
  4940. }
  4941. let soundType = (soundSpec & 1);
  4942.  
  4943.  
  4944. let meta = this._audioMetadata;
  4945. let track = this._audioTrack;
  4946.  
  4947. if (!meta) {
  4948. if (this._hasAudio === false && this._hasAudioFlagOverrided === false) {
  4949. this._hasAudio = true;
  4950. this._mediaInfo.hasAudio = true;
  4951. }
  4952.  
  4953. // initial metadata
  4954. meta = this._audioMetadata = {};
  4955. meta.type = 'audio';
  4956. meta.id = track.id;
  4957. meta.timescale = this._timescale;
  4958. meta.duration = this._duration;
  4959. meta.audioSampleRate = soundRate;
  4960. meta.channelCount = (soundType === 0 ? 1 : 2);
  4961. }
  4962.  
  4963. if (soundFormat === 10) { // AAC
  4964. let aacData = this._parseAACAudioData(arrayBuffer, dataOffset + 1, dataSize - 1);
  4965.  
  4966. if (aacData == undefined) {
  4967. return;
  4968. }
  4969.  
  4970. if (aacData.packetType === 0) { // AAC sequence header (AudioSpecificConfig)
  4971. if (meta.config) {
  4972. Log.w(this.TAG, 'Found another AudioSpecificConfig!');
  4973. }
  4974. let misc = aacData.data;
  4975. meta.audioSampleRate = misc.samplingRate;
  4976. meta.channelCount = misc.channelCount;
  4977. meta.codec = misc.codec;
  4978. meta.originalCodec = misc.originalCodec;
  4979. meta.config = misc.config;
  4980. // added by qli5
  4981. meta.configRaw = misc.configRaw;
  4982. // added by Xmader
  4983. meta.audioObjectType = misc.audioObjectType;
  4984. meta.samplingFrequencyIndex = misc.samplingIndex;
  4985. meta.channelConfig = misc.channelCount;
  4986. // The decode result of an aac sample is 1024 PCM samples
  4987. meta.refSampleDuration = 1024 / meta.audioSampleRate * meta.timescale;
  4988. Log.v(this.TAG, 'Parsed AudioSpecificConfig');
  4989.  
  4990. if (this._isInitialMetadataDispatched()) {
  4991. // Non-initial metadata, force dispatch (or flush) parsed frames to remuxer
  4992. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  4993. this._onDataAvailable(this._audioTrack, this._videoTrack);
  4994. }
  4995. } else {
  4996. this._audioInitialMetadataDispatched = true;
  4997. }
  4998. // then notify new metadata
  4999. this._dispatch = false;
  5000. this._onTrackMetadata('audio', meta);
  5001.  
  5002. let mi = this._mediaInfo;
  5003. mi.audioCodec = meta.originalCodec;
  5004. mi.audioSampleRate = meta.audioSampleRate;
  5005. mi.audioChannelCount = meta.channelCount;
  5006. if (mi.hasVideo) {
  5007. if (mi.videoCodec != null) {
  5008. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  5009. }
  5010. } else {
  5011. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  5012. }
  5013. if (mi.isComplete()) {
  5014. this._onMediaInfo(mi);
  5015. }
  5016. } else if (aacData.packetType === 1) { // AAC raw frame data
  5017. let dts = this._timestampBase + tagTimestamp;
  5018. let aacSample = { unit: aacData.data, length: aacData.data.byteLength, dts: dts, pts: dts };
  5019. track.samples.push(aacSample);
  5020. track.length += aacData.data.length;
  5021. } else {
  5022. Log.e(this.TAG, \`Flv: Unsupported AAC data type \${aacData.packetType}\`);
  5023. }
  5024. } else if (soundFormat === 2) { // MP3
  5025. if (!meta.codec) {
  5026. // We need metadata for mp3 audio track, extract info from frame header
  5027. let misc = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, true);
  5028. if (misc == undefined) {
  5029. return;
  5030. }
  5031. meta.audioSampleRate = misc.samplingRate;
  5032. meta.channelCount = misc.channelCount;
  5033. meta.codec = misc.codec;
  5034. meta.originalCodec = misc.originalCodec;
  5035. // The decode result of an mp3 sample is 1152 PCM samples
  5036. meta.refSampleDuration = 1152 / meta.audioSampleRate * meta.timescale;
  5037. Log.v(this.TAG, 'Parsed MPEG Audio Frame Header');
  5038.  
  5039. this._audioInitialMetadataDispatched = true;
  5040. this._onTrackMetadata('audio', meta);
  5041.  
  5042. let mi = this._mediaInfo;
  5043. mi.audioCodec = meta.codec;
  5044. mi.audioSampleRate = meta.audioSampleRate;
  5045. mi.audioChannelCount = meta.channelCount;
  5046. mi.audioDataRate = misc.bitRate;
  5047. if (mi.hasVideo) {
  5048. if (mi.videoCodec != null) {
  5049. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  5050. }
  5051. } else {
  5052. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  5053. }
  5054. if (mi.isComplete()) {
  5055. this._onMediaInfo(mi);
  5056. }
  5057. }
  5058.  
  5059. // This packet is always a valid audio packet, extract it
  5060. let data = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, false);
  5061. if (data == undefined) {
  5062. return;
  5063. }
  5064. let dts = this._timestampBase + tagTimestamp;
  5065. let mp3Sample = { unit: data, length: data.byteLength, dts: dts, pts: dts };
  5066. track.samples.push(mp3Sample);
  5067. track.length += data.length;
  5068. }
  5069. }
  5070.  
  5071. _parseAACAudioData(arrayBuffer, dataOffset, dataSize) {
  5072. if (dataSize <= 1) {
  5073. Log.w(this.TAG, 'Flv: Invalid AAC packet, missing AACPacketType or/and Data!');
  5074. return;
  5075. }
  5076.  
  5077. let result = {};
  5078. let array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  5079.  
  5080. result.packetType = array[0];
  5081.  
  5082. if (array[0] === 0) {
  5083. result.data = this._parseAACAudioSpecificConfig(arrayBuffer, dataOffset + 1, dataSize - 1);
  5084. } else {
  5085. result.data = array.subarray(1);
  5086. }
  5087.  
  5088. return result;
  5089. }
  5090.  
  5091. _parseAACAudioSpecificConfig(arrayBuffer, dataOffset, dataSize) {
  5092. let array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  5093. let config = null;
  5094.  
  5095. /* Audio Object Type:
  5096. 0: Null
  5097. 1: AAC Main
  5098. 2: AAC LC
  5099. 3: AAC SSR (Scalable Sample Rate)
  5100. 4: AAC LTP (Long Term Prediction)
  5101. 5: HE-AAC / SBR (Spectral Band Replication)
  5102. 6: AAC Scalable
  5103. */
  5104.  
  5105. let audioObjectType = 0;
  5106. let originalAudioObjectType = 0;
  5107. let samplingIndex = 0;
  5108. let extensionSamplingIndex = null;
  5109.  
  5110. // 5 bits
  5111. audioObjectType = originalAudioObjectType = array[0] >>> 3;
  5112. // 4 bits
  5113. samplingIndex = ((array[0] & 0x07) << 1) | (array[1] >>> 7);
  5114. if (samplingIndex < 0 || samplingIndex >= this._mpegSamplingRates.length) {
  5115. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: AAC invalid sampling frequency index!');
  5116. return;
  5117. }
  5118.  
  5119. let samplingFrequence = this._mpegSamplingRates[samplingIndex];
  5120.  
  5121. // 4 bits
  5122. let channelConfig = (array[1] & 0x78) >>> 3;
  5123. if (channelConfig < 0 || channelConfig >= 8) {
  5124. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: AAC invalid channel configuration');
  5125. return;
  5126. }
  5127.  
  5128. if (audioObjectType === 5) { // HE-AAC?
  5129. // 4 bits
  5130. extensionSamplingIndex = ((array[1] & 0x07) << 1) | (array[2] >>> 7);
  5131. }
  5132.  
  5133. // workarounds for various browsers
  5134. let userAgent = _navigator.userAgent.toLowerCase();
  5135.  
  5136. if (userAgent.indexOf('firefox') !== -1) {
  5137. // firefox: use SBR (HE-AAC) if freq less than 24kHz
  5138. if (samplingIndex >= 6) {
  5139. audioObjectType = 5;
  5140. config = new Array(4);
  5141. extensionSamplingIndex = samplingIndex - 3;
  5142. } else { // use LC-AAC
  5143. audioObjectType = 2;
  5144. config = new Array(2);
  5145. extensionSamplingIndex = samplingIndex;
  5146. }
  5147. } else if (userAgent.indexOf('android') !== -1) {
  5148. // android: always use LC-AAC
  5149. audioObjectType = 2;
  5150. config = new Array(2);
  5151. extensionSamplingIndex = samplingIndex;
  5152. } else {
  5153. // for other browsers, e.g. chrome...
  5154. // Always use HE-AAC to make it easier to switch aac codec profile
  5155. audioObjectType = 5;
  5156. extensionSamplingIndex = samplingIndex;
  5157. config = new Array(4);
  5158.  
  5159. if (samplingIndex >= 6) {
  5160. extensionSamplingIndex = samplingIndex - 3;
  5161. } else if (channelConfig === 1) { // Mono channel
  5162. audioObjectType = 2;
  5163. config = new Array(2);
  5164. extensionSamplingIndex = samplingIndex;
  5165. }
  5166. }
  5167.  
  5168. config[0] = audioObjectType << 3;
  5169. config[0] |= (samplingIndex & 0x0F) >>> 1;
  5170. config[1] = (samplingIndex & 0x0F) << 7;
  5171. config[1] |= (channelConfig & 0x0F) << 3;
  5172. if (audioObjectType === 5) {
  5173. config[1] |= ((extensionSamplingIndex & 0x0F) >>> 1);
  5174. config[2] = (extensionSamplingIndex & 0x01) << 7;
  5175. // extended audio object type: force to 2 (LC-AAC)
  5176. config[2] |= (2 << 2);
  5177. config[3] = 0;
  5178. }
  5179.  
  5180. return {
  5181. audioObjectType, // audio_object_type, added by Xmader
  5182. samplingIndex, // sampling_frequency_index, added by Xmader
  5183. configRaw: array, // added by qli5
  5184. config: config,
  5185. samplingRate: samplingFrequence,
  5186. channelCount: channelConfig, // channel_config
  5187. codec: 'mp4a.40.' + audioObjectType,
  5188. originalCodec: 'mp4a.40.' + originalAudioObjectType
  5189. };
  5190. }
  5191.  
  5192. _parseMP3AudioData(arrayBuffer, dataOffset, dataSize, requestHeader) {
  5193. if (dataSize < 4) {
  5194. Log.w(this.TAG, 'Flv: Invalid MP3 packet, header missing!');
  5195. return;
  5196. }
  5197.  
  5198. let le = this._littleEndian;
  5199. let array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  5200. let result = null;
  5201.  
  5202. if (requestHeader) {
  5203. if (array[0] !== 0xFF) {
  5204. return;
  5205. }
  5206. let ver = (array[1] >>> 3) & 0x03;
  5207. let layer = (array[1] & 0x06) >> 1;
  5208.  
  5209. let bitrate_index = (array[2] & 0xF0) >>> 4;
  5210. let sampling_freq_index = (array[2] & 0x0C) >>> 2;
  5211.  
  5212. let channel_mode = (array[3] >>> 6) & 0x03;
  5213. let channel_count = channel_mode !== 3 ? 2 : 1;
  5214.  
  5215. let sample_rate = 0;
  5216. let bit_rate = 0;
  5217.  
  5218. let codec = 'mp3';
  5219.  
  5220. switch (ver) {
  5221. case 0: // MPEG 2.5
  5222. sample_rate = this._mpegAudioV25SampleRateTable[sampling_freq_index];
  5223. break;
  5224. case 2: // MPEG 2
  5225. sample_rate = this._mpegAudioV20SampleRateTable[sampling_freq_index];
  5226. break;
  5227. case 3: // MPEG 1
  5228. sample_rate = this._mpegAudioV10SampleRateTable[sampling_freq_index];
  5229. break;
  5230. }
  5231.  
  5232. switch (layer) {
  5233. case 1: // Layer 3
  5234. if (bitrate_index < this._mpegAudioL3BitRateTable.length) {
  5235. bit_rate = this._mpegAudioL3BitRateTable[bitrate_index];
  5236. }
  5237. break;
  5238. case 2: // Layer 2
  5239. if (bitrate_index < this._mpegAudioL2BitRateTable.length) {
  5240. bit_rate = this._mpegAudioL2BitRateTable[bitrate_index];
  5241. }
  5242. break;
  5243. case 3: // Layer 1
  5244. if (bitrate_index < this._mpegAudioL1BitRateTable.length) {
  5245. bit_rate = this._mpegAudioL1BitRateTable[bitrate_index];
  5246. }
  5247. break;
  5248. }
  5249.  
  5250. result = {
  5251. bitRate: bit_rate,
  5252. samplingRate: sample_rate,
  5253. channelCount: channel_count,
  5254. codec: codec,
  5255. originalCodec: codec
  5256. };
  5257. } else {
  5258. result = array;
  5259. }
  5260.  
  5261. return result;
  5262. }
  5263.  
  5264. _parseVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition) {
  5265. if (dataSize <= 1) {
  5266. Log.w(this.TAG, 'Flv: Invalid video packet, missing VideoData payload!');
  5267. return;
  5268. }
  5269.  
  5270. if (this._hasVideoFlagOverrided === true && this._hasVideo === false) {
  5271. // If hasVideo: false indicated explicitly in MediaDataSource,
  5272. // Ignore all the video packets
  5273. return;
  5274. }
  5275.  
  5276. let spec = (new Uint8Array(arrayBuffer, dataOffset, dataSize))[0];
  5277.  
  5278. let frameType = (spec & 240) >>> 4;
  5279. let codecId = spec & 15;
  5280.  
  5281. if (codecId !== 7) {
  5282. this._onError(DemuxErrors.CODEC_UNSUPPORTED, \`Flv: Unsupported codec in video frame: \${codecId}\`);
  5283. return;
  5284. }
  5285.  
  5286. this._parseAVCVideoPacket(arrayBuffer, dataOffset + 1, dataSize - 1, tagTimestamp, tagPosition, frameType);
  5287. }
  5288.  
  5289. _parseAVCVideoPacket(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType) {
  5290. if (dataSize < 4) {
  5291. Log.w(this.TAG, 'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime');
  5292. return;
  5293. }
  5294.  
  5295. let le = this._littleEndian;
  5296. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  5297.  
  5298. let packetType = v.getUint8(0);
  5299. let cts = v.getUint32(0, !le) & 0x00FFFFFF;
  5300.  
  5301. if (packetType === 0) { // AVCDecoderConfigurationRecord
  5302. this._parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset + 4, dataSize - 4);
  5303. } else if (packetType === 1) { // One or more Nalus
  5304. this._parseAVCVideoData(arrayBuffer, dataOffset + 4, dataSize - 4, tagTimestamp, tagPosition, frameType, cts);
  5305. } else if (packetType === 2) {
  5306. // empty, AVC end of sequence
  5307. } else {
  5308. this._onError(DemuxErrors.FORMAT_ERROR, \`Flv: Invalid video packet type \${packetType}\`);
  5309. return;
  5310. }
  5311. }
  5312.  
  5313. _parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset, dataSize) {
  5314. if (dataSize < 7) {
  5315. Log.w(this.TAG, 'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!');
  5316. return;
  5317. }
  5318.  
  5319. let meta = this._videoMetadata;
  5320. let track = this._videoTrack;
  5321. let le = this._littleEndian;
  5322. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  5323.  
  5324. if (!meta) {
  5325. if (this._hasVideo === false && this._hasVideoFlagOverrided === false) {
  5326. this._hasVideo = true;
  5327. this._mediaInfo.hasVideo = true;
  5328. }
  5329.  
  5330. meta = this._videoMetadata = {};
  5331. meta.type = 'video';
  5332. meta.id = track.id;
  5333. meta.timescale = this._timescale;
  5334. meta.duration = this._duration;
  5335. } else {
  5336. if (typeof meta.avcc !== 'undefined') {
  5337. Log.w(this.TAG, 'Found another AVCDecoderConfigurationRecord!');
  5338. }
  5339. }
  5340.  
  5341. let version = v.getUint8(0); // configurationVersion
  5342. let avcProfile = v.getUint8(1); // avcProfileIndication
  5343. let profileCompatibility = v.getUint8(2); // profile_compatibility
  5344. let avcLevel = v.getUint8(3); // AVCLevelIndication
  5345.  
  5346. if (version !== 1 || avcProfile === 0) {
  5347. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord');
  5348. return;
  5349. }
  5350.  
  5351. this._naluLengthSize = (v.getUint8(4) & 3) + 1; // lengthSizeMinusOne
  5352. if (this._naluLengthSize !== 3 && this._naluLengthSize !== 4) { // holy shit!!!
  5353. this._onError(DemuxErrors.FORMAT_ERROR, \`Flv: Strange NaluLengthSizeMinusOne: \${this._naluLengthSize - 1}\`);
  5354. return;
  5355. }
  5356.  
  5357. let spsCount = v.getUint8(5) & 31; // numOfSequenceParameterSets
  5358. if (spsCount === 0) {
  5359. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No SPS');
  5360. return;
  5361. } else if (spsCount > 1) {
  5362. Log.w(this.TAG, \`Flv: Strange AVCDecoderConfigurationRecord: SPS Count = \${spsCount}\`);
  5363. }
  5364.  
  5365. let offset = 6;
  5366.  
  5367. for (let i = 0; i < spsCount; i++) {
  5368. let len = v.getUint16(offset, !le); // sequenceParameterSetLength
  5369. offset += 2;
  5370.  
  5371. if (len === 0) {
  5372. continue;
  5373. }
  5374.  
  5375. // Notice: Nalu without startcode header (00 00 00 01)
  5376. let sps = new Uint8Array(arrayBuffer, dataOffset + offset, len);
  5377. offset += len;
  5378.  
  5379. let config = SPSParser.parseSPS(sps);
  5380. if (i !== 0) {
  5381. // ignore other sps's config
  5382. continue;
  5383. }
  5384.  
  5385. meta.codecWidth = config.codec_size.width;
  5386. meta.codecHeight = config.codec_size.height;
  5387. meta.presentWidth = config.present_size.width;
  5388. meta.presentHeight = config.present_size.height;
  5389.  
  5390. meta.profile = config.profile_string;
  5391. meta.level = config.level_string;
  5392. meta.bitDepth = config.bit_depth;
  5393. meta.chromaFormat = config.chroma_format;
  5394. meta.sarRatio = config.sar_ratio;
  5395. meta.frameRate = config.frame_rate;
  5396.  
  5397. if (config.frame_rate.fixed === false ||
  5398. config.frame_rate.fps_num === 0 ||
  5399. config.frame_rate.fps_den === 0) {
  5400. meta.frameRate = this._referenceFrameRate;
  5401. }
  5402.  
  5403. let fps_den = meta.frameRate.fps_den;
  5404. let fps_num = meta.frameRate.fps_num;
  5405. meta.refSampleDuration = meta.timescale * (fps_den / fps_num);
  5406.  
  5407. let codecArray = sps.subarray(1, 4);
  5408. let codecString = 'avc1.';
  5409. for (let j = 0; j < 3; j++) {
  5410. let h = codecArray[j].toString(16);
  5411. if (h.length < 2) {
  5412. h = '0' + h;
  5413. }
  5414. codecString += h;
  5415. }
  5416. meta.codec = codecString;
  5417.  
  5418. let mi = this._mediaInfo;
  5419. mi.width = meta.codecWidth;
  5420. mi.height = meta.codecHeight;
  5421. mi.fps = meta.frameRate.fps;
  5422. mi.profile = meta.profile;
  5423. mi.level = meta.level;
  5424. mi.chromaFormat = config.chroma_format_string;
  5425. mi.sarNum = meta.sarRatio.width;
  5426. mi.sarDen = meta.sarRatio.height;
  5427. mi.videoCodec = codecString;
  5428.  
  5429. if (mi.hasAudio) {
  5430. if (mi.audioCodec != null) {
  5431. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  5432. }
  5433. } else {
  5434. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + '"';
  5435. }
  5436. if (mi.isComplete()) {
  5437. this._onMediaInfo(mi);
  5438. }
  5439. }
  5440.  
  5441. let ppsCount = v.getUint8(offset); // numOfPictureParameterSets
  5442. if (ppsCount === 0) {
  5443. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No PPS');
  5444. return;
  5445. } else if (ppsCount > 1) {
  5446. Log.w(this.TAG, \`Flv: Strange AVCDecoderConfigurationRecord: PPS Count = \${ppsCount}\`);
  5447. }
  5448.  
  5449. offset++;
  5450.  
  5451. for (let i = 0; i < ppsCount; i++) {
  5452. let len = v.getUint16(offset, !le); // pictureParameterSetLength
  5453. offset += 2;
  5454.  
  5455. if (len === 0) {
  5456. continue;
  5457. }
  5458.  
  5459. // pps is useless for extracting video information
  5460. offset += len;
  5461. }
  5462.  
  5463. meta.avcc = new Uint8Array(dataSize);
  5464. meta.avcc.set(new Uint8Array(arrayBuffer, dataOffset, dataSize), 0);
  5465. Log.v(this.TAG, 'Parsed AVCDecoderConfigurationRecord');
  5466.  
  5467. if (this._isInitialMetadataDispatched()) {
  5468. // flush parsed frames
  5469. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  5470. this._onDataAvailable(this._audioTrack, this._videoTrack);
  5471. }
  5472. } else {
  5473. this._videoInitialMetadataDispatched = true;
  5474. }
  5475. // notify new metadata
  5476. this._dispatch = false;
  5477. this._onTrackMetadata('video', meta);
  5478. }
  5479.  
  5480. _parseAVCVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType, cts) {
  5481. let le = this._littleEndian;
  5482. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  5483.  
  5484. let units = [], length = 0;
  5485.  
  5486. let offset = 0;
  5487. const lengthSize = this._naluLengthSize;
  5488. let dts = this._timestampBase + tagTimestamp;
  5489. let keyframe = (frameType === 1); // from FLV Frame Type constants
  5490. let refIdc = 1; // added by qli5
  5491.  
  5492. while (offset < dataSize) {
  5493. if (offset + 4 >= dataSize) {
  5494. Log.w(this.TAG, \`Malformed Nalu near timestamp \${dts}, offset = \${offset}, dataSize = \${dataSize}\`);
  5495. break; // data not enough for next Nalu
  5496. }
  5497. // Nalu with length-header (AVC1)
  5498. let naluSize = v.getUint32(offset, !le); // Big-Endian read
  5499. if (lengthSize === 3) {
  5500. naluSize >>>= 8;
  5501. }
  5502. if (naluSize > dataSize - lengthSize) {
  5503. Log.w(this.TAG, \`Malformed Nalus near timestamp \${dts}, NaluSize > DataSize!\`);
  5504. return;
  5505. }
  5506.  
  5507. let unitType = v.getUint8(offset + lengthSize) & 0x1F;
  5508. // added by qli5
  5509. refIdc = v.getUint8(offset + lengthSize) & 0x60;
  5510.  
  5511. if (unitType === 5) { // IDR
  5512. keyframe = true;
  5513. }
  5514.  
  5515. let data = new Uint8Array(arrayBuffer, dataOffset + offset, lengthSize + naluSize);
  5516. let unit = { type: unitType, data: data };
  5517. units.push(unit);
  5518. length += data.byteLength;
  5519.  
  5520. offset += lengthSize + naluSize;
  5521. }
  5522.  
  5523. if (units.length) {
  5524. let track = this._videoTrack;
  5525. let avcSample = {
  5526. units: units,
  5527. length: length,
  5528. isKeyframe: keyframe,
  5529. refIdc: refIdc,
  5530. dts: dts,
  5531. cts: cts,
  5532. pts: (dts + cts)
  5533. };
  5534. if (keyframe) {
  5535. avcSample.fileposition = tagPosition;
  5536. }
  5537. track.samples.push(avcSample);
  5538. track.length += length;
  5539. }
  5540. }
  5541.  
  5542. }
  5543.  
  5544. /***
  5545. * Copyright (C) 2018 Qli5. All Rights Reserved.
  5546. *
  5547. * @author qli5 <goodlq11[at](163|gmail).com>
  5548. *
  5549. * This Source Code Form is subject to the terms of the Mozilla Public
  5550. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5551. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5552. */
  5553.  
  5554. class ASS {
  5555. /**
  5556. * Extract sections from ass string
  5557. * @param {string} str
  5558. * @returns {Object} - object from sections
  5559. */
  5560. static extractSections(str) {
  5561. const regex = /^\\ufeff?\\[(.*)\\]\$/mg;
  5562. let match;
  5563. let matchArr = [];
  5564. while ((match = regex.exec(str)) !== null) {
  5565. matchArr.push({ name: match[1], index: match.index });
  5566. }
  5567. let ret = {};
  5568. matchArr.forEach((match, i) => ret[match.name] = str.slice(match.index, matchArr[i + 1] && matchArr[i + 1].index));
  5569. return ret;
  5570. }
  5571.  
  5572. /**
  5573. * Extract subtitle lines from section Events
  5574. * @param {string} str
  5575. * @returns {Array<Object>} - array of subtitle lines
  5576. */
  5577. static extractSubtitleLines(str) {
  5578. const lines = str.split(/\\r\\n+/);
  5579. if (lines[0] != '[Events]' && lines[0] != '[events]') throw new Error('ASSDemuxer: section is not [Events]');
  5580. if (lines[1].indexOf('Format:') != 0 && lines[1].indexOf('format:') != 0) throw new Error('ASSDemuxer: cannot find Format definition in section [Events]');
  5581.  
  5582. const format = lines[1].slice(lines[1].indexOf(':') + 1).split(',').map(e => e.trim());
  5583. return lines.slice(2).map(e => {
  5584. let j = {};
  5585. e.replace(/[d|D]ialogue:\\s*/, '')
  5586. .match(new RegExp(new Array(format.length - 1).fill('(.*?),').join('') + '(.*)'))
  5587. .slice(1)
  5588. .forEach((k, index) => j[format[index]] = k);
  5589. return j;
  5590. });
  5591. }
  5592.  
  5593. /**
  5594. * Create a new ASS Demuxer
  5595. */
  5596. constructor() {
  5597. this.info = '';
  5598. this.styles = '';
  5599. this.events = '';
  5600. this.eventsHeader = '';
  5601. this.pictures = '';
  5602. this.fonts = '';
  5603. this.lines = [];
  5604. }
  5605.  
  5606. get header() {
  5607. // return this.info + this.styles + this.eventsHeader;
  5608. return this.info + this.styles;
  5609. }
  5610.  
  5611. /**
  5612. * Load a file from an arraybuffer of a string
  5613. * @param {(ArrayBuffer|string)} chunk
  5614. */
  5615. parseFile(chunk) {
  5616. const str = typeof chunk == 'string' ? chunk : new _TextDecoder('utf-8').decode(chunk);
  5617. for (let [i, j] of Object.entries(ASS.extractSections(str))) {
  5618. if (i.match(/Script Info(?:mation)?/i)) this.info = j;
  5619. else if (i.match(/V4\\+? Styles?/i)) this.styles = j;
  5620. else if (i.match(/Events?/i)) this.events = j;
  5621. else if (i.match(/Pictures?/i)) this.pictures = j;
  5622. else if (i.match(/Fonts?/i)) this.fonts = j;
  5623. }
  5624. this.eventsHeader = this.events.split('\\n', 2).join('\\n') + '\\n';
  5625. this.lines = ASS.extractSubtitleLines(this.events);
  5626. return this;
  5627. }
  5628. }
  5629.  
  5630. /** Detect free variable \`global\` from Node.js. */
  5631. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  5632.  
  5633. /** Detect free variable \`self\`. */
  5634. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  5635.  
  5636. /** Used as a reference to the global object. */
  5637. var root = freeGlobal || freeSelf || Function('return this')();
  5638.  
  5639. /** Built-in value references. */
  5640. var Symbol = root.Symbol;
  5641.  
  5642. /** Used for built-in method references. */
  5643. var objectProto = Object.prototype;
  5644.  
  5645. /** Used to check objects for own properties. */
  5646. var hasOwnProperty = objectProto.hasOwnProperty;
  5647.  
  5648. /**
  5649. * Used to resolve the
  5650. * [\`toStringTag\`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  5651. * of values.
  5652. */
  5653. var nativeObjectToString = objectProto.toString;
  5654.  
  5655. /** Built-in value references. */
  5656. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  5657.  
  5658. /**
  5659. * A specialized version of \`baseGetTag\` which ignores \`Symbol.toStringTag\` values.
  5660. *
  5661. * @private
  5662. * @param {*} value The value to query.
  5663. * @returns {string} Returns the raw \`toStringTag\`.
  5664. */
  5665. function getRawTag(value) {
  5666. var isOwn = hasOwnProperty.call(value, symToStringTag),
  5667. tag = value[symToStringTag];
  5668.  
  5669. try {
  5670. value[symToStringTag] = undefined;
  5671. var unmasked = true;
  5672. } catch (e) {}
  5673.  
  5674. var result = nativeObjectToString.call(value);
  5675. if (unmasked) {
  5676. if (isOwn) {
  5677. value[symToStringTag] = tag;
  5678. } else {
  5679. delete value[symToStringTag];
  5680. }
  5681. }
  5682. return result;
  5683. }
  5684.  
  5685. /** Used for built-in method references. */
  5686. var objectProto\$1 = Object.prototype;
  5687.  
  5688. /**
  5689. * Used to resolve the
  5690. * [\`toStringTag\`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  5691. * of values.
  5692. */
  5693. var nativeObjectToString\$1 = objectProto\$1.toString;
  5694.  
  5695. /**
  5696. * Converts \`value\` to a string using \`Object.prototype.toString\`.
  5697. *
  5698. * @private
  5699. * @param {*} value The value to convert.
  5700. * @returns {string} Returns the converted string.
  5701. */
  5702. function objectToString(value) {
  5703. return nativeObjectToString\$1.call(value);
  5704. }
  5705.  
  5706. /** \`Object#toString\` result references. */
  5707. var nullTag = '[object Null]',
  5708. undefinedTag = '[object Undefined]';
  5709.  
  5710. /** Built-in value references. */
  5711. var symToStringTag\$1 = Symbol ? Symbol.toStringTag : undefined;
  5712.  
  5713. /**
  5714. * The base implementation of \`getTag\` without fallbacks for buggy environments.
  5715. *
  5716. * @private
  5717. * @param {*} value The value to query.
  5718. * @returns {string} Returns the \`toStringTag\`.
  5719. */
  5720. function baseGetTag(value) {
  5721. if (value == null) {
  5722. return value === undefined ? undefinedTag : nullTag;
  5723. }
  5724. return (symToStringTag\$1 && symToStringTag\$1 in Object(value))
  5725. ? getRawTag(value)
  5726. : objectToString(value);
  5727. }
  5728.  
  5729. /**
  5730. * Checks if \`value\` is the
  5731. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  5732. * of \`Object\`. (e.g. arrays, functions, objects, regexes, \`new Number(0)\`, and \`new String('')\`)
  5733. *
  5734. * @static
  5735. * @memberOf _
  5736. * @since 0.1.0
  5737. * @category Lang
  5738. * @param {*} value The value to check.
  5739. * @returns {boolean} Returns \`true\` if \`value\` is an object, else \`false\`.
  5740. * @example
  5741. *
  5742. * _.isObject({});
  5743. * // => true
  5744. *
  5745. * _.isObject([1, 2, 3]);
  5746. * // => true
  5747. *
  5748. * _.isObject(_.noop);
  5749. * // => true
  5750. *
  5751. * _.isObject(null);
  5752. * // => false
  5753. */
  5754. function isObject(value) {
  5755. var type = typeof value;
  5756. return value != null && (type == 'object' || type == 'function');
  5757. }
  5758.  
  5759. /** \`Object#toString\` result references. */
  5760. var asyncTag = '[object AsyncFunction]',
  5761. funcTag = '[object Function]',
  5762. genTag = '[object GeneratorFunction]',
  5763. proxyTag = '[object Proxy]';
  5764.  
  5765. /**
  5766. * Checks if \`value\` is classified as a \`Function\` object.
  5767. *
  5768. * @static
  5769. * @memberOf _
  5770. * @since 0.1.0
  5771. * @category Lang
  5772. * @param {*} value The value to check.
  5773. * @returns {boolean} Returns \`true\` if \`value\` is a function, else \`false\`.
  5774. * @example
  5775. *
  5776. * _.isFunction(_);
  5777. * // => true
  5778. *
  5779. * _.isFunction(/abc/);
  5780. * // => false
  5781. */
  5782. function isFunction(value) {
  5783. if (!isObject(value)) {
  5784. return false;
  5785. }
  5786. // The use of \`Object#toString\` avoids issues with the \`typeof\` operator
  5787. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  5788. var tag = baseGetTag(value);
  5789. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  5790. }
  5791.  
  5792. /** Used to detect overreaching core-js shims. */
  5793. var coreJsData = root['__core-js_shared__'];
  5794.  
  5795. /** Used to detect methods masquerading as native. */
  5796. var maskSrcKey = (function() {
  5797. var uid = /[^.]+\$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  5798. return uid ? ('Symbol(src)_1.' + uid) : '';
  5799. }());
  5800.  
  5801. /**
  5802. * Checks if \`func\` has its source masked.
  5803. *
  5804. * @private
  5805. * @param {Function} func The function to check.
  5806. * @returns {boolean} Returns \`true\` if \`func\` is masked, else \`false\`.
  5807. */
  5808. function isMasked(func) {
  5809. return !!maskSrcKey && (maskSrcKey in func);
  5810. }
  5811.  
  5812. /** Used for built-in method references. */
  5813. var funcProto = Function.prototype;
  5814.  
  5815. /** Used to resolve the decompiled source of functions. */
  5816. var funcToString = funcProto.toString;
  5817.  
  5818. /**
  5819. * Converts \`func\` to its source code.
  5820. *
  5821. * @private
  5822. * @param {Function} func The function to convert.
  5823. * @returns {string} Returns the source code.
  5824. */
  5825. function toSource(func) {
  5826. if (func != null) {
  5827. try {
  5828. return funcToString.call(func);
  5829. } catch (e) {}
  5830. try {
  5831. return (func + '');
  5832. } catch (e) {}
  5833. }
  5834. return '';
  5835. }
  5836.  
  5837. /**
  5838. * Used to match \`RegExp\`
  5839. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  5840. */
  5841. var reRegExpChar = /[\\\\^\$.*+?()[\\]{}|]/g;
  5842.  
  5843. /** Used to detect host constructors (Safari). */
  5844. var reIsHostCtor = /^\\[object .+?Constructor\\]\$/;
  5845.  
  5846. /** Used for built-in method references. */
  5847. var funcProto\$1 = Function.prototype,
  5848. objectProto\$2 = Object.prototype;
  5849.  
  5850. /** Used to resolve the decompiled source of functions. */
  5851. var funcToString\$1 = funcProto\$1.toString;
  5852.  
  5853. /** Used to check objects for own properties. */
  5854. var hasOwnProperty\$1 = objectProto\$2.hasOwnProperty;
  5855.  
  5856. /** Used to detect if a method is native. */
  5857. var reIsNative = RegExp('^' +
  5858. funcToString\$1.call(hasOwnProperty\$1).replace(reRegExpChar, '\\\\\$&')
  5859. .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '\$1.*?') + '\$'
  5860. );
  5861.  
  5862. /**
  5863. * The base implementation of \`_.isNative\` without bad shim checks.
  5864. *
  5865. * @private
  5866. * @param {*} value The value to check.
  5867. * @returns {boolean} Returns \`true\` if \`value\` is a native function,
  5868. * else \`false\`.
  5869. */
  5870. function baseIsNative(value) {
  5871. if (!isObject(value) || isMasked(value)) {
  5872. return false;
  5873. }
  5874. var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  5875. return pattern.test(toSource(value));
  5876. }
  5877.  
  5878. /**
  5879. * Gets the value at \`key\` of \`object\`.
  5880. *
  5881. * @private
  5882. * @param {Object} [object] The object to query.
  5883. * @param {string} key The key of the property to get.
  5884. * @returns {*} Returns the property value.
  5885. */
  5886. function getValue(object, key) {
  5887. return object == null ? undefined : object[key];
  5888. }
  5889.  
  5890. /**
  5891. * Gets the native function at \`key\` of \`object\`.
  5892. *
  5893. * @private
  5894. * @param {Object} object The object to query.
  5895. * @param {string} key The key of the method to get.
  5896. * @returns {*} Returns the function if it's native, else \`undefined\`.
  5897. */
  5898. function getNative(object, key) {
  5899. var value = getValue(object, key);
  5900. return baseIsNative(value) ? value : undefined;
  5901. }
  5902.  
  5903. /* Built-in method references that are verified to be native. */
  5904. var nativeCreate = getNative(Object, 'create');
  5905.  
  5906. /**
  5907. * Removes all key-value entries from the hash.
  5908. *
  5909. * @private
  5910. * @name clear
  5911. * @memberOf Hash
  5912. */
  5913. function hashClear() {
  5914. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  5915. this.size = 0;
  5916. }
  5917.  
  5918. /**
  5919. * Removes \`key\` and its value from the hash.
  5920. *
  5921. * @private
  5922. * @name delete
  5923. * @memberOf Hash
  5924. * @param {Object} hash The hash to modify.
  5925. * @param {string} key The key of the value to remove.
  5926. * @returns {boolean} Returns \`true\` if the entry was removed, else \`false\`.
  5927. */
  5928. function hashDelete(key) {
  5929. var result = this.has(key) && delete this.__data__[key];
  5930. this.size -= result ? 1 : 0;
  5931. return result;
  5932. }
  5933.  
  5934. /** Used to stand-in for \`undefined\` hash values. */
  5935. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  5936.  
  5937. /** Used for built-in method references. */
  5938. var objectProto\$3 = Object.prototype;
  5939.  
  5940. /** Used to check objects for own properties. */
  5941. var hasOwnProperty\$2 = objectProto\$3.hasOwnProperty;
  5942.  
  5943. /**
  5944. * Gets the hash value for \`key\`.
  5945. *
  5946. * @private
  5947. * @name get
  5948. * @memberOf Hash
  5949. * @param {string} key The key of the value to get.
  5950. * @returns {*} Returns the entry value.
  5951. */
  5952. function hashGet(key) {
  5953. var data = this.__data__;
  5954. if (nativeCreate) {
  5955. var result = data[key];
  5956. return result === HASH_UNDEFINED ? undefined : result;
  5957. }
  5958. return hasOwnProperty\$2.call(data, key) ? data[key] : undefined;
  5959. }
  5960.  
  5961. /** Used for built-in method references. */
  5962. var objectProto\$4 = Object.prototype;
  5963.  
  5964. /** Used to check objects for own properties. */
  5965. var hasOwnProperty\$3 = objectProto\$4.hasOwnProperty;
  5966.  
  5967. /**
  5968. * Checks if a hash value for \`key\` exists.
  5969. *
  5970. * @private
  5971. * @name has
  5972. * @memberOf Hash
  5973. * @param {string} key The key of the entry to check.
  5974. * @returns {boolean} Returns \`true\` if an entry for \`key\` exists, else \`false\`.
  5975. */
  5976. function hashHas(key) {
  5977. var data = this.__data__;
  5978. return nativeCreate ? (data[key] !== undefined) : hasOwnProperty\$3.call(data, key);
  5979. }
  5980.  
  5981. /** Used to stand-in for \`undefined\` hash values. */
  5982. var HASH_UNDEFINED\$1 = '__lodash_hash_undefined__';
  5983.  
  5984. /**
  5985. * Sets the hash \`key\` to \`value\`.
  5986. *
  5987. * @private
  5988. * @name set
  5989. * @memberOf Hash
  5990. * @param {string} key The key of the value to set.
  5991. * @param {*} value The value to set.
  5992. * @returns {Object} Returns the hash instance.
  5993. */
  5994. function hashSet(key, value) {
  5995. var data = this.__data__;
  5996. this.size += this.has(key) ? 0 : 1;
  5997. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED\$1 : value;
  5998. return this;
  5999. }
  6000.  
  6001. /**
  6002. * Creates a hash object.
  6003. *
  6004. * @private
  6005. * @constructor
  6006. * @param {Array} [entries] The key-value pairs to cache.
  6007. */
  6008. function Hash(entries) {
  6009. var index = -1,
  6010. length = entries == null ? 0 : entries.length;
  6011.  
  6012. this.clear();
  6013. while (++index < length) {
  6014. var entry = entries[index];
  6015. this.set(entry[0], entry[1]);
  6016. }
  6017. }
  6018.  
  6019. // Add methods to \`Hash\`.
  6020. Hash.prototype.clear = hashClear;
  6021. Hash.prototype['delete'] = hashDelete;
  6022. Hash.prototype.get = hashGet;
  6023. Hash.prototype.has = hashHas;
  6024. Hash.prototype.set = hashSet;
  6025.  
  6026. /**
  6027. * Removes all key-value entries from the list cache.
  6028. *
  6029. * @private
  6030. * @name clear
  6031. * @memberOf ListCache
  6032. */
  6033. function listCacheClear() {
  6034. this.__data__ = [];
  6035. this.size = 0;
  6036. }
  6037.  
  6038. /**
  6039. * Performs a
  6040. * [\`SameValueZero\`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  6041. * comparison between two values to determine if they are equivalent.
  6042. *
  6043. * @static
  6044. * @memberOf _
  6045. * @since 4.0.0
  6046. * @category Lang
  6047. * @param {*} value The value to compare.
  6048. * @param {*} other The other value to compare.
  6049. * @returns {boolean} Returns \`true\` if the values are equivalent, else \`false\`.
  6050. * @example
  6051. *
  6052. * var object = { 'a': 1 };
  6053. * var other = { 'a': 1 };
  6054. *
  6055. * _.eq(object, object);
  6056. * // => true
  6057. *
  6058. * _.eq(object, other);
  6059. * // => false
  6060. *
  6061. * _.eq('a', 'a');
  6062. * // => true
  6063. *
  6064. * _.eq('a', Object('a'));
  6065. * // => false
  6066. *
  6067. * _.eq(NaN, NaN);
  6068. * // => true
  6069. */
  6070. function eq(value, other) {
  6071. return value === other || (value !== value && other !== other);
  6072. }
  6073.  
  6074. /**
  6075. * Gets the index at which the \`key\` is found in \`array\` of key-value pairs.
  6076. *
  6077. * @private
  6078. * @param {Array} array The array to inspect.
  6079. * @param {*} key The key to search for.
  6080. * @returns {number} Returns the index of the matched value, else \`-1\`.
  6081. */
  6082. function assocIndexOf(array, key) {
  6083. var length = array.length;
  6084. while (length--) {
  6085. if (eq(array[length][0], key)) {
  6086. return length;
  6087. }
  6088. }
  6089. return -1;
  6090. }
  6091.  
  6092. /** Used for built-in method references. */
  6093. var arrayProto = Array.prototype;
  6094.  
  6095. /** Built-in value references. */
  6096. var splice = arrayProto.splice;
  6097.  
  6098. /**
  6099. * Removes \`key\` and its value from the list cache.
  6100. *
  6101. * @private
  6102. * @name delete
  6103. * @memberOf ListCache
  6104. * @param {string} key The key of the value to remove.
  6105. * @returns {boolean} Returns \`true\` if the entry was removed, else \`false\`.
  6106. */
  6107. function listCacheDelete(key) {
  6108. var data = this.__data__,
  6109. index = assocIndexOf(data, key);
  6110.  
  6111. if (index < 0) {
  6112. return false;
  6113. }
  6114. var lastIndex = data.length - 1;
  6115. if (index == lastIndex) {
  6116. data.pop();
  6117. } else {
  6118. splice.call(data, index, 1);
  6119. }
  6120. --this.size;
  6121. return true;
  6122. }
  6123.  
  6124. /**
  6125. * Gets the list cache value for \`key\`.
  6126. *
  6127. * @private
  6128. * @name get
  6129. * @memberOf ListCache
  6130. * @param {string} key The key of the value to get.
  6131. * @returns {*} Returns the entry value.
  6132. */
  6133. function listCacheGet(key) {
  6134. var data = this.__data__,
  6135. index = assocIndexOf(data, key);
  6136.  
  6137. return index < 0 ? undefined : data[index][1];
  6138. }
  6139.  
  6140. /**
  6141. * Checks if a list cache value for \`key\` exists.
  6142. *
  6143. * @private
  6144. * @name has
  6145. * @memberOf ListCache
  6146. * @param {string} key The key of the entry to check.
  6147. * @returns {boolean} Returns \`true\` if an entry for \`key\` exists, else \`false\`.
  6148. */
  6149. function listCacheHas(key) {
  6150. return assocIndexOf(this.__data__, key) > -1;
  6151. }
  6152.  
  6153. /**
  6154. * Sets the list cache \`key\` to \`value\`.
  6155. *
  6156. * @private
  6157. * @name set
  6158. * @memberOf ListCache
  6159. * @param {string} key The key of the value to set.
  6160. * @param {*} value The value to set.
  6161. * @returns {Object} Returns the list cache instance.
  6162. */
  6163. function listCacheSet(key, value) {
  6164. var data = this.__data__,
  6165. index = assocIndexOf(data, key);
  6166.  
  6167. if (index < 0) {
  6168. ++this.size;
  6169. data.push([key, value]);
  6170. } else {
  6171. data[index][1] = value;
  6172. }
  6173. return this;
  6174. }
  6175.  
  6176. /**
  6177. * Creates an list cache object.
  6178. *
  6179. * @private
  6180. * @constructor
  6181. * @param {Array} [entries] The key-value pairs to cache.
  6182. */
  6183. function ListCache(entries) {
  6184. var index = -1,
  6185. length = entries == null ? 0 : entries.length;
  6186.  
  6187. this.clear();
  6188. while (++index < length) {
  6189. var entry = entries[index];
  6190. this.set(entry[0], entry[1]);
  6191. }
  6192. }
  6193.  
  6194. // Add methods to \`ListCache\`.
  6195. ListCache.prototype.clear = listCacheClear;
  6196. ListCache.prototype['delete'] = listCacheDelete;
  6197. ListCache.prototype.get = listCacheGet;
  6198. ListCache.prototype.has = listCacheHas;
  6199. ListCache.prototype.set = listCacheSet;
  6200.  
  6201. /* Built-in method references that are verified to be native. */
  6202. var Map = getNative(root, 'Map');
  6203.  
  6204. /**
  6205. * Removes all key-value entries from the map.
  6206. *
  6207. * @private
  6208. * @name clear
  6209. * @memberOf MapCache
  6210. */
  6211. function mapCacheClear() {
  6212. this.size = 0;
  6213. this.__data__ = {
  6214. 'hash': new Hash,
  6215. 'map': new (Map || ListCache),
  6216. 'string': new Hash
  6217. };
  6218. }
  6219.  
  6220. /**
  6221. * Checks if \`value\` is suitable for use as unique object key.
  6222. *
  6223. * @private
  6224. * @param {*} value The value to check.
  6225. * @returns {boolean} Returns \`true\` if \`value\` is suitable, else \`false\`.
  6226. */
  6227. function isKeyable(value) {
  6228. var type = typeof value;
  6229. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  6230. ? (value !== '__proto__')
  6231. : (value === null);
  6232. }
  6233.  
  6234. /**
  6235. * Gets the data for \`map\`.
  6236. *
  6237. * @private
  6238. * @param {Object} map The map to query.
  6239. * @param {string} key The reference key.
  6240. * @returns {*} Returns the map data.
  6241. */
  6242. function getMapData(map, key) {
  6243. var data = map.__data__;
  6244. return isKeyable(key)
  6245. ? data[typeof key == 'string' ? 'string' : 'hash']
  6246. : data.map;
  6247. }
  6248.  
  6249. /**
  6250. * Removes \`key\` and its value from the map.
  6251. *
  6252. * @private
  6253. * @name delete
  6254. * @memberOf MapCache
  6255. * @param {string} key The key of the value to remove.
  6256. * @returns {boolean} Returns \`true\` if the entry was removed, else \`false\`.
  6257. */
  6258. function mapCacheDelete(key) {
  6259. var result = getMapData(this, key)['delete'](key);
  6260. this.size -= result ? 1 : 0;
  6261. return result;
  6262. }
  6263.  
  6264. /**
  6265. * Gets the map value for \`key\`.
  6266. *
  6267. * @private
  6268. * @name get
  6269. * @memberOf MapCache
  6270. * @param {string} key The key of the value to get.
  6271. * @returns {*} Returns the entry value.
  6272. */
  6273. function mapCacheGet(key) {
  6274. return getMapData(this, key).get(key);
  6275. }
  6276.  
  6277. /**
  6278. * Checks if a map value for \`key\` exists.
  6279. *
  6280. * @private
  6281. * @name has
  6282. * @memberOf MapCache
  6283. * @param {string} key The key of the entry to check.
  6284. * @returns {boolean} Returns \`true\` if an entry for \`key\` exists, else \`false\`.
  6285. */
  6286. function mapCacheHas(key) {
  6287. return getMapData(this, key).has(key);
  6288. }
  6289.  
  6290. /**
  6291. * Sets the map \`key\` to \`value\`.
  6292. *
  6293. * @private
  6294. * @name set
  6295. * @memberOf MapCache
  6296. * @param {string} key The key of the value to set.
  6297. * @param {*} value The value to set.
  6298. * @returns {Object} Returns the map cache instance.
  6299. */
  6300. function mapCacheSet(key, value) {
  6301. var data = getMapData(this, key),
  6302. size = data.size;
  6303.  
  6304. data.set(key, value);
  6305. this.size += data.size == size ? 0 : 1;
  6306. return this;
  6307. }
  6308.  
  6309. /**
  6310. * Creates a map cache object to store key-value pairs.
  6311. *
  6312. * @private
  6313. * @constructor
  6314. * @param {Array} [entries] The key-value pairs to cache.
  6315. */
  6316. function MapCache(entries) {
  6317. var index = -1,
  6318. length = entries == null ? 0 : entries.length;
  6319.  
  6320. this.clear();
  6321. while (++index < length) {
  6322. var entry = entries[index];
  6323. this.set(entry[0], entry[1]);
  6324. }
  6325. }
  6326.  
  6327. // Add methods to \`MapCache\`.
  6328. MapCache.prototype.clear = mapCacheClear;
  6329. MapCache.prototype['delete'] = mapCacheDelete;
  6330. MapCache.prototype.get = mapCacheGet;
  6331. MapCache.prototype.has = mapCacheHas;
  6332. MapCache.prototype.set = mapCacheSet;
  6333.  
  6334. /** Error message constants. */
  6335. var FUNC_ERROR_TEXT = 'Expected a function';
  6336.  
  6337. /**
  6338. * Creates a function that memoizes the result of \`func\`. If \`resolver\` is
  6339. * provided, it determines the cache key for storing the result based on the
  6340. * arguments provided to the memoized function. By default, the first argument
  6341. * provided to the memoized function is used as the map cache key. The \`func\`
  6342. * is invoked with the \`this\` binding of the memoized function.
  6343. *
  6344. * **Note:** The cache is exposed as the \`cache\` property on the memoized
  6345. * function. Its creation may be customized by replacing the \`_.memoize.Cache\`
  6346. * constructor with one whose instances implement the
  6347. * [\`Map\`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  6348. * method interface of \`clear\`, \`delete\`, \`get\`, \`has\`, and \`set\`.
  6349. *
  6350. * @static
  6351. * @memberOf _
  6352. * @since 0.1.0
  6353. * @category Function
  6354. * @param {Function} func The function to have its output memoized.
  6355. * @param {Function} [resolver] The function to resolve the cache key.
  6356. * @returns {Function} Returns the new memoized function.
  6357. * @example
  6358. *
  6359. * var object = { 'a': 1, 'b': 2 };
  6360. * var other = { 'c': 3, 'd': 4 };
  6361. *
  6362. * var values = _.memoize(_.values);
  6363. * values(object);
  6364. * // => [1, 2]
  6365. *
  6366. * values(other);
  6367. * // => [3, 4]
  6368. *
  6369. * object.a = 2;
  6370. * values(object);
  6371. * // => [1, 2]
  6372. *
  6373. * // Modify the result cache.
  6374. * values.cache.set(object, ['a', 'b']);
  6375. * values(object);
  6376. * // => ['a', 'b']
  6377. *
  6378. * // Replace \`_.memoize.Cache\`.
  6379. * _.memoize.Cache = WeakMap;
  6380. */
  6381. function memoize(func, resolver) {
  6382. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  6383. throw new TypeError(FUNC_ERROR_TEXT);
  6384. }
  6385. var memoized = function() {
  6386. var args = arguments,
  6387. key = resolver ? resolver.apply(this, args) : args[0],
  6388. cache = memoized.cache;
  6389.  
  6390. if (cache.has(key)) {
  6391. return cache.get(key);
  6392. }
  6393. var result = func.apply(this, args);
  6394. memoized.cache = cache.set(key, result) || cache;
  6395. return result;
  6396. };
  6397. memoized.cache = new (memoize.Cache || MapCache);
  6398. return memoized;
  6399. }
  6400.  
  6401. // Expose \`MapCache\`.
  6402. memoize.Cache = MapCache;
  6403.  
  6404. const numberToByteArray = (num, byteLength = getNumberByteLength(num)) => {
  6405. var byteArray;
  6406. if (byteLength == 1) {
  6407. byteArray = new DataView(new ArrayBuffer(1));
  6408. byteArray.setUint8(0, num);
  6409. }
  6410. else if (byteLength == 2) {
  6411. byteArray = new DataView(new ArrayBuffer(2));
  6412. byteArray.setUint16(0, num);
  6413. }
  6414. else if (byteLength == 3) {
  6415. byteArray = new DataView(new ArrayBuffer(3));
  6416. byteArray.setUint8(0, num >> 16);
  6417. byteArray.setUint16(1, num & 0xffff);
  6418. }
  6419. else if (byteLength == 4) {
  6420. byteArray = new DataView(new ArrayBuffer(4));
  6421. byteArray.setUint32(0, num);
  6422. }
  6423. else if (num < 0xffffffff) {
  6424. byteArray = new DataView(new ArrayBuffer(5));
  6425. byteArray.setUint32(1, num);
  6426. }
  6427. else if (byteLength == 5) {
  6428. byteArray = new DataView(new ArrayBuffer(5));
  6429. byteArray.setUint8(0, num / 0x100000000 | 0);
  6430. byteArray.setUint32(1, num % 0x100000000);
  6431. }
  6432. else if (byteLength == 6) {
  6433. byteArray = new DataView(new ArrayBuffer(6));
  6434. byteArray.setUint16(0, num / 0x100000000 | 0);
  6435. byteArray.setUint32(2, num % 0x100000000);
  6436. }
  6437. else if (byteLength == 7) {
  6438. byteArray = new DataView(new ArrayBuffer(7));
  6439. byteArray.setUint8(0, num / 0x1000000000000 | 0);
  6440. byteArray.setUint16(1, num / 0x100000000 & 0xffff);
  6441. byteArray.setUint32(3, num % 0x100000000);
  6442. }
  6443. else if (byteLength == 8) {
  6444. byteArray = new DataView(new ArrayBuffer(8));
  6445. byteArray.setUint32(0, num / 0x100000000 | 0);
  6446. byteArray.setUint32(4, num % 0x100000000);
  6447. }
  6448. else {
  6449. throw new Error("EBML.typedArrayUtils.numberToByteArray: byte length must be less than or equal to 8");
  6450. }
  6451. return new Uint8Array(byteArray.buffer);
  6452. };
  6453. const stringToByteArray = memoize((str) => {
  6454. return Uint8Array.from(Array.from(str).map(_ => _.codePointAt(0)));
  6455. });
  6456. function getNumberByteLength(num) {
  6457. if (num < 0) {
  6458. throw new Error("EBML.typedArrayUtils.getNumberByteLength: negative number not implemented");
  6459. }
  6460. else if (num < 0x100) {
  6461. return 1;
  6462. }
  6463. else if (num < 0x10000) {
  6464. return 2;
  6465. }
  6466. else if (num < 0x1000000) {
  6467. return 3;
  6468. }
  6469. else if (num < 0x100000000) {
  6470. return 4;
  6471. }
  6472. else if (num < 0x10000000000) {
  6473. return 5;
  6474. }
  6475. else if (num < 0x1000000000000) {
  6476. return 6;
  6477. }
  6478. else if (num < 0x20000000000000) {
  6479. return 7;
  6480. }
  6481. else {
  6482. throw new Error("EBML.typedArrayUtils.getNumberByteLength: number exceeds Number.MAX_SAFE_INTEGER");
  6483. }
  6484. }
  6485. const int16Bit = memoize((num) => {
  6486. const ab = new ArrayBuffer(2);
  6487. new DataView(ab).setInt16(0, num);
  6488. return new Uint8Array(ab);
  6489. });
  6490. const float32bit = memoize((num) => {
  6491. const ab = new ArrayBuffer(4);
  6492. new DataView(ab).setFloat32(0, num);
  6493. return new Uint8Array(ab);
  6494. });
  6495. const dumpBytes = (b) => {
  6496. return Array.from(new Uint8Array(b)).map(_ => \`0x\${_.toString(16)}\`).join(", ");
  6497. };
  6498.  
  6499. class Value {
  6500. constructor(bytes) {
  6501. this.bytes = bytes;
  6502. }
  6503. write(buf, pos) {
  6504. buf.set(this.bytes, pos);
  6505. return pos + this.bytes.length;
  6506. }
  6507. countSize() {
  6508. return this.bytes.length;
  6509. }
  6510. }
  6511. class Element {
  6512. constructor(id, children, isSizeUnknown) {
  6513. this.id = id;
  6514. this.children = children;
  6515. const bodySize = this.children.reduce((p, c) => p + c.countSize(), 0);
  6516. this.sizeMetaData = isSizeUnknown ?
  6517. UNKNOWN_SIZE :
  6518. vintEncode(numberToByteArray(bodySize, getEBMLByteLength(bodySize)));
  6519. this.size = this.id.length + this.sizeMetaData.length + bodySize;
  6520. }
  6521. write(buf, pos) {
  6522. buf.set(this.id, pos);
  6523. buf.set(this.sizeMetaData, pos + this.id.length);
  6524. return this.children.reduce((p, c) => c.write(buf, p), pos + this.id.length + this.sizeMetaData.length);
  6525. }
  6526. countSize() {
  6527. return this.size;
  6528. }
  6529. }
  6530. const bytes = memoize((data) => {
  6531. return new Value(data);
  6532. });
  6533. const number = memoize((num) => {
  6534. return bytes(numberToByteArray(num));
  6535. });
  6536. const vintEncodedNumber = memoize((num) => {
  6537. return bytes(vintEncode(numberToByteArray(num, getEBMLByteLength(num))));
  6538. });
  6539. const int16 = memoize((num) => {
  6540. return bytes(int16Bit(num));
  6541. });
  6542. const float = memoize((num) => {
  6543. return bytes(float32bit(num));
  6544. });
  6545. const string = memoize((str) => {
  6546. return bytes(stringToByteArray(str));
  6547. });
  6548. const element = (id, child) => {
  6549. return new Element(id, Array.isArray(child) ? child : [child], false);
  6550. };
  6551. const unknownSizeElement = (id, child) => {
  6552. return new Element(id, Array.isArray(child) ? child : [child], true);
  6553. };
  6554. const build = (v) => {
  6555. const b = new Uint8Array(v.countSize());
  6556. v.write(b, 0);
  6557. return b;
  6558. };
  6559. const getEBMLByteLength = (num) => {
  6560. if (num < 0x7f) {
  6561. return 1;
  6562. }
  6563. else if (num < 0x3fff) {
  6564. return 2;
  6565. }
  6566. else if (num < 0x1fffff) {
  6567. return 3;
  6568. }
  6569. else if (num < 0xfffffff) {
  6570. return 4;
  6571. }
  6572. else if (num < 0x7ffffffff) {
  6573. return 5;
  6574. }
  6575. else if (num < 0x3ffffffffff) {
  6576. return 6;
  6577. }
  6578. else if (num < 0x1ffffffffffff) {
  6579. return 7;
  6580. }
  6581. else if (num < 0x20000000000000) {
  6582. return 8;
  6583. }
  6584. else if (num < 0xffffffffffffff) {
  6585. throw new Error("EBMLgetEBMLByteLength: number exceeds Number.MAX_SAFE_INTEGER");
  6586. }
  6587. else {
  6588. throw new Error("EBMLgetEBMLByteLength: data size must be less than or equal to " + (Math.pow(2, 56) - 2));
  6589. }
  6590. };
  6591. const UNKNOWN_SIZE = new Uint8Array([0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
  6592. const vintEncode = (byteArray) => {
  6593. byteArray[0] = getSizeMask(byteArray.length) | byteArray[0];
  6594. return byteArray;
  6595. };
  6596. const getSizeMask = (byteLength) => {
  6597. return 0x80 >> (byteLength - 1);
  6598. };
  6599.  
  6600. /**
  6601. * @see https://www.matroska.org/technical/specs/index.html
  6602. */
  6603. const ID = {
  6604. EBML: Uint8Array.of(0x1A, 0x45, 0xDF, 0xA3),
  6605. EBMLVersion: Uint8Array.of(0x42, 0x86),
  6606. EBMLReadVersion: Uint8Array.of(0x42, 0xF7),
  6607. EBMLMaxIDLength: Uint8Array.of(0x42, 0xF2),
  6608. EBMLMaxSizeLength: Uint8Array.of(0x42, 0xF3),
  6609. DocType: Uint8Array.of(0x42, 0x82),
  6610. DocTypeVersion: Uint8Array.of(0x42, 0x87),
  6611. DocTypeReadVersion: Uint8Array.of(0x42, 0x85),
  6612. Void: Uint8Array.of(0xEC),
  6613. CRC32: Uint8Array.of(0xBF),
  6614. Segment: Uint8Array.of(0x18, 0x53, 0x80, 0x67),
  6615. SeekHead: Uint8Array.of(0x11, 0x4D, 0x9B, 0x74),
  6616. Seek: Uint8Array.of(0x4D, 0xBB),
  6617. SeekID: Uint8Array.of(0x53, 0xAB),
  6618. SeekPosition: Uint8Array.of(0x53, 0xAC),
  6619. Info: Uint8Array.of(0x15, 0x49, 0xA9, 0x66),
  6620. SegmentUID: Uint8Array.of(0x73, 0xA4),
  6621. SegmentFilename: Uint8Array.of(0x73, 0x84),
  6622. PrevUID: Uint8Array.of(0x3C, 0xB9, 0x23),
  6623. PrevFilename: Uint8Array.of(0x3C, 0x83, 0xAB),
  6624. NextUID: Uint8Array.of(0x3E, 0xB9, 0x23),
  6625. NextFilename: Uint8Array.of(0x3E, 0x83, 0xBB),
  6626. SegmentFamily: Uint8Array.of(0x44, 0x44),
  6627. ChapterTranslate: Uint8Array.of(0x69, 0x24),
  6628. ChapterTranslateEditionUID: Uint8Array.of(0x69, 0xFC),
  6629. ChapterTranslateCodec: Uint8Array.of(0x69, 0xBF),
  6630. ChapterTranslateID: Uint8Array.of(0x69, 0xA5),
  6631. TimecodeScale: Uint8Array.of(0x2A, 0xD7, 0xB1),
  6632. Duration: Uint8Array.of(0x44, 0x89),
  6633. DateUTC: Uint8Array.of(0x44, 0x61),
  6634. Title: Uint8Array.of(0x7B, 0xA9),
  6635. MuxingApp: Uint8Array.of(0x4D, 0x80),
  6636. WritingApp: Uint8Array.of(0x57, 0x41),
  6637. Cluster: Uint8Array.of(0x1F, 0x43, 0xB6, 0x75),
  6638. Timecode: Uint8Array.of(0xE7),
  6639. SilentTracks: Uint8Array.of(0x58, 0x54),
  6640. SilentTrackNumber: Uint8Array.of(0x58, 0xD7),
  6641. Position: Uint8Array.of(0xA7),
  6642. PrevSize: Uint8Array.of(0xAB),
  6643. SimpleBlock: Uint8Array.of(0xA3),
  6644. BlockGroup: Uint8Array.of(0xA0),
  6645. Block: Uint8Array.of(0xA1),
  6646. BlockAdditions: Uint8Array.of(0x75, 0xA1),
  6647. BlockMore: Uint8Array.of(0xA6),
  6648. BlockAddID: Uint8Array.of(0xEE),
  6649. BlockAdditional: Uint8Array.of(0xA5),
  6650. BlockDuration: Uint8Array.of(0x9B),
  6651. ReferencePriority: Uint8Array.of(0xFA),
  6652. ReferenceBlock: Uint8Array.of(0xFB),
  6653. CodecState: Uint8Array.of(0xA4),
  6654. DiscardPadding: Uint8Array.of(0x75, 0xA2),
  6655. Slices: Uint8Array.of(0x8E),
  6656. TimeSlice: Uint8Array.of(0xE8),
  6657. LaceNumber: Uint8Array.of(0xCC),
  6658. Tracks: Uint8Array.of(0x16, 0x54, 0xAE, 0x6B),
  6659. TrackEntry: Uint8Array.of(0xAE),
  6660. TrackNumber: Uint8Array.of(0xD7),
  6661. TrackUID: Uint8Array.of(0x73, 0xC5),
  6662. TrackType: Uint8Array.of(0x83),
  6663. FlagEnabled: Uint8Array.of(0xB9),
  6664. FlagDefault: Uint8Array.of(0x88),
  6665. FlagForced: Uint8Array.of(0x55, 0xAA),
  6666. FlagLacing: Uint8Array.of(0x9C),
  6667. MinCache: Uint8Array.of(0x6D, 0xE7),
  6668. MaxCache: Uint8Array.of(0x6D, 0xF8),
  6669. DefaultDuration: Uint8Array.of(0x23, 0xE3, 0x83),
  6670. DefaultDecodedFieldDuration: Uint8Array.of(0x23, 0x4E, 0x7A),
  6671. MaxBlockAdditionID: Uint8Array.of(0x55, 0xEE),
  6672. Name: Uint8Array.of(0x53, 0x6E),
  6673. Language: Uint8Array.of(0x22, 0xB5, 0x9C),
  6674. CodecID: Uint8Array.of(0x86),
  6675. CodecPrivate: Uint8Array.of(0x63, 0xA2),
  6676. CodecName: Uint8Array.of(0x25, 0x86, 0x88),
  6677. AttachmentLink: Uint8Array.of(0x74, 0x46),
  6678. CodecDecodeAll: Uint8Array.of(0xAA),
  6679. TrackOverlay: Uint8Array.of(0x6F, 0xAB),
  6680. CodecDelay: Uint8Array.of(0x56, 0xAA),
  6681. SeekPreRoll: Uint8Array.of(0x56, 0xBB),
  6682. TrackTranslate: Uint8Array.of(0x66, 0x24),
  6683. TrackTranslateEditionUID: Uint8Array.of(0x66, 0xFC),
  6684. TrackTranslateCodec: Uint8Array.of(0x66, 0xBF),
  6685. TrackTranslateTrackID: Uint8Array.of(0x66, 0xA5),
  6686. Video: Uint8Array.of(0xE0),
  6687. FlagInterlaced: Uint8Array.of(0x9A),
  6688. FieldOrder: Uint8Array.of(0x9D),
  6689. StereoMode: Uint8Array.of(0x53, 0xB8),
  6690. AlphaMode: Uint8Array.of(0x53, 0xC0),
  6691. PixelWidth: Uint8Array.of(0xB0),
  6692. PixelHeight: Uint8Array.of(0xBA),
  6693. PixelCropBottom: Uint8Array.of(0x54, 0xAA),
  6694. PixelCropTop: Uint8Array.of(0x54, 0xBB),
  6695. PixelCropLeft: Uint8Array.of(0x54, 0xCC),
  6696. PixelCropRight: Uint8Array.of(0x54, 0xDD),
  6697. DisplayWidth: Uint8Array.of(0x54, 0xB0),
  6698. DisplayHeight: Uint8Array.of(0x54, 0xBA),
  6699. DisplayUnit: Uint8Array.of(0x54, 0xB2),
  6700. AspectRatioType: Uint8Array.of(0x54, 0xB3),
  6701. ColourSpace: Uint8Array.of(0x2E, 0xB5, 0x24),
  6702. Colour: Uint8Array.of(0x55, 0xB0),
  6703. MatrixCoefficients: Uint8Array.of(0x55, 0xB1),
  6704. BitsPerChannel: Uint8Array.of(0x55, 0xB2),
  6705. ChromaSubsamplingHorz: Uint8Array.of(0x55, 0xB3),
  6706. ChromaSubsamplingVert: Uint8Array.of(0x55, 0xB4),
  6707. CbSubsamplingHorz: Uint8Array.of(0x55, 0xB5),
  6708. CbSubsamplingVert: Uint8Array.of(0x55, 0xB6),
  6709. ChromaSitingHorz: Uint8Array.of(0x55, 0xB7),
  6710. ChromaSitingVert: Uint8Array.of(0x55, 0xB8),
  6711. Range: Uint8Array.of(0x55, 0xB9),
  6712. TransferCharacteristics: Uint8Array.of(0x55, 0xBA),
  6713. Primaries: Uint8Array.of(0x55, 0xBB),
  6714. MaxCLL: Uint8Array.of(0x55, 0xBC),
  6715. MaxFALL: Uint8Array.of(0x55, 0xBD),
  6716. MasteringMetadata: Uint8Array.of(0x55, 0xD0),
  6717. PrimaryRChromaticityX: Uint8Array.of(0x55, 0xD1),
  6718. PrimaryRChromaticityY: Uint8Array.of(0x55, 0xD2),
  6719. PrimaryGChromaticityX: Uint8Array.of(0x55, 0xD3),
  6720. PrimaryGChromaticityY: Uint8Array.of(0x55, 0xD4),
  6721. PrimaryBChromaticityX: Uint8Array.of(0x55, 0xD5),
  6722. PrimaryBChromaticityY: Uint8Array.of(0x55, 0xD6),
  6723. WhitePointChromaticityX: Uint8Array.of(0x55, 0xD7),
  6724. WhitePointChromaticityY: Uint8Array.of(0x55, 0xD8),
  6725. LuminanceMax: Uint8Array.of(0x55, 0xD9),
  6726. LuminanceMin: Uint8Array.of(0x55, 0xDA),
  6727. Audio: Uint8Array.of(0xE1),
  6728. SamplingFrequency: Uint8Array.of(0xB5),
  6729. OutputSamplingFrequency: Uint8Array.of(0x78, 0xB5),
  6730. Channels: Uint8Array.of(0x9F),
  6731. BitDepth: Uint8Array.of(0x62, 0x64),
  6732. TrackOperation: Uint8Array.of(0xE2),
  6733. TrackCombinePlanes: Uint8Array.of(0xE3),
  6734. TrackPlane: Uint8Array.of(0xE4),
  6735. TrackPlaneUID: Uint8Array.of(0xE5),
  6736. TrackPlaneType: Uint8Array.of(0xE6),
  6737. TrackJoinBlocks: Uint8Array.of(0xE9),
  6738. TrackJoinUID: Uint8Array.of(0xED),
  6739. ContentEncodings: Uint8Array.of(0x6D, 0x80),
  6740. ContentEncoding: Uint8Array.of(0x62, 0x40),
  6741. ContentEncodingOrder: Uint8Array.of(0x50, 0x31),
  6742. ContentEncodingScope: Uint8Array.of(0x50, 0x32),
  6743. ContentEncodingType: Uint8Array.of(0x50, 0x33),
  6744. ContentCompression: Uint8Array.of(0x50, 0x34),
  6745. ContentCompAlgo: Uint8Array.of(0x42, 0x54),
  6746. ContentCompSettings: Uint8Array.of(0x42, 0x55),
  6747. ContentEncryption: Uint8Array.of(0x50, 0x35),
  6748. ContentEncAlgo: Uint8Array.of(0x47, 0xE1),
  6749. ContentEncKeyID: Uint8Array.of(0x47, 0xE2),
  6750. ContentSignature: Uint8Array.of(0x47, 0xE3),
  6751. ContentSigKeyID: Uint8Array.of(0x47, 0xE4),
  6752. ContentSigAlgo: Uint8Array.of(0x47, 0xE5),
  6753. ContentSigHashAlgo: Uint8Array.of(0x47, 0xE6),
  6754. Cues: Uint8Array.of(0x1C, 0x53, 0xBB, 0x6B),
  6755. CuePoint: Uint8Array.of(0xBB),
  6756. CueTime: Uint8Array.of(0xB3),
  6757. CueTrackPositions: Uint8Array.of(0xB7),
  6758. CueTrack: Uint8Array.of(0xF7),
  6759. CueClusterPosition: Uint8Array.of(0xF1),
  6760. CueRelativePosition: Uint8Array.of(0xF0),
  6761. CueDuration: Uint8Array.of(0xB2),
  6762. CueBlockNumber: Uint8Array.of(0x53, 0x78),
  6763. CueCodecState: Uint8Array.of(0xEA),
  6764. CueReference: Uint8Array.of(0xDB),
  6765. CueRefTime: Uint8Array.of(0x96),
  6766. Attachments: Uint8Array.of(0x19, 0x41, 0xA4, 0x69),
  6767. AttachedFile: Uint8Array.of(0x61, 0xA7),
  6768. FileDescription: Uint8Array.of(0x46, 0x7E),
  6769. FileName: Uint8Array.of(0x46, 0x6E),
  6770. FileMimeType: Uint8Array.of(0x46, 0x60),
  6771. FileData: Uint8Array.of(0x46, 0x5C),
  6772. FileUID: Uint8Array.of(0x46, 0xAE),
  6773. Chapters: Uint8Array.of(0x10, 0x43, 0xA7, 0x70),
  6774. EditionEntry: Uint8Array.of(0x45, 0xB9),
  6775. EditionUID: Uint8Array.of(0x45, 0xBC),
  6776. EditionFlagHidden: Uint8Array.of(0x45, 0xBD),
  6777. EditionFlagDefault: Uint8Array.of(0x45, 0xDB),
  6778. EditionFlagOrdered: Uint8Array.of(0x45, 0xDD),
  6779. ChapterAtom: Uint8Array.of(0xB6),
  6780. ChapterUID: Uint8Array.of(0x73, 0xC4),
  6781. ChapterStringUID: Uint8Array.of(0x56, 0x54),
  6782. ChapterTimeStart: Uint8Array.of(0x91),
  6783. ChapterTimeEnd: Uint8Array.of(0x92),
  6784. ChapterFlagHidden: Uint8Array.of(0x98),
  6785. ChapterFlagEnabled: Uint8Array.of(0x45, 0x98),
  6786. ChapterSegmentUID: Uint8Array.of(0x6E, 0x67),
  6787. ChapterSegmentEditionUID: Uint8Array.of(0x6E, 0xBC),
  6788. ChapterPhysicalEquiv: Uint8Array.of(0x63, 0xC3),
  6789. ChapterTrack: Uint8Array.of(0x8F),
  6790. ChapterTrackNumber: Uint8Array.of(0x89),
  6791. ChapterDisplay: Uint8Array.of(0x80),
  6792. ChapString: Uint8Array.of(0x85),
  6793. ChapLanguage: Uint8Array.of(0x43, 0x7C),
  6794. ChapCountry: Uint8Array.of(0x43, 0x7E),
  6795. ChapProcess: Uint8Array.of(0x69, 0x44),
  6796. ChapProcessCodecID: Uint8Array.of(0x69, 0x55),
  6797. ChapProcessPrivate: Uint8Array.of(0x45, 0x0D),
  6798. ChapProcessCommand: Uint8Array.of(0x69, 0x11),
  6799. ChapProcessTime: Uint8Array.of(0x69, 0x22),
  6800. ChapProcessData: Uint8Array.of(0x69, 0x33),
  6801. Tags: Uint8Array.of(0x12, 0x54, 0xC3, 0x67),
  6802. Tag: Uint8Array.of(0x73, 0x73),
  6803. Targets: Uint8Array.of(0x63, 0xC0),
  6804. TargetTypeValue: Uint8Array.of(0x68, 0xCA),
  6805. TargetType: Uint8Array.of(0x63, 0xCA),
  6806. TagTrackUID: Uint8Array.of(0x63, 0xC5),
  6807. TagEditionUID: Uint8Array.of(0x63, 0xC9),
  6808. TagChapterUID: Uint8Array.of(0x63, 0xC4),
  6809. TagAttachmentUID: Uint8Array.of(0x63, 0xC6),
  6810. SimpleTag: Uint8Array.of(0x67, 0xC8),
  6811. TagName: Uint8Array.of(0x45, 0xA3),
  6812. TagLanguage: Uint8Array.of(0x44, 0x7A),
  6813. TagDefault: Uint8Array.of(0x44, 0x84),
  6814. TagString: Uint8Array.of(0x44, 0x87),
  6815. TagBinary: Uint8Array.of(0x44, 0x85),
  6816. };
  6817.  
  6818.  
  6819.  
  6820. var EBML = /*#__PURE__*/Object.freeze({
  6821. Value: Value,
  6822. Element: Element,
  6823. bytes: bytes,
  6824. number: number,
  6825. vintEncodedNumber: vintEncodedNumber,
  6826. int16: int16,
  6827. float: float,
  6828. string: string,
  6829. element: element,
  6830. unknownSizeElement: unknownSizeElement,
  6831. build: build,
  6832. getEBMLByteLength: getEBMLByteLength,
  6833. UNKNOWN_SIZE: UNKNOWN_SIZE,
  6834. vintEncode: vintEncode,
  6835. getSizeMask: getSizeMask,
  6836. ID: ID,
  6837. numberToByteArray: numberToByteArray,
  6838. stringToByteArray: stringToByteArray,
  6839. getNumberByteLength: getNumberByteLength,
  6840. int16Bit: int16Bit,
  6841. float32bit: float32bit,
  6842. dumpBytes: dumpBytes
  6843. });
  6844.  
  6845. /***
  6846. * The EMBL builder is from simple-ebml-builder
  6847. *
  6848. * Copyright 2017 ryiwamoto
  6849. *
  6850. * @author ryiwamoto, qli5
  6851. *
  6852. * Permission is hereby granted, free of charge, to any person obtaining
  6853. * a copy of this software and associated documentation files (the
  6854. * "Software"), to deal in the Software without restriction, including
  6855. * without limitation the rights to use, copy, modify, merge, publish,
  6856. * distribute, sublicense, and/or sell copies of the Software, and to
  6857. * permit persons to whom the Software is furnished to do so, subject
  6858. * to the following conditions:
  6859. *
  6860. * The above copyright notice and this permission notice shall be
  6861. * included in all copies or substantial portions of the Software.
  6862. *
  6863. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  6864. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  6865. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  6866. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  6867. * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  6868. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  6869. * DEALINGS IN THE SOFTWARE.
  6870. */
  6871.  
  6872. /***
  6873. * Copyright (C) 2018 Qli5. All Rights Reserved.
  6874. *
  6875. * @author qli5 <goodlq11[at](163|gmail).com>
  6876. *
  6877. * This Source Code Form is subject to the terms of the Mozilla Public
  6878. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6879. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6880. */
  6881.  
  6882. /**
  6883. * @typedef {Object} AssBlock
  6884. * @property {number} track
  6885. * @property {Uint8Array} frame
  6886. * @property {number} timestamp
  6887. * @property {number} duration
  6888. */
  6889.  
  6890. class MKV {
  6891. constructor(config) {
  6892. this.min = true;
  6893. this.onprogress = null;
  6894. Object.assign(this, config);
  6895. this.segmentUID = MKV.randomBytes(16);
  6896. this.trackUIDBase = Math.trunc(Math.random() * 2 ** 16);
  6897. this.trackMetadata = { h264: null, aac: null, assList: [] };
  6898. this.duration = 0;
  6899. /** @type {{ h264: any[]; aac: any[]; assList: AssBlock[][]; }} */
  6900. this.blocks = { h264: [], aac: [], assList: [] };
  6901. }
  6902.  
  6903. static randomBytes(num) {
  6904. return Array.from(new Array(num), () => Math.trunc(Math.random() * 256));
  6905. }
  6906.  
  6907. static textToMS(str) {
  6908. const [, h, mm, ss, ms10] = str.match(/(\\d+):(\\d+):(\\d+).(\\d+)/);
  6909. return h * 3600000 + mm * 60000 + ss * 1000 + ms10 * 10;
  6910. }
  6911.  
  6912. static mimeToCodecID(str) {
  6913. if (str.startsWith('avc1')) {
  6914. return 'V_MPEG4/ISO/AVC';
  6915. }
  6916. else if (str.startsWith('mp4a')) {
  6917. return 'A_AAC';
  6918. }
  6919. else {
  6920. throw new Error(\`MKVRemuxer: unknown codec \${str}\`);
  6921. }
  6922. }
  6923.  
  6924. static uint8ArrayConcat(...array) {
  6925. // if (Array.isArray(array[0])) array = array[0];
  6926. if (array.length == 1) return array[0];
  6927. if (typeof Buffer != 'undefined') return Buffer.concat(array);
  6928. const ret = new Uint8Array(array.reduce((i, j) => i + j.byteLength, 0));
  6929. let length = 0;
  6930. for (let e of array) {
  6931. ret.set(e, length);
  6932. length += e.byteLength;
  6933. }
  6934. return ret;
  6935. }
  6936.  
  6937. addH264Metadata(h264) {
  6938. this.trackMetadata.h264 = {
  6939. codecId: MKV.mimeToCodecID(h264.codec),
  6940. codecPrivate: h264.avcc,
  6941. defaultDuration: h264.refSampleDuration * 1000000,
  6942. pixelWidth: h264.codecWidth,
  6943. pixelHeight: h264.codecHeight,
  6944. displayWidth: h264.presentWidth,
  6945. displayHeight: h264.presentHeight
  6946. };
  6947. this.duration = Math.max(this.duration, h264.duration);
  6948. }
  6949.  
  6950. addAACMetadata(aac) {
  6951. this.trackMetadata.aac = {
  6952. codecId: MKV.mimeToCodecID(aac.originalCodec),
  6953. codecPrivate: aac.configRaw,
  6954. defaultDuration: aac.refSampleDuration * 1000000,
  6955. samplingFrequence: aac.audioSampleRate,
  6956. channels: aac.channelCount
  6957. };
  6958. this.duration = Math.max(this.duration, aac.duration);
  6959. }
  6960.  
  6961. /**
  6962. * @param {import("../demuxer/ass").ASS} ass
  6963. * @param {string} name
  6964. */
  6965. addASSMetadata(ass, name = "") {
  6966. this.trackMetadata.assList.push({
  6967. codecId: 'S_TEXT/ASS',
  6968. codecPrivate: new _TextEncoder().encode(ass.header),
  6969. name,
  6970. _info: ass.info,
  6971. _styles: ass.styles,
  6972. });
  6973. }
  6974.  
  6975. addH264Stream(h264) {
  6976. this.blocks.h264 = this.blocks.h264.concat(h264.samples.map(e => ({
  6977. track: 1,
  6978. frame: MKV.uint8ArrayConcat(...e.units.map(i => i.data)),
  6979. isKeyframe: e.isKeyframe,
  6980. discardable: Boolean(e.refIdc),
  6981. timestamp: e.pts,
  6982. simple: true,
  6983. })));
  6984. }
  6985.  
  6986. addAACStream(aac) {
  6987. this.blocks.aac = this.blocks.aac.concat(aac.samples.map(e => ({
  6988. track: 2,
  6989. frame: e.unit,
  6990. timestamp: e.pts,
  6991. simple: true,
  6992. })));
  6993. }
  6994.  
  6995. /**
  6996. * @param {import("../demuxer/ass").ASS} ass
  6997. */
  6998. addASSStream(ass) {
  6999. const n = this.blocks.assList.length;
  7000. const lineBlocks = ass.lines.map((e, i) => ({
  7001. track: 3 + n,
  7002. frame: new _TextEncoder().encode(\`\${i},\${e['Layer'] || ''},\${e['Style'] || ''},\${e['Name'] || ''},\${e['MarginL'] || ''},\${e['MarginR'] || ''},\${e['MarginV'] || ''},\${e['Effect'] || ''},\${e['Text'] || ''}\`),
  7003. timestamp: MKV.textToMS(e['Start']),
  7004. duration: MKV.textToMS(e['End']) - MKV.textToMS(e['Start']),
  7005. }));
  7006. this.blocks.assList.push(lineBlocks);
  7007. }
  7008.  
  7009. combineSubtitles() {
  7010. const [firstB, ...restB] = this.blocks.assList;
  7011. const l = Math.min(this.blocks.assList.length, this.trackMetadata.assList.length);
  7012. /**
  7013. * @param {AssBlock} a
  7014. * @param {AssBlock} b
  7015. */
  7016. const sortFn = (a, b) => {
  7017. return a.timestamp - b.timestamp
  7018. };
  7019. restB.forEach((a, n) => {
  7020. this.blocks.assList.push(
  7021. a.concat(firstB).sort(sortFn).map((x) => {
  7022. return {
  7023. track: 3 + l + n,
  7024. frame: x.frame,
  7025. timestamp: x.timestamp,
  7026. duration: x.duration,
  7027. }
  7028. })
  7029. );
  7030. });
  7031. const [firstM, ...restM] = this.trackMetadata.assList;
  7032. restM.forEach((a) => {
  7033. const name = \`\${firstM.name} + \${a.name}\`;
  7034. const info = firstM._info.replace(/^(Title:.+)\$/m, \`\$1 \${name}\`);
  7035. const firstStyles = firstM._styles.split(/\\r?\\n+/).filter(x => !!x);
  7036. const aStyles = a._styles.split(/\\r?\\n+/).slice(2);
  7037. const styles = firstStyles.concat(aStyles).join("\\r\\n");
  7038. const header = info + styles;
  7039. this.trackMetadata.assList.push({
  7040. name: name,
  7041. codecId: 'S_TEXT/ASS',
  7042. codecPrivate: new _TextEncoder().encode(header),
  7043. });
  7044. });
  7045. }
  7046.  
  7047. build() {
  7048. return new _Blob([
  7049. this.buildHeader(),
  7050. this.buildBody()
  7051. ]);
  7052. }
  7053.  
  7054. buildHeader() {
  7055. return new _Blob([EBML.build(EBML.element(EBML.ID.EBML, [
  7056. EBML.element(EBML.ID.EBMLVersion, EBML.number(1)),
  7057. EBML.element(EBML.ID.EBMLReadVersion, EBML.number(1)),
  7058. EBML.element(EBML.ID.EBMLMaxIDLength, EBML.number(4)),
  7059. EBML.element(EBML.ID.EBMLMaxSizeLength, EBML.number(8)),
  7060. EBML.element(EBML.ID.DocType, EBML.string('matroska')),
  7061. EBML.element(EBML.ID.DocTypeVersion, EBML.number(4)),
  7062. EBML.element(EBML.ID.DocTypeReadVersion, EBML.number(2)),
  7063. ]))]);
  7064. }
  7065.  
  7066. buildBody() {
  7067. if (this.min) {
  7068. return new _Blob([EBML.build(EBML.element(EBML.ID.Segment, [
  7069. this.getSegmentInfo(),
  7070. this.getTracks(),
  7071. ...this.getClusterArray()
  7072. ]))]);
  7073. }
  7074. else {
  7075. return new _Blob([EBML.build(EBML.element(EBML.ID.Segment, [
  7076. this.getSeekHead(),
  7077. this.getVoid(4100),
  7078. this.getSegmentInfo(),
  7079. this.getTracks(),
  7080. this.getVoid(1100),
  7081. ...this.getClusterArray()
  7082. ]))]);
  7083. }
  7084. }
  7085.  
  7086. getSeekHead() {
  7087. return EBML.element(EBML.ID.SeekHead, [
  7088. EBML.element(EBML.ID.Seek, [
  7089. EBML.element(EBML.ID.SeekID, EBML.bytes(EBML.ID.Info)),
  7090. EBML.element(EBML.ID.SeekPosition, EBML.number(4050))
  7091. ]),
  7092. EBML.element(EBML.ID.Seek, [
  7093. EBML.element(EBML.ID.SeekID, EBML.bytes(EBML.ID.Tracks)),
  7094. EBML.element(EBML.ID.SeekPosition, EBML.number(4200))
  7095. ]),
  7096. ]);
  7097. }
  7098.  
  7099. getVoid(length = 2000) {
  7100. return EBML.element(EBML.ID.Void, EBML.bytes(new Uint8Array(length)));
  7101. }
  7102.  
  7103. getSegmentInfo() {
  7104. return EBML.element(EBML.ID.Info, [
  7105. EBML.element(EBML.ID.TimecodeScale, EBML.number(1000000)),
  7106. EBML.element(EBML.ID.MuxingApp, EBML.string('flv.js + assparser_qli5 -> simple-ebml-builder')),
  7107. EBML.element(EBML.ID.WritingApp, EBML.string('flvass2mkv.js by qli5')),
  7108. EBML.element(EBML.ID.Duration, EBML.float(this.duration)),
  7109. EBML.element(EBML.ID.SegmentUID, EBML.bytes(this.segmentUID)),
  7110. ]);
  7111. }
  7112.  
  7113. getTracks() {
  7114. return EBML.element(EBML.ID.Tracks, [
  7115. this.getVideoTrackEntry(),
  7116. this.getAudioTrackEntry(),
  7117. ...this.getSubtitleTrackEntry(),
  7118. ]);
  7119. }
  7120.  
  7121. getVideoTrackEntry() {
  7122. return EBML.element(EBML.ID.TrackEntry, [
  7123. EBML.element(EBML.ID.TrackNumber, EBML.number(1)),
  7124. EBML.element(EBML.ID.TrackUID, EBML.number(this.trackUIDBase + 1)),
  7125. EBML.element(EBML.ID.TrackType, EBML.number(0x01)),
  7126. EBML.element(EBML.ID.FlagLacing, EBML.number(0x00)),
  7127. EBML.element(EBML.ID.CodecID, EBML.string(this.trackMetadata.h264.codecId)),
  7128. EBML.element(EBML.ID.CodecPrivate, EBML.bytes(this.trackMetadata.h264.codecPrivate)),
  7129. EBML.element(EBML.ID.DefaultDuration, EBML.number(this.trackMetadata.h264.defaultDuration)),
  7130. EBML.element(EBML.ID.Language, EBML.string('und')),
  7131. EBML.element(EBML.ID.Video, [
  7132. EBML.element(EBML.ID.PixelWidth, EBML.number(this.trackMetadata.h264.pixelWidth)),
  7133. EBML.element(EBML.ID.PixelHeight, EBML.number(this.trackMetadata.h264.pixelHeight)),
  7134. EBML.element(EBML.ID.DisplayWidth, EBML.number(this.trackMetadata.h264.displayWidth)),
  7135. EBML.element(EBML.ID.DisplayHeight, EBML.number(this.trackMetadata.h264.displayHeight)),
  7136. ]),
  7137. ]);
  7138. }
  7139.  
  7140. getAudioTrackEntry() {
  7141. return EBML.element(EBML.ID.TrackEntry, [
  7142. EBML.element(EBML.ID.TrackNumber, EBML.number(2)),
  7143. EBML.element(EBML.ID.TrackUID, EBML.number(this.trackUIDBase + 2)),
  7144. EBML.element(EBML.ID.TrackType, EBML.number(0x02)),
  7145. EBML.element(EBML.ID.FlagLacing, EBML.number(0x00)),
  7146. EBML.element(EBML.ID.CodecID, EBML.string(this.trackMetadata.aac.codecId)),
  7147. EBML.element(EBML.ID.CodecPrivate, EBML.bytes(this.trackMetadata.aac.codecPrivate)),
  7148. EBML.element(EBML.ID.DefaultDuration, EBML.number(this.trackMetadata.aac.defaultDuration)),
  7149. EBML.element(EBML.ID.Language, EBML.string('und')),
  7150. EBML.element(EBML.ID.Audio, [
  7151. EBML.element(EBML.ID.SamplingFrequency, EBML.float(this.trackMetadata.aac.samplingFrequence)),
  7152. EBML.element(EBML.ID.Channels, EBML.number(this.trackMetadata.aac.channels)),
  7153. ]),
  7154. ]);
  7155. }
  7156.  
  7157. getSubtitleTrackEntry() {
  7158. return this.trackMetadata.assList.map((ass, i) => {
  7159. return EBML.element(EBML.ID.TrackEntry, [
  7160. EBML.element(EBML.ID.TrackNumber, EBML.number(3 + i)),
  7161. EBML.element(EBML.ID.TrackUID, EBML.number(this.trackUIDBase + 3 + i)),
  7162. EBML.element(EBML.ID.TrackType, EBML.number(0x11)),
  7163. EBML.element(EBML.ID.FlagLacing, EBML.number(0x00)),
  7164. EBML.element(EBML.ID.CodecID, EBML.string(ass.codecId)),
  7165. EBML.element(EBML.ID.CodecPrivate, EBML.bytes(ass.codecPrivate)),
  7166. EBML.element(EBML.ID.Language, EBML.string('und')),
  7167. ass.name && EBML.element(EBML.ID.Name, EBML.bytes(new _TextEncoder().encode(ass.name))),
  7168. ].filter(x => !!x));
  7169. });
  7170. }
  7171.  
  7172. getClusterArray() {
  7173. // H264 codecState
  7174. this.blocks.h264[0].simple = false;
  7175. this.blocks.h264[0].codecState = this.trackMetadata.h264.codecPrivate;
  7176.  
  7177. let i = 0;
  7178. let j = 0;
  7179. let k = Array.from({ length: this.blocks.assList.length }).fill(0);
  7180. let clusterTimeCode = 0;
  7181. let clusterContent = [EBML.element(EBML.ID.Timecode, EBML.number(clusterTimeCode))];
  7182. let ret = [clusterContent];
  7183. const progressThrottler = Math.pow(2, Math.floor(Math.log(this.blocks.h264.length >> 7) / Math.log(2))) - 1;
  7184. for (i = 0; i < this.blocks.h264.length; i++) {
  7185. const e = this.blocks.h264[i];
  7186. for (; j < this.blocks.aac.length; j++) {
  7187. if (this.blocks.aac[j].timestamp < e.timestamp) {
  7188. clusterContent.push(this.getBlocks(this.blocks.aac[j], clusterTimeCode));
  7189. }
  7190. else {
  7191. break;
  7192. }
  7193. }
  7194. this.blocks.assList.forEach((ass, n) => {
  7195. for (; k[n] < ass.length; k[n]++) {
  7196. if (ass[k[n]].timestamp < e.timestamp) {
  7197. clusterContent.push(this.getBlocks(ass[k[n]], clusterTimeCode));
  7198. }
  7199. else {
  7200. break;
  7201. }
  7202. }
  7203. });
  7204. if (e.isKeyframe/* || clusterContent.length > 72 */) {
  7205. // start new cluster
  7206. clusterTimeCode = e.timestamp;
  7207. clusterContent = [EBML.element(EBML.ID.Timecode, EBML.number(clusterTimeCode))];
  7208. ret.push(clusterContent);
  7209. }
  7210. clusterContent.push(this.getBlocks(e, clusterTimeCode));
  7211. if (this.onprogress && !(i & progressThrottler)) this.onprogress({ loaded: i, total: this.blocks.h264.length });
  7212. }
  7213. for (; j < this.blocks.aac.length; j++) clusterContent.push(this.getBlocks(this.blocks.aac[j], clusterTimeCode));
  7214. this.blocks.assList.forEach((ass, n) => {
  7215. for (; k[n] < ass.length; k[n]++) clusterContent.push(this.getBlocks(ass[k[n]], clusterTimeCode));
  7216. });
  7217. if (this.onprogress) this.onprogress({ loaded: i, total: this.blocks.h264.length });
  7218. if (ret[0].length == 1) ret.shift();
  7219. ret = ret.map(clusterContent => EBML.element(EBML.ID.Cluster, clusterContent));
  7220.  
  7221. return ret;
  7222. }
  7223.  
  7224. getBlocks(e, clusterTimeCode) {
  7225. if (e.simple) {
  7226. return EBML.element(EBML.ID.SimpleBlock, [
  7227. EBML.vintEncodedNumber(e.track),
  7228. EBML.int16(e.timestamp - clusterTimeCode),
  7229. EBML.bytes(e.isKeyframe ? [128] : [0]),
  7230. EBML.bytes(e.frame)
  7231. ]);
  7232. }
  7233. else {
  7234. let blockGroupContent = [EBML.element(EBML.ID.Block, [
  7235. EBML.vintEncodedNumber(e.track),
  7236. EBML.int16(e.timestamp - clusterTimeCode),
  7237. EBML.bytes([0]),
  7238. EBML.bytes(e.frame)
  7239. ])];
  7240. if (typeof e.duration != 'undefined') {
  7241. blockGroupContent.push(EBML.element(EBML.ID.BlockDuration, EBML.number(e.duration)));
  7242. }
  7243. if (typeof e.codecState != 'undefined') {
  7244. blockGroupContent.push(EBML.element(EBML.ID.CodecState, EBML.bytes(e.codecState)));
  7245. }
  7246. return EBML.element(EBML.ID.BlockGroup, blockGroupContent);
  7247. }
  7248. }
  7249. }
  7250.  
  7251. /***
  7252. * FLV + ASS => MKV transmuxer
  7253. * Demux FLV into H264 + AAC stream and ASS into line stream; then
  7254. * remux them into a MKV file.
  7255. *
  7256. * @author qli5 <goodlq11[at](163|gmail).com>
  7257. *
  7258. * This Source Code Form is subject to the terms of the Mozilla Public
  7259. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7260. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7261. *
  7262. * The FLV demuxer is from flv.js <https://github.com/Bilibili/flv.js/>
  7263. * by zheng qian <xqq@xqq.im>, licensed under Apache 2.0.
  7264. *
  7265. * The EMBL builder is from simple-ebml-builder
  7266. * <https://www.npmjs.com/package/simple-ebml-builder> by ryiwamoto,
  7267. * licensed under MIT.
  7268. */
  7269.  
  7270. /**
  7271. * @param {Blob|string|ArrayBuffer} x
  7272. */
  7273. const getArrayBuffer = (x) => {
  7274. return new Promise((resolve, reject) => {
  7275. if (x instanceof _Blob) {
  7276. const e = new FileReader();
  7277. e.onload = () => resolve(e.result);
  7278. e.onerror = reject;
  7279. e.readAsArrayBuffer(x);
  7280. }
  7281. else if (typeof x == 'string') {
  7282. const e = new XMLHttpRequest();
  7283. e.responseType = 'arraybuffer';
  7284. e.onload = () => resolve(e.response);
  7285. e.onerror = reject;
  7286. e.open('get', x);
  7287. e.send();
  7288. }
  7289. else if (x instanceof ArrayBuffer) {
  7290. resolve(x);
  7291. }
  7292. else {
  7293. reject(new TypeError('flvass2mkv: getArrayBuffer {Blob|string|ArrayBuffer}'));
  7294. }
  7295. })
  7296. };
  7297.  
  7298. const FLVASS2MKV = class {
  7299. constructor(config = {}) {
  7300. this.onflvprogress = null;
  7301. this.onfileload = null;
  7302. this.onmkvprogress = null;
  7303. this.onload = null;
  7304. Object.assign(this, config);
  7305. this.mkvConfig = { onprogress: this.onmkvprogress };
  7306. Object.assign(this.mkvConfig, config.mkvConfig);
  7307. }
  7308.  
  7309. /**
  7310. * Demux FLV into H264 + AAC stream and ASS into line stream; then
  7311. * remux them into a MKV file.
  7312. * @typedef {Blob|string|ArrayBuffer} F
  7313. * @param {F} flv
  7314. * @param {F} ass
  7315. * @param {{ name: string; file: F; }[]} subtitleAssList
  7316. */
  7317. async build(flv = './samples/gen_case.flv', ass = './samples/gen_case.ass', subtitleAssList) {
  7318. // load flv and ass as arraybuffer
  7319. await Promise.all([
  7320. (async () => {
  7321. flv = await getArrayBuffer(flv);
  7322. })(),
  7323. (async () => {
  7324. ass = await getArrayBuffer(ass);
  7325. })(),
  7326. (async () => {
  7327. subtitleAssList = await Promise.all(
  7328. subtitleAssList.map(async ({ name, file }) => {
  7329. return { name, file: await getArrayBuffer(file) }
  7330. })
  7331. );
  7332. })(),
  7333. ]);
  7334.  
  7335. if (this.onfileload) this.onfileload();
  7336.  
  7337. const mkv = new MKV(this.mkvConfig);
  7338.  
  7339. const assParser = new ASS();
  7340. const assData = assParser.parseFile(ass);
  7341. mkv.addASSMetadata(assData, "弹幕");
  7342. mkv.addASSStream(assData);
  7343.  
  7344. subtitleAssList.forEach(({ name, file }) => {
  7345. const subAssData = assParser.parseFile(file);
  7346. mkv.addASSMetadata(subAssData, name);
  7347. mkv.addASSStream(subAssData);
  7348. });
  7349.  
  7350. if (subtitleAssList.length > 0) {
  7351. mkv.combineSubtitles();
  7352. }
  7353.  
  7354. const flvProbeData = FLVDemuxer.probe(flv);
  7355. const flvDemuxer = new FLVDemuxer(flvProbeData);
  7356. let mediaInfo = null;
  7357. let h264 = null;
  7358. let aac = null;
  7359. flvDemuxer.onDataAvailable = (...array) => {
  7360. array.forEach(e => {
  7361. if (e.type == 'video') h264 = e;
  7362. else if (e.type == 'audio') aac = e;
  7363. else throw new Error(\`MKVRemuxer: unrecoginzed data type \${e.type}\`);
  7364. });
  7365. };
  7366. flvDemuxer.onMediaInfo = i => mediaInfo = i;
  7367. flvDemuxer.onTrackMetadata = (i, e) => {
  7368. if (i == 'video') mkv.addH264Metadata(e);
  7369. else if (i == 'audio') mkv.addAACMetadata(e);
  7370. else throw new Error(\`MKVRemuxer: unrecoginzed metadata type \${i}\`);
  7371. };
  7372. flvDemuxer.onError = e => { throw new Error(e); };
  7373. const finalOffset = flvDemuxer.parseChunks(flv, flvProbeData.dataOffset);
  7374. if (finalOffset != flv.byteLength) throw new Error('FLVDemuxer: unexpected EOF');
  7375. mkv.addH264Stream(h264);
  7376. mkv.addAACStream(aac);
  7377.  
  7378. const ret = mkv.build();
  7379. if (this.onload) this.onload(ret);
  7380. return ret;
  7381. }
  7382. };
  7383.  
  7384. // if nodejs then test
  7385. if (typeof window == 'undefined') {
  7386. if (require.main == module) {
  7387. (async () => {
  7388. const fs = require('fs');
  7389. const assFileName = process.argv.slice(1).find(e => e.includes('.ass')) || './samples/gen_case.ass';
  7390. const flvFileName = process.argv.slice(1).find(e => e.includes('.flv')) || './samples/gen_case.flv';
  7391. const assFile = fs.readFileSync(assFileName).buffer;
  7392. const flvFile = fs.readFileSync(flvFileName).buffer;
  7393. fs.writeFileSync('out.mkv', await new FLVASS2MKV({ onmkvprogress: console.log.bind(console) }).build(flvFile, assFile));
  7394. })();
  7395. }
  7396. }
  7397.  
  7398. return FLVASS2MKV;
  7399.  
  7400. }());
  7401. //# sourceMappingURL=index.js.map
  7402.  
  7403. </script>
  7404. <script>
  7405. const fileProgress = document.getElementById('fileProgress');
  7406. const mkvProgress = document.getElementById('mkvProgress');
  7407. const a = document.getElementById('a');
  7408. window.exec = async (option, target) => {
  7409. const defaultOption = {
  7410. onflvprogress: ({ loaded, total }) => {
  7411. fileProgress.value = loaded;
  7412. fileProgress.max = total;
  7413. },
  7414. onfileload: () => {
  7415. console.timeEnd('file');
  7416. console.time('flvass2mkv');
  7417. },
  7418. onmkvprogress: ({ loaded, total }) => {
  7419. mkvProgress.value = loaded;
  7420. mkvProgress.max = total;
  7421. },
  7422. name: 'merged.mkv',
  7423. subtitleAssList: [],
  7424. };
  7425. option = Object.assign(defaultOption, option);
  7426. target.download = a.download = a.textContent = option.name;
  7427. console.time('file');
  7428. const mkv = await new FLVASS2MKV(option).build(option.flv, option.ass, option.subtitleAssList);
  7429. console.timeEnd('flvass2mkv');
  7430. target.href = a.href = URL.createObjectURL(mkv);
  7431. target.textContent = "另存为MKV"
  7432. target.onclick = () => {
  7433. window.close()
  7434. }
  7435. return a.href
  7436. };
  7437. </script>
  7438. </body>
  7439.  
  7440. </html>
  7441. `;
  7442.  
  7443. /***
  7444. * Copyright (C) 2018 Qli5. All Rights Reserved.
  7445. *
  7446. * @author qli5 <goodlq11[at](163|gmail).com>
  7447. *
  7448. * This Source Code Form is subject to the terms of the Mozilla Public
  7449. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7450. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7451. */
  7452.  
  7453. class MKVTransmuxer {
  7454. constructor(option) {
  7455. this.workerWin = null;
  7456. this.option = option;
  7457. }
  7458.  
  7459. /**
  7460. * FLV + ASS => MKV entry point
  7461. * @param {Blob|string|ArrayBuffer} flv
  7462. * @param {Blob|string|ArrayBuffer} ass
  7463. * @param {string=} name
  7464. * @param {Node} target
  7465. * @param {{ name: string; file: (Blob|string|ArrayBuffer); }[]=} subtitleAssList
  7466. */
  7467. exec(flv, ass, name, target, subtitleAssList = []) {
  7468. if (target.textContent != "另存为MKV") {
  7469. target.textContent = "打包中";
  7470.  
  7471. // 1. Allocate for a new window
  7472. if (!this.workerWin) this.workerWin = top.open('', undefined, ' ');
  7473.  
  7474. // 2. Inject scripts
  7475. this.workerWin.document.write(embeddedHTML);
  7476. this.workerWin.document.close();
  7477.  
  7478. // 3. Invoke exec
  7479. if (!(this.option instanceof Object)) this.option = null;
  7480. this.workerWin.exec(Object.assign({}, this.option, { flv, ass, name, subtitleAssList }), target);
  7481. URL.revokeObjectURL(flv);
  7482. URL.revokeObjectURL(ass);
  7483.  
  7484. // 4. Free parent window
  7485. // if (top.confirm('MKV打包中……要关掉这个窗口,释放内存吗?')) {
  7486. // top.location = 'about:blank';
  7487. // }
  7488. }
  7489. }
  7490. }
  7491.  
  7492. /***
  7493. * Copyright (C) 2018 Qli5. All Rights Reserved.
  7494. *
  7495. * @author qli5 <goodlq11[at](163|gmail).com>
  7496. *
  7497. * This Source Code Form is subject to the terms of the Mozilla Public
  7498. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7499. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7500. */
  7501.  
  7502. const _navigator = typeof navigator === 'object' && navigator || { userAgent: 'chrome' };
  7503.  
  7504. const _TextDecoder = typeof TextDecoder === 'function' && TextDecoder || class extends require('string_decoder').StringDecoder {
  7505. /**
  7506. * @param {ArrayBuffer} chunk
  7507. * @returns {string}
  7508. */
  7509. decode(chunk) {
  7510. return this.end(Buffer.from(chunk));
  7511. }
  7512. };
  7513.  
  7514. /***
  7515. * The FLV demuxer is from flv.js
  7516. *
  7517. * Copyright (C) 2016 Bilibili. All Rights Reserved.
  7518. *
  7519. * @author zheng qian <xqq@xqq.im>
  7520. *
  7521. * Licensed under the Apache License, Version 2.0 (the "License");
  7522. * you may not use this file except in compliance with the License.
  7523. * You may obtain a copy of the License at
  7524. *
  7525. * http://www.apache.org/licenses/LICENSE-2.0
  7526. *
  7527. * Unless required by applicable law or agreed to in writing, software
  7528. * distributed under the License is distributed on an "AS IS" BASIS,
  7529. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7530. * See the License for the specific language governing permissions and
  7531. * limitations under the License.
  7532. */
  7533.  
  7534. // import FLVDemuxer from 'flv.js/src/demux/flv-demuxer.js';
  7535. // ..import Log from '../utils/logger.js';
  7536. const Log = {
  7537. e: console.error.bind(console),
  7538. w: console.warn.bind(console),
  7539. i: console.log.bind(console),
  7540. v: console.log.bind(console),
  7541. };
  7542.  
  7543. // ..import AMF from './amf-parser.js';
  7544. // ....import Log from '../utils/logger.js';
  7545. // ....import decodeUTF8 from '../utils/utf8-conv.js';
  7546. function checkContinuation(uint8array, start, checkLength) {
  7547. let array = uint8array;
  7548. if (start + checkLength < array.length) {
  7549. while (checkLength--) {
  7550. if ((array[++start] & 0xC0) !== 0x80)
  7551. return false;
  7552. }
  7553. return true;
  7554. } else {
  7555. return false;
  7556. }
  7557. }
  7558.  
  7559. function decodeUTF8(uint8array) {
  7560. let out = [];
  7561. let input = uint8array;
  7562. let i = 0;
  7563. let length = uint8array.length;
  7564.  
  7565. while (i < length) {
  7566. if (input[i] < 0x80) {
  7567. out.push(String.fromCharCode(input[i]));
  7568. ++i;
  7569. continue;
  7570. } else if (input[i] < 0xC0) {
  7571. // fallthrough
  7572. } else if (input[i] < 0xE0) {
  7573. if (checkContinuation(input, i, 1)) {
  7574. let ucs4 = (input[i] & 0x1F) << 6 | (input[i + 1] & 0x3F);
  7575. if (ucs4 >= 0x80) {
  7576. out.push(String.fromCharCode(ucs4 & 0xFFFF));
  7577. i += 2;
  7578. continue;
  7579. }
  7580. }
  7581. } else if (input[i] < 0xF0) {
  7582. if (checkContinuation(input, i, 2)) {
  7583. let ucs4 = (input[i] & 0xF) << 12 | (input[i + 1] & 0x3F) << 6 | input[i + 2] & 0x3F;
  7584. if (ucs4 >= 0x800 && (ucs4 & 0xF800) !== 0xD800) {
  7585. out.push(String.fromCharCode(ucs4 & 0xFFFF));
  7586. i += 3;
  7587. continue;
  7588. }
  7589. }
  7590. } else if (input[i] < 0xF8) {
  7591. if (checkContinuation(input, i, 3)) {
  7592. let ucs4 = (input[i] & 0x7) << 18 | (input[i + 1] & 0x3F) << 12
  7593. | (input[i + 2] & 0x3F) << 6 | (input[i + 3] & 0x3F);
  7594. if (ucs4 > 0x10000 && ucs4 < 0x110000) {
  7595. ucs4 -= 0x10000;
  7596. out.push(String.fromCharCode((ucs4 >>> 10) | 0xD800));
  7597. out.push(String.fromCharCode((ucs4 & 0x3FF) | 0xDC00));
  7598. i += 4;
  7599. continue;
  7600. }
  7601. }
  7602. }
  7603. out.push(String.fromCharCode(0xFFFD));
  7604. ++i;
  7605. }
  7606.  
  7607. return out.join('');
  7608. }
  7609.  
  7610. // ....import {IllegalStateException} from '../utils/exception.js';
  7611. class IllegalStateException extends Error { }
  7612.  
  7613. let le = (function () {
  7614. let buf = new ArrayBuffer(2);
  7615. (new DataView(buf)).setInt16(0, 256, true); // little-endian write
  7616. return (new Int16Array(buf))[0] === 256; // platform-spec read, if equal then LE
  7617. })();
  7618.  
  7619. class AMF {
  7620.  
  7621. static parseScriptData(arrayBuffer, dataOffset, dataSize) {
  7622. let data = {};
  7623.  
  7624. try {
  7625. let name = AMF.parseValue(arrayBuffer, dataOffset, dataSize);
  7626. let value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  7627.  
  7628. data[name.data] = value.data;
  7629. } catch (e) {
  7630. Log.e('AMF', e.toString());
  7631. }
  7632.  
  7633. return data;
  7634. }
  7635.  
  7636. static parseObject(arrayBuffer, dataOffset, dataSize) {
  7637. if (dataSize < 3) {
  7638. throw new IllegalStateException('Data not enough when parse ScriptDataObject');
  7639. }
  7640. let name = AMF.parseString(arrayBuffer, dataOffset, dataSize);
  7641. let value = AMF.parseValue(arrayBuffer, dataOffset + name.size, dataSize - name.size);
  7642. let isObjectEnd = value.objectEnd;
  7643.  
  7644. return {
  7645. data: {
  7646. name: name.data,
  7647. value: value.data
  7648. },
  7649. size: name.size + value.size,
  7650. objectEnd: isObjectEnd
  7651. };
  7652. }
  7653.  
  7654. static parseVariable(arrayBuffer, dataOffset, dataSize) {
  7655. return AMF.parseObject(arrayBuffer, dataOffset, dataSize);
  7656. }
  7657.  
  7658. static parseString(arrayBuffer, dataOffset, dataSize) {
  7659. if (dataSize < 2) {
  7660. throw new IllegalStateException('Data not enough when parse String');
  7661. }
  7662. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  7663. let length = v.getUint16(0, !le);
  7664.  
  7665. let str;
  7666. if (length > 0) {
  7667. str = decodeUTF8(new Uint8Array(arrayBuffer, dataOffset + 2, length));
  7668. } else {
  7669. str = '';
  7670. }
  7671.  
  7672. return {
  7673. data: str,
  7674. size: 2 + length
  7675. };
  7676. }
  7677.  
  7678. static parseLongString(arrayBuffer, dataOffset, dataSize) {
  7679. if (dataSize < 4) {
  7680. throw new IllegalStateException('Data not enough when parse LongString');
  7681. }
  7682. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  7683. let length = v.getUint32(0, !le);
  7684.  
  7685. let str;
  7686. if (length > 0) {
  7687. str = decodeUTF8(new Uint8Array(arrayBuffer, dataOffset + 4, length));
  7688. } else {
  7689. str = '';
  7690. }
  7691.  
  7692. return {
  7693. data: str,
  7694. size: 4 + length
  7695. };
  7696. }
  7697.  
  7698. static parseDate(arrayBuffer, dataOffset, dataSize) {
  7699. if (dataSize < 10) {
  7700. throw new IllegalStateException('Data size invalid when parse Date');
  7701. }
  7702. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  7703. let timestamp = v.getFloat64(0, !le);
  7704. let localTimeOffset = v.getInt16(8, !le);
  7705. timestamp += localTimeOffset * 60 * 1000; // get UTC time
  7706.  
  7707. return {
  7708. data: new Date(timestamp),
  7709. size: 8 + 2
  7710. };
  7711. }
  7712.  
  7713. static parseValue(arrayBuffer, dataOffset, dataSize) {
  7714. if (dataSize < 1) {
  7715. throw new IllegalStateException('Data not enough when parse Value');
  7716. }
  7717.  
  7718. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  7719.  
  7720. let offset = 1;
  7721. let type = v.getUint8(0);
  7722. let value;
  7723. let objectEnd = false;
  7724.  
  7725. try {
  7726. switch (type) {
  7727. case 0: // Number(Double) type
  7728. value = v.getFloat64(1, !le);
  7729. offset += 8;
  7730. break;
  7731. case 1: { // Boolean type
  7732. let b = v.getUint8(1);
  7733. value = b ? true : false;
  7734. offset += 1;
  7735. break;
  7736. }
  7737. case 2: { // String type
  7738. let amfstr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  7739. value = amfstr.data;
  7740. offset += amfstr.size;
  7741. break;
  7742. }
  7743. case 3: { // Object(s) type
  7744. value = {};
  7745. let terminal = 0; // workaround for malformed Objects which has missing ScriptDataObjectEnd
  7746. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  7747. terminal = 3;
  7748. }
  7749. while (offset < dataSize - 4) { // 4 === type(UI8) + ScriptDataObjectEnd(UI24)
  7750. let amfobj = AMF.parseObject(arrayBuffer, dataOffset + offset, dataSize - offset - terminal);
  7751. if (amfobj.objectEnd)
  7752. break;
  7753. value[amfobj.data.name] = amfobj.data.value;
  7754. offset += amfobj.size;
  7755. }
  7756. if (offset <= dataSize - 3) {
  7757. let marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  7758. if (marker === 9) {
  7759. offset += 3;
  7760. }
  7761. }
  7762. break;
  7763. }
  7764. case 8: { // ECMA array type (Mixed array)
  7765. value = {};
  7766. offset += 4; // ECMAArrayLength(UI32)
  7767. let terminal = 0; // workaround for malformed MixedArrays which has missing ScriptDataObjectEnd
  7768. if ((v.getUint32(dataSize - 4, !le) & 0x00FFFFFF) === 9) {
  7769. terminal = 3;
  7770. }
  7771. while (offset < dataSize - 8) { // 8 === type(UI8) + ECMAArrayLength(UI32) + ScriptDataVariableEnd(UI24)
  7772. let amfvar = AMF.parseVariable(arrayBuffer, dataOffset + offset, dataSize - offset - terminal);
  7773. if (amfvar.objectEnd)
  7774. break;
  7775. value[amfvar.data.name] = amfvar.data.value;
  7776. offset += amfvar.size;
  7777. }
  7778. if (offset <= dataSize - 3) {
  7779. let marker = v.getUint32(offset - 1, !le) & 0x00FFFFFF;
  7780. if (marker === 9) {
  7781. offset += 3;
  7782. }
  7783. }
  7784. break;
  7785. }
  7786. case 9: // ScriptDataObjectEnd
  7787. value = undefined;
  7788. offset = 1;
  7789. objectEnd = true;
  7790. break;
  7791. case 10: { // Strict array type
  7792. // ScriptDataValue[n]. NOTE: according to video_file_format_spec_v10_1.pdf
  7793. value = [];
  7794. let strictArrayLength = v.getUint32(1, !le);
  7795. offset += 4;
  7796. for (let i = 0; i < strictArrayLength; i++) {
  7797. let val = AMF.parseValue(arrayBuffer, dataOffset + offset, dataSize - offset);
  7798. value.push(val.data);
  7799. offset += val.size;
  7800. }
  7801. break;
  7802. }
  7803. case 11: { // Date type
  7804. let date = AMF.parseDate(arrayBuffer, dataOffset + 1, dataSize - 1);
  7805. value = date.data;
  7806. offset += date.size;
  7807. break;
  7808. }
  7809. case 12: { // Long string type
  7810. let amfLongStr = AMF.parseString(arrayBuffer, dataOffset + 1, dataSize - 1);
  7811. value = amfLongStr.data;
  7812. offset += amfLongStr.size;
  7813. break;
  7814. }
  7815. default:
  7816. // ignore and skip
  7817. offset = dataSize;
  7818. Log.w('AMF', 'Unsupported AMF value type ' + type);
  7819. }
  7820. } catch (e) {
  7821. Log.e('AMF', e.toString());
  7822. }
  7823.  
  7824. return {
  7825. data: value,
  7826. size: offset,
  7827. objectEnd: objectEnd
  7828. };
  7829. }
  7830.  
  7831. }
  7832.  
  7833. // ..import SPSParser from './sps-parser.js';
  7834. // ....import ExpGolomb from './exp-golomb.js';
  7835. // ......import {IllegalStateException, InvalidArgumentException} from '../utils/exception.js';
  7836. class InvalidArgumentException extends Error { }
  7837.  
  7838. class ExpGolomb {
  7839.  
  7840. constructor(uint8array) {
  7841. this.TAG = 'ExpGolomb';
  7842.  
  7843. this._buffer = uint8array;
  7844. this._buffer_index = 0;
  7845. this._total_bytes = uint8array.byteLength;
  7846. this._total_bits = uint8array.byteLength * 8;
  7847. this._current_word = 0;
  7848. this._current_word_bits_left = 0;
  7849. }
  7850.  
  7851. destroy() {
  7852. this._buffer = null;
  7853. }
  7854.  
  7855. _fillCurrentWord() {
  7856. let buffer_bytes_left = this._total_bytes - this._buffer_index;
  7857. if (buffer_bytes_left <= 0)
  7858. throw new IllegalStateException('ExpGolomb: _fillCurrentWord() but no bytes available');
  7859.  
  7860. let bytes_read = Math.min(4, buffer_bytes_left);
  7861. let word = new Uint8Array(4);
  7862. word.set(this._buffer.subarray(this._buffer_index, this._buffer_index + bytes_read));
  7863. this._current_word = new DataView(word.buffer).getUint32(0, false);
  7864.  
  7865. this._buffer_index += bytes_read;
  7866. this._current_word_bits_left = bytes_read * 8;
  7867. }
  7868.  
  7869. readBits(bits) {
  7870. if (bits > 32)
  7871. throw new InvalidArgumentException('ExpGolomb: readBits() bits exceeded max 32bits!');
  7872.  
  7873. if (bits <= this._current_word_bits_left) {
  7874. let result = this._current_word >>> (32 - bits);
  7875. this._current_word <<= bits;
  7876. this._current_word_bits_left -= bits;
  7877. return result;
  7878. }
  7879.  
  7880. let result = this._current_word_bits_left ? this._current_word : 0;
  7881. result = result >>> (32 - this._current_word_bits_left);
  7882. let bits_need_left = bits - this._current_word_bits_left;
  7883.  
  7884. this._fillCurrentWord();
  7885. let bits_read_next = Math.min(bits_need_left, this._current_word_bits_left);
  7886.  
  7887. let result2 = this._current_word >>> (32 - bits_read_next);
  7888. this._current_word <<= bits_read_next;
  7889. this._current_word_bits_left -= bits_read_next;
  7890.  
  7891. result = (result << bits_read_next) | result2;
  7892. return result;
  7893. }
  7894.  
  7895. readBool() {
  7896. return this.readBits(1) === 1;
  7897. }
  7898.  
  7899. readByte() {
  7900. return this.readBits(8);
  7901. }
  7902.  
  7903. _skipLeadingZero() {
  7904. let zero_count;
  7905. for (zero_count = 0; zero_count < this._current_word_bits_left; zero_count++) {
  7906. if (0 !== (this._current_word & (0x80000000 >>> zero_count))) {
  7907. this._current_word <<= zero_count;
  7908. this._current_word_bits_left -= zero_count;
  7909. return zero_count;
  7910. }
  7911. }
  7912. this._fillCurrentWord();
  7913. return zero_count + this._skipLeadingZero();
  7914. }
  7915.  
  7916. readUEG() { // unsigned exponential golomb
  7917. let leading_zeros = this._skipLeadingZero();
  7918. return this.readBits(leading_zeros + 1) - 1;
  7919. }
  7920.  
  7921. readSEG() { // signed exponential golomb
  7922. let value = this.readUEG();
  7923. if (value & 0x01) {
  7924. return (value + 1) >>> 1;
  7925. } else {
  7926. return -1 * (value >>> 1);
  7927. }
  7928. }
  7929.  
  7930. }
  7931.  
  7932. class SPSParser {
  7933.  
  7934. static _ebsp2rbsp(uint8array) {
  7935. let src = uint8array;
  7936. let src_length = src.byteLength;
  7937. let dst = new Uint8Array(src_length);
  7938. let dst_idx = 0;
  7939.  
  7940. for (let i = 0; i < src_length; i++) {
  7941. if (i >= 2) {
  7942. // Unescape: Skip 0x03 after 00 00
  7943. if (src[i] === 0x03 && src[i - 1] === 0x00 && src[i - 2] === 0x00) {
  7944. continue;
  7945. }
  7946. }
  7947. dst[dst_idx] = src[i];
  7948. dst_idx++;
  7949. }
  7950.  
  7951. return new Uint8Array(dst.buffer, 0, dst_idx);
  7952. }
  7953.  
  7954. static parseSPS(uint8array) {
  7955. let rbsp = SPSParser._ebsp2rbsp(uint8array);
  7956. let gb = new ExpGolomb(rbsp);
  7957.  
  7958. gb.readByte();
  7959. let profile_idc = gb.readByte(); // profile_idc
  7960. gb.readByte(); // constraint_set_flags[5] + reserved_zero[3]
  7961. let level_idc = gb.readByte(); // level_idc
  7962. gb.readUEG(); // seq_parameter_set_id
  7963.  
  7964. let profile_string = SPSParser.getProfileString(profile_idc);
  7965. let level_string = SPSParser.getLevelString(level_idc);
  7966. let chroma_format_idc = 1;
  7967. let chroma_format = 420;
  7968. let chroma_format_table = [0, 420, 422, 444];
  7969. let bit_depth = 8;
  7970.  
  7971. if (profile_idc === 100 || profile_idc === 110 || profile_idc === 122 ||
  7972. profile_idc === 244 || profile_idc === 44 || profile_idc === 83 ||
  7973. profile_idc === 86 || profile_idc === 118 || profile_idc === 128 ||
  7974. profile_idc === 138 || profile_idc === 144) {
  7975.  
  7976. chroma_format_idc = gb.readUEG();
  7977. if (chroma_format_idc === 3) {
  7978. gb.readBits(1); // separate_colour_plane_flag
  7979. }
  7980. if (chroma_format_idc <= 3) {
  7981. chroma_format = chroma_format_table[chroma_format_idc];
  7982. }
  7983.  
  7984. bit_depth = gb.readUEG() + 8; // bit_depth_luma_minus8
  7985. gb.readUEG(); // bit_depth_chroma_minus8
  7986. gb.readBits(1); // qpprime_y_zero_transform_bypass_flag
  7987. if (gb.readBool()) { // seq_scaling_matrix_present_flag
  7988. let scaling_list_count = (chroma_format_idc !== 3) ? 8 : 12;
  7989. for (let i = 0; i < scaling_list_count; i++) {
  7990. if (gb.readBool()) { // seq_scaling_list_present_flag
  7991. if (i < 6) {
  7992. SPSParser._skipScalingList(gb, 16);
  7993. } else {
  7994. SPSParser._skipScalingList(gb, 64);
  7995. }
  7996. }
  7997. }
  7998. }
  7999. }
  8000. gb.readUEG(); // log2_max_frame_num_minus4
  8001. let pic_order_cnt_type = gb.readUEG();
  8002. if (pic_order_cnt_type === 0) {
  8003. gb.readUEG(); // log2_max_pic_order_cnt_lsb_minus_4
  8004. } else if (pic_order_cnt_type === 1) {
  8005. gb.readBits(1); // delta_pic_order_always_zero_flag
  8006. gb.readSEG(); // offset_for_non_ref_pic
  8007. gb.readSEG(); // offset_for_top_to_bottom_field
  8008. let num_ref_frames_in_pic_order_cnt_cycle = gb.readUEG();
  8009. for (let i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++) {
  8010. gb.readSEG(); // offset_for_ref_frame
  8011. }
  8012. }
  8013. gb.readUEG(); // max_num_ref_frames
  8014. gb.readBits(1); // gaps_in_frame_num_value_allowed_flag
  8015.  
  8016. let pic_width_in_mbs_minus1 = gb.readUEG();
  8017. let pic_height_in_map_units_minus1 = gb.readUEG();
  8018.  
  8019. let frame_mbs_only_flag = gb.readBits(1);
  8020. if (frame_mbs_only_flag === 0) {
  8021. gb.readBits(1); // mb_adaptive_frame_field_flag
  8022. }
  8023. gb.readBits(1); // direct_8x8_inference_flag
  8024.  
  8025. let frame_crop_left_offset = 0;
  8026. let frame_crop_right_offset = 0;
  8027. let frame_crop_top_offset = 0;
  8028. let frame_crop_bottom_offset = 0;
  8029.  
  8030. let frame_cropping_flag = gb.readBool();
  8031. if (frame_cropping_flag) {
  8032. frame_crop_left_offset = gb.readUEG();
  8033. frame_crop_right_offset = gb.readUEG();
  8034. frame_crop_top_offset = gb.readUEG();
  8035. frame_crop_bottom_offset = gb.readUEG();
  8036. }
  8037.  
  8038. let sar_width = 1, sar_height = 1;
  8039. let fps = 0, fps_fixed = true, fps_num = 0, fps_den = 0;
  8040.  
  8041. let vui_parameters_present_flag = gb.readBool();
  8042. if (vui_parameters_present_flag) {
  8043. if (gb.readBool()) { // aspect_ratio_info_present_flag
  8044. let aspect_ratio_idc = gb.readByte();
  8045. let sar_w_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  8046. let sar_h_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  8047.  
  8048. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  8049. sar_width = sar_w_table[aspect_ratio_idc - 1];
  8050. sar_height = sar_h_table[aspect_ratio_idc - 1];
  8051. } else if (aspect_ratio_idc === 255) {
  8052. sar_width = gb.readByte() << 8 | gb.readByte();
  8053. sar_height = gb.readByte() << 8 | gb.readByte();
  8054. }
  8055. }
  8056.  
  8057. if (gb.readBool()) { // overscan_info_present_flag
  8058. gb.readBool(); // overscan_appropriate_flag
  8059. }
  8060. if (gb.readBool()) { // video_signal_type_present_flag
  8061. gb.readBits(4); // video_format & video_full_range_flag
  8062. if (gb.readBool()) { // colour_description_present_flag
  8063. gb.readBits(24); // colour_primaries & transfer_characteristics & matrix_coefficients
  8064. }
  8065. }
  8066. if (gb.readBool()) { // chroma_loc_info_present_flag
  8067. gb.readUEG(); // chroma_sample_loc_type_top_field
  8068. gb.readUEG(); // chroma_sample_loc_type_bottom_field
  8069. }
  8070. if (gb.readBool()) { // timing_info_present_flag
  8071. let num_units_in_tick = gb.readBits(32);
  8072. let time_scale = gb.readBits(32);
  8073. fps_fixed = gb.readBool(); // fixed_frame_rate_flag
  8074.  
  8075. fps_num = time_scale;
  8076. fps_den = num_units_in_tick * 2;
  8077. fps = fps_num / fps_den;
  8078. }
  8079. }
  8080.  
  8081. let sarScale = 1;
  8082. if (sar_width !== 1 || sar_height !== 1) {
  8083. sarScale = sar_width / sar_height;
  8084. }
  8085.  
  8086. let crop_unit_x = 0, crop_unit_y = 0;
  8087. if (chroma_format_idc === 0) {
  8088. crop_unit_x = 1;
  8089. crop_unit_y = 2 - frame_mbs_only_flag;
  8090. } else {
  8091. let sub_wc = (chroma_format_idc === 3) ? 1 : 2;
  8092. let sub_hc = (chroma_format_idc === 1) ? 2 : 1;
  8093. crop_unit_x = sub_wc;
  8094. crop_unit_y = sub_hc * (2 - frame_mbs_only_flag);
  8095. }
  8096.  
  8097. let codec_width = (pic_width_in_mbs_minus1 + 1) * 16;
  8098. let codec_height = (2 - frame_mbs_only_flag) * ((pic_height_in_map_units_minus1 + 1) * 16);
  8099.  
  8100. codec_width -= (frame_crop_left_offset + frame_crop_right_offset) * crop_unit_x;
  8101. codec_height -= (frame_crop_top_offset + frame_crop_bottom_offset) * crop_unit_y;
  8102.  
  8103. let present_width = Math.ceil(codec_width * sarScale);
  8104.  
  8105. gb.destroy();
  8106. gb = null;
  8107.  
  8108. return {
  8109. profile_string: profile_string, // baseline, high, high10, ...
  8110. level_string: level_string, // 3, 3.1, 4, 4.1, 5, 5.1, ...
  8111. bit_depth: bit_depth, // 8bit, 10bit, ...
  8112. chroma_format: chroma_format, // 4:2:0, 4:2:2, ...
  8113. chroma_format_string: SPSParser.getChromaFormatString(chroma_format),
  8114.  
  8115. frame_rate: {
  8116. fixed: fps_fixed,
  8117. fps: fps,
  8118. fps_den: fps_den,
  8119. fps_num: fps_num
  8120. },
  8121.  
  8122. sar_ratio: {
  8123. width: sar_width,
  8124. height: sar_height
  8125. },
  8126.  
  8127. codec_size: {
  8128. width: codec_width,
  8129. height: codec_height
  8130. },
  8131.  
  8132. present_size: {
  8133. width: present_width,
  8134. height: codec_height
  8135. }
  8136. };
  8137. }
  8138.  
  8139. static _skipScalingList(gb, count) {
  8140. let last_scale = 8, next_scale = 8;
  8141. let delta_scale = 0;
  8142. for (let i = 0; i < count; i++) {
  8143. if (next_scale !== 0) {
  8144. delta_scale = gb.readSEG();
  8145. next_scale = (last_scale + delta_scale + 256) % 256;
  8146. }
  8147. last_scale = (next_scale === 0) ? last_scale : next_scale;
  8148. }
  8149. }
  8150.  
  8151. static getProfileString(profile_idc) {
  8152. switch (profile_idc) {
  8153. case 66:
  8154. return 'Baseline';
  8155. case 77:
  8156. return 'Main';
  8157. case 88:
  8158. return 'Extended';
  8159. case 100:
  8160. return 'High';
  8161. case 110:
  8162. return 'High10';
  8163. case 122:
  8164. return 'High422';
  8165. case 244:
  8166. return 'High444';
  8167. default:
  8168. return 'Unknown';
  8169. }
  8170. }
  8171.  
  8172. static getLevelString(level_idc) {
  8173. return (level_idc / 10).toFixed(1);
  8174. }
  8175.  
  8176. static getChromaFormatString(chroma) {
  8177. switch (chroma) {
  8178. case 420:
  8179. return '4:2:0';
  8180. case 422:
  8181. return '4:2:2';
  8182. case 444:
  8183. return '4:4:4';
  8184. default:
  8185. return 'Unknown';
  8186. }
  8187. }
  8188.  
  8189. }
  8190.  
  8191. // ..import DemuxErrors from './demux-errors.js';
  8192. const DemuxErrors = {
  8193. OK: 'OK',
  8194. FORMAT_ERROR: 'FormatError',
  8195. FORMAT_UNSUPPORTED: 'FormatUnsupported',
  8196. CODEC_UNSUPPORTED: 'CodecUnsupported'
  8197. };
  8198.  
  8199. // ..import MediaInfo from '../core/media-info.js';
  8200. class MediaInfo {
  8201.  
  8202. constructor() {
  8203. this.mimeType = null;
  8204. this.duration = null;
  8205.  
  8206. this.hasAudio = null;
  8207. this.hasVideo = null;
  8208. this.audioCodec = null;
  8209. this.videoCodec = null;
  8210. this.audioDataRate = null;
  8211. this.videoDataRate = null;
  8212.  
  8213. this.audioSampleRate = null;
  8214. this.audioChannelCount = null;
  8215.  
  8216. this.width = null;
  8217. this.height = null;
  8218. this.fps = null;
  8219. this.profile = null;
  8220. this.level = null;
  8221. this.chromaFormat = null;
  8222. this.sarNum = null;
  8223. this.sarDen = null;
  8224.  
  8225. this.metadata = null;
  8226. this.segments = null; // MediaInfo[]
  8227. this.segmentCount = null;
  8228. this.hasKeyframesIndex = null;
  8229. this.keyframesIndex = null;
  8230. }
  8231.  
  8232. isComplete() {
  8233. let audioInfoComplete = (this.hasAudio === false) ||
  8234. (this.hasAudio === true &&
  8235. this.audioCodec != null &&
  8236. this.audioSampleRate != null &&
  8237. this.audioChannelCount != null);
  8238.  
  8239. let videoInfoComplete = (this.hasVideo === false) ||
  8240. (this.hasVideo === true &&
  8241. this.videoCodec != null &&
  8242. this.width != null &&
  8243. this.height != null &&
  8244. this.fps != null &&
  8245. this.profile != null &&
  8246. this.level != null &&
  8247. this.chromaFormat != null &&
  8248. this.sarNum != null &&
  8249. this.sarDen != null);
  8250.  
  8251. // keyframesIndex may not be present
  8252. return this.mimeType != null &&
  8253. this.duration != null &&
  8254. this.metadata != null &&
  8255. this.hasKeyframesIndex != null &&
  8256. audioInfoComplete &&
  8257. videoInfoComplete;
  8258. }
  8259.  
  8260. isSeekable() {
  8261. return this.hasKeyframesIndex === true;
  8262. }
  8263.  
  8264. getNearestKeyframe(milliseconds) {
  8265. if (this.keyframesIndex == null) {
  8266. return null;
  8267. }
  8268.  
  8269. let table = this.keyframesIndex;
  8270. let keyframeIdx = this._search(table.times, milliseconds);
  8271.  
  8272. return {
  8273. index: keyframeIdx,
  8274. milliseconds: table.times[keyframeIdx],
  8275. fileposition: table.filepositions[keyframeIdx]
  8276. };
  8277. }
  8278.  
  8279. _search(list, value) {
  8280. let idx = 0;
  8281.  
  8282. let last = list.length - 1;
  8283. let mid = 0;
  8284. let lbound = 0;
  8285. let ubound = last;
  8286.  
  8287. if (value < list[0]) {
  8288. idx = 0;
  8289. lbound = ubound + 1; // skip search
  8290. }
  8291.  
  8292. while (lbound <= ubound) {
  8293. mid = lbound + Math.floor((ubound - lbound) / 2);
  8294. if (mid === last || (value >= list[mid] && value < list[mid + 1])) {
  8295. idx = mid;
  8296. break;
  8297. } else if (list[mid] < value) {
  8298. lbound = mid + 1;
  8299. } else {
  8300. ubound = mid - 1;
  8301. }
  8302. }
  8303.  
  8304. return idx;
  8305. }
  8306.  
  8307. }
  8308.  
  8309. function ReadBig32(array, index) {
  8310. return ((array[index] << 24) |
  8311. (array[index + 1] << 16) |
  8312. (array[index + 2] << 8) |
  8313. (array[index + 3]));
  8314. }
  8315.  
  8316. class FLVDemuxer {
  8317.  
  8318. /**
  8319. * Create a new FLV demuxer
  8320. * @param {Object} probeData
  8321. * @param {boolean} probeData.match
  8322. * @param {number} probeData.consumed
  8323. * @param {number} probeData.dataOffset
  8324. * @param {boolean} probeData.hasAudioTrack
  8325. * @param {boolean} probeData.hasVideoTrack
  8326. */
  8327. constructor(probeData) {
  8328. this.TAG = 'FLVDemuxer';
  8329.  
  8330. this._onError = null;
  8331. this._onMediaInfo = null;
  8332. this._onTrackMetadata = null;
  8333. this._onDataAvailable = null;
  8334.  
  8335. this._dataOffset = probeData.dataOffset;
  8336. this._firstParse = true;
  8337. this._dispatch = false;
  8338.  
  8339. this._hasAudio = probeData.hasAudioTrack;
  8340. this._hasVideo = probeData.hasVideoTrack;
  8341.  
  8342. this._hasAudioFlagOverrided = false;
  8343. this._hasVideoFlagOverrided = false;
  8344.  
  8345. this._audioInitialMetadataDispatched = false;
  8346. this._videoInitialMetadataDispatched = false;
  8347.  
  8348. this._mediaInfo = new MediaInfo();
  8349. this._mediaInfo.hasAudio = this._hasAudio;
  8350. this._mediaInfo.hasVideo = this._hasVideo;
  8351. this._metadata = null;
  8352. this._audioMetadata = null;
  8353. this._videoMetadata = null;
  8354.  
  8355. this._naluLengthSize = 4;
  8356. this._timestampBase = 0; // int32, in milliseconds
  8357. this._timescale = 1000;
  8358. this._duration = 0; // int32, in milliseconds
  8359. this._durationOverrided = false;
  8360. this._referenceFrameRate = {
  8361. fixed: true,
  8362. fps: 23.976,
  8363. fps_num: 23976,
  8364. fps_den: 1000
  8365. };
  8366.  
  8367. this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48000];
  8368.  
  8369. this._mpegSamplingRates = [
  8370. 96000, 88200, 64000, 48000, 44100, 32000,
  8371. 24000, 22050, 16000, 12000, 11025, 8000, 7350
  8372. ];
  8373.  
  8374. this._mpegAudioV10SampleRateTable = [44100, 48000, 32000, 0];
  8375. this._mpegAudioV20SampleRateTable = [22050, 24000, 16000, 0];
  8376. this._mpegAudioV25SampleRateTable = [11025, 12000, 8000, 0];
  8377.  
  8378. this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1];
  8379. this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1];
  8380. this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1];
  8381.  
  8382. this._videoTrack = { type: 'video', id: 1, sequenceNumber: 0, samples: [], length: 0 };
  8383. this._audioTrack = { type: 'audio', id: 2, sequenceNumber: 0, samples: [], length: 0 };
  8384.  
  8385. this._littleEndian = (function () {
  8386. let buf = new ArrayBuffer(2);
  8387. (new DataView(buf)).setInt16(0, 256, true); // little-endian write
  8388. return (new Int16Array(buf))[0] === 256; // platform-spec read, if equal then LE
  8389. })();
  8390. }
  8391.  
  8392. destroy() {
  8393. this._mediaInfo = null;
  8394. this._metadata = null;
  8395. this._audioMetadata = null;
  8396. this._videoMetadata = null;
  8397. this._videoTrack = null;
  8398. this._audioTrack = null;
  8399.  
  8400. this._onError = null;
  8401. this._onMediaInfo = null;
  8402. this._onTrackMetadata = null;
  8403. this._onDataAvailable = null;
  8404. }
  8405.  
  8406. /**
  8407. * Probe the flv data
  8408. * @param {ArrayBuffer} buffer
  8409. * @returns {Object} - probeData to be feed into constructor
  8410. */
  8411. static probe(buffer) {
  8412. let data = new Uint8Array(buffer);
  8413. let mismatch = { match: false };
  8414.  
  8415. if (data[0] !== 0x46 || data[1] !== 0x4C || data[2] !== 0x56 || data[3] !== 0x01) {
  8416. return mismatch;
  8417. }
  8418.  
  8419. let hasAudio = ((data[4] & 4) >>> 2) !== 0;
  8420. let hasVideo = (data[4] & 1) !== 0;
  8421.  
  8422. let offset = ReadBig32(data, 5);
  8423.  
  8424. if (offset < 9) {
  8425. return mismatch;
  8426. }
  8427.  
  8428. return {
  8429. match: true,
  8430. consumed: offset,
  8431. dataOffset: offset,
  8432. hasAudioTrack: hasAudio,
  8433. hasVideoTrack: hasVideo
  8434. };
  8435. }
  8436.  
  8437. bindDataSource(loader) {
  8438. loader.onDataArrival = this.parseChunks.bind(this);
  8439. return this;
  8440. }
  8441.  
  8442. // prototype: function(type: string, metadata: any): void
  8443. get onTrackMetadata() {
  8444. return this._onTrackMetadata;
  8445. }
  8446.  
  8447. set onTrackMetadata(callback) {
  8448. this._onTrackMetadata = callback;
  8449. }
  8450.  
  8451. // prototype: function(mediaInfo: MediaInfo): void
  8452. get onMediaInfo() {
  8453. return this._onMediaInfo;
  8454. }
  8455.  
  8456. set onMediaInfo(callback) {
  8457. this._onMediaInfo = callback;
  8458. }
  8459.  
  8460. // prototype: function(type: number, info: string): void
  8461. get onError() {
  8462. return this._onError;
  8463. }
  8464.  
  8465. set onError(callback) {
  8466. this._onError = callback;
  8467. }
  8468.  
  8469. // prototype: function(videoTrack: any, audioTrack: any): void
  8470. get onDataAvailable() {
  8471. return this._onDataAvailable;
  8472. }
  8473.  
  8474. set onDataAvailable(callback) {
  8475. this._onDataAvailable = callback;
  8476. }
  8477.  
  8478. // timestamp base for output samples, must be in milliseconds
  8479. get timestampBase() {
  8480. return this._timestampBase;
  8481. }
  8482.  
  8483. set timestampBase(base) {
  8484. this._timestampBase = base;
  8485. }
  8486.  
  8487. get overridedDuration() {
  8488. return this._duration;
  8489. }
  8490.  
  8491. // Force-override media duration. Must be in milliseconds, int32
  8492. set overridedDuration(duration) {
  8493. this._durationOverrided = true;
  8494. this._duration = duration;
  8495. this._mediaInfo.duration = duration;
  8496. }
  8497.  
  8498. // Force-override audio track present flag, boolean
  8499. set overridedHasAudio(hasAudio) {
  8500. this._hasAudioFlagOverrided = true;
  8501. this._hasAudio = hasAudio;
  8502. this._mediaInfo.hasAudio = hasAudio;
  8503. }
  8504.  
  8505. // Force-override video track present flag, boolean
  8506. set overridedHasVideo(hasVideo) {
  8507. this._hasVideoFlagOverrided = true;
  8508. this._hasVideo = hasVideo;
  8509. this._mediaInfo.hasVideo = hasVideo;
  8510. }
  8511.  
  8512. resetMediaInfo() {
  8513. this._mediaInfo = new MediaInfo();
  8514. }
  8515.  
  8516. _isInitialMetadataDispatched() {
  8517. if (this._hasAudio && this._hasVideo) { // both audio & video
  8518. return this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched;
  8519. }
  8520. if (this._hasAudio && !this._hasVideo) { // audio only
  8521. return this._audioInitialMetadataDispatched;
  8522. }
  8523. if (!this._hasAudio && this._hasVideo) { // video only
  8524. return this._videoInitialMetadataDispatched;
  8525. }
  8526. return false;
  8527. }
  8528.  
  8529. // function parseChunks(chunk: ArrayBuffer, byteStart: number): number;
  8530. parseChunks(chunk, byteStart) {
  8531. if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) {
  8532. throw new IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');
  8533. }
  8534.  
  8535. // qli5: fix nonzero byteStart
  8536. let offset = byteStart || 0;
  8537. let le = this._littleEndian;
  8538.  
  8539. if (byteStart === 0) { // buffer with FLV header
  8540. if (chunk.byteLength > 13) {
  8541. let probeData = FLVDemuxer.probe(chunk);
  8542. offset = probeData.dataOffset;
  8543. } else {
  8544. return 0;
  8545. }
  8546. }
  8547.  
  8548. if (this._firstParse) { // handle PreviousTagSize0 before Tag1
  8549. this._firstParse = false;
  8550. if (offset !== this._dataOffset) {
  8551. Log.w(this.TAG, 'First time parsing but chunk byteStart invalid!');
  8552. }
  8553.  
  8554. let v = new DataView(chunk, offset);
  8555. let prevTagSize0 = v.getUint32(0, !le);
  8556. if (prevTagSize0 !== 0) {
  8557. Log.w(this.TAG, 'PrevTagSize0 !== 0 !!!');
  8558. }
  8559. offset += 4;
  8560. }
  8561.  
  8562. while (offset < chunk.byteLength) {
  8563. this._dispatch = true;
  8564.  
  8565. let v = new DataView(chunk, offset);
  8566.  
  8567. if (offset + 11 + 4 > chunk.byteLength) {
  8568. // data not enough for parsing an flv tag
  8569. break;
  8570. }
  8571.  
  8572. let tagType = v.getUint8(0);
  8573. let dataSize = v.getUint32(0, !le) & 0x00FFFFFF;
  8574.  
  8575. if (offset + 11 + dataSize + 4 > chunk.byteLength) {
  8576. // data not enough for parsing actual data body
  8577. break;
  8578. }
  8579.  
  8580. if (tagType !== 8 && tagType !== 9 && tagType !== 18) {
  8581. Log.w(this.TAG, `Unsupported tag type ${tagType}, skipped`);
  8582. // consume the whole tag (skip it)
  8583. offset += 11 + dataSize + 4;
  8584. continue;
  8585. }
  8586.  
  8587. let ts2 = v.getUint8(4);
  8588. let ts1 = v.getUint8(5);
  8589. let ts0 = v.getUint8(6);
  8590. let ts3 = v.getUint8(7);
  8591.  
  8592. let timestamp = ts0 | (ts1 << 8) | (ts2 << 16) | (ts3 << 24);
  8593.  
  8594. let streamId = v.getUint32(7, !le) & 0x00FFFFFF;
  8595. if (streamId !== 0) {
  8596. Log.w(this.TAG, 'Meet tag which has StreamID != 0!');
  8597. }
  8598.  
  8599. let dataOffset = offset + 11;
  8600.  
  8601. switch (tagType) {
  8602. case 8: // Audio
  8603. this._parseAudioData(chunk, dataOffset, dataSize, timestamp);
  8604. break;
  8605. case 9: // Video
  8606. this._parseVideoData(chunk, dataOffset, dataSize, timestamp, byteStart + offset);
  8607. break;
  8608. case 18: // ScriptDataObject
  8609. this._parseScriptData(chunk, dataOffset, dataSize);
  8610. break;
  8611. }
  8612.  
  8613. let prevTagSize = v.getUint32(11 + dataSize, !le);
  8614. if (prevTagSize !== 11 + dataSize) {
  8615. Log.w(this.TAG, `Invalid PrevTagSize ${prevTagSize}`);
  8616. }
  8617.  
  8618. offset += 11 + dataSize + 4; // tagBody + dataSize + prevTagSize
  8619. }
  8620.  
  8621. // dispatch parsed frames to consumer (typically, the remuxer)
  8622. if (this._isInitialMetadataDispatched()) {
  8623. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  8624. this._onDataAvailable(this._audioTrack, this._videoTrack);
  8625. }
  8626. }
  8627.  
  8628. return offset; // consumed bytes, just equals latest offset index
  8629. }
  8630.  
  8631. _parseScriptData(arrayBuffer, dataOffset, dataSize) {
  8632. let scriptData = AMF.parseScriptData(arrayBuffer, dataOffset, dataSize);
  8633.  
  8634. if (scriptData.hasOwnProperty('onMetaData')) {
  8635. if (scriptData.onMetaData == null || typeof scriptData.onMetaData !== 'object') {
  8636. Log.w(this.TAG, 'Invalid onMetaData structure!');
  8637. return;
  8638. }
  8639. if (this._metadata) {
  8640. Log.w(this.TAG, 'Found another onMetaData tag!');
  8641. }
  8642. this._metadata = scriptData;
  8643. let onMetaData = this._metadata.onMetaData;
  8644.  
  8645. if (typeof onMetaData.hasAudio === 'boolean') { // hasAudio
  8646. if (this._hasAudioFlagOverrided === false) {
  8647. this._hasAudio = onMetaData.hasAudio;
  8648. this._mediaInfo.hasAudio = this._hasAudio;
  8649. }
  8650. }
  8651. if (typeof onMetaData.hasVideo === 'boolean') { // hasVideo
  8652. if (this._hasVideoFlagOverrided === false) {
  8653. this._hasVideo = onMetaData.hasVideo;
  8654. this._mediaInfo.hasVideo = this._hasVideo;
  8655. }
  8656. }
  8657. if (typeof onMetaData.audiodatarate === 'number') { // audiodatarate
  8658. this._mediaInfo.audioDataRate = onMetaData.audiodatarate;
  8659. }
  8660. if (typeof onMetaData.videodatarate === 'number') { // videodatarate
  8661. this._mediaInfo.videoDataRate = onMetaData.videodatarate;
  8662. }
  8663. if (typeof onMetaData.width === 'number') { // width
  8664. this._mediaInfo.width = onMetaData.width;
  8665. }
  8666. if (typeof onMetaData.height === 'number') { // height
  8667. this._mediaInfo.height = onMetaData.height;
  8668. }
  8669. if (typeof onMetaData.duration === 'number') { // duration
  8670. if (!this._durationOverrided) {
  8671. let duration = Math.floor(onMetaData.duration * this._timescale);
  8672. this._duration = duration;
  8673. this._mediaInfo.duration = duration;
  8674. }
  8675. } else {
  8676. this._mediaInfo.duration = 0;
  8677. }
  8678. if (typeof onMetaData.framerate === 'number') { // framerate
  8679. let fps_num = Math.floor(onMetaData.framerate * 1000);
  8680. if (fps_num > 0) {
  8681. let fps = fps_num / 1000;
  8682. this._referenceFrameRate.fixed = true;
  8683. this._referenceFrameRate.fps = fps;
  8684. this._referenceFrameRate.fps_num = fps_num;
  8685. this._referenceFrameRate.fps_den = 1000;
  8686. this._mediaInfo.fps = fps;
  8687. }
  8688. }
  8689. if (typeof onMetaData.keyframes === 'object') { // keyframes
  8690. this._mediaInfo.hasKeyframesIndex = true;
  8691. let keyframes = onMetaData.keyframes;
  8692. this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(keyframes);
  8693. onMetaData.keyframes = null; // keyframes has been extracted, remove it
  8694. } else {
  8695. this._mediaInfo.hasKeyframesIndex = false;
  8696. }
  8697. this._dispatch = false;
  8698. this._mediaInfo.metadata = onMetaData;
  8699. Log.v(this.TAG, 'Parsed onMetaData');
  8700. if (this._mediaInfo.isComplete()) {
  8701. this._onMediaInfo(this._mediaInfo);
  8702. }
  8703. }
  8704. }
  8705.  
  8706. _parseKeyframesIndex(keyframes) {
  8707. let times = [];
  8708. let filepositions = [];
  8709.  
  8710. // ignore first keyframe which is actually AVC Sequence Header (AVCDecoderConfigurationRecord)
  8711. for (let i = 1; i < keyframes.times.length; i++) {
  8712. let time = this._timestampBase + Math.floor(keyframes.times[i] * 1000);
  8713. times.push(time);
  8714. filepositions.push(keyframes.filepositions[i]);
  8715. }
  8716.  
  8717. return {
  8718. times: times,
  8719. filepositions: filepositions
  8720. };
  8721. }
  8722.  
  8723. _parseAudioData(arrayBuffer, dataOffset, dataSize, tagTimestamp) {
  8724. if (dataSize <= 1) {
  8725. Log.w(this.TAG, 'Flv: Invalid audio packet, missing SoundData payload!');
  8726. return;
  8727. }
  8728.  
  8729. if (this._hasAudioFlagOverrided === true && this._hasAudio === false) {
  8730. // If hasAudio: false indicated explicitly in MediaDataSource,
  8731. // Ignore all the audio packets
  8732. return;
  8733. }
  8734.  
  8735. let le = this._littleEndian;
  8736. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  8737.  
  8738. let soundSpec = v.getUint8(0);
  8739.  
  8740. let soundFormat = soundSpec >>> 4;
  8741. if (soundFormat !== 2 && soundFormat !== 10) { // MP3 or AAC
  8742. this._onError(DemuxErrors.CODEC_UNSUPPORTED, 'Flv: Unsupported audio codec idx: ' + soundFormat);
  8743. return;
  8744. }
  8745.  
  8746. let soundRate = 0;
  8747. let soundRateIndex = (soundSpec & 12) >>> 2;
  8748. if (soundRateIndex >= 0 && soundRateIndex <= 4) {
  8749. soundRate = this._flvSoundRateTable[soundRateIndex];
  8750. } else {
  8751. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid audio sample rate idx: ' + soundRateIndex);
  8752. return;
  8753. }
  8754. let soundType = (soundSpec & 1);
  8755.  
  8756.  
  8757. let meta = this._audioMetadata;
  8758. let track = this._audioTrack;
  8759.  
  8760. if (!meta) {
  8761. if (this._hasAudio === false && this._hasAudioFlagOverrided === false) {
  8762. this._hasAudio = true;
  8763. this._mediaInfo.hasAudio = true;
  8764. }
  8765.  
  8766. // initial metadata
  8767. meta = this._audioMetadata = {};
  8768. meta.type = 'audio';
  8769. meta.id = track.id;
  8770. meta.timescale = this._timescale;
  8771. meta.duration = this._duration;
  8772. meta.audioSampleRate = soundRate;
  8773. meta.channelCount = (soundType === 0 ? 1 : 2);
  8774. }
  8775.  
  8776. if (soundFormat === 10) { // AAC
  8777. let aacData = this._parseAACAudioData(arrayBuffer, dataOffset + 1, dataSize - 1);
  8778.  
  8779. if (aacData == undefined) {
  8780. return;
  8781. }
  8782.  
  8783. if (aacData.packetType === 0) { // AAC sequence header (AudioSpecificConfig)
  8784. if (meta.config) {
  8785. Log.w(this.TAG, 'Found another AudioSpecificConfig!');
  8786. }
  8787. let misc = aacData.data;
  8788. meta.audioSampleRate = misc.samplingRate;
  8789. meta.channelCount = misc.channelCount;
  8790. meta.codec = misc.codec;
  8791. meta.originalCodec = misc.originalCodec;
  8792. meta.config = misc.config;
  8793. // added by qli5
  8794. meta.configRaw = misc.configRaw;
  8795. // added by Xmader
  8796. meta.audioObjectType = misc.audioObjectType;
  8797. meta.samplingFrequencyIndex = misc.samplingIndex;
  8798. meta.channelConfig = misc.channelCount;
  8799. // The decode result of an aac sample is 1024 PCM samples
  8800. meta.refSampleDuration = 1024 / meta.audioSampleRate * meta.timescale;
  8801. Log.v(this.TAG, 'Parsed AudioSpecificConfig');
  8802.  
  8803. if (this._isInitialMetadataDispatched()) {
  8804. // Non-initial metadata, force dispatch (or flush) parsed frames to remuxer
  8805. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  8806. this._onDataAvailable(this._audioTrack, this._videoTrack);
  8807. }
  8808. } else {
  8809. this._audioInitialMetadataDispatched = true;
  8810. }
  8811. // then notify new metadata
  8812. this._dispatch = false;
  8813. this._onTrackMetadata('audio', meta);
  8814.  
  8815. let mi = this._mediaInfo;
  8816. mi.audioCodec = meta.originalCodec;
  8817. mi.audioSampleRate = meta.audioSampleRate;
  8818. mi.audioChannelCount = meta.channelCount;
  8819. if (mi.hasVideo) {
  8820. if (mi.videoCodec != null) {
  8821. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  8822. }
  8823. } else {
  8824. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  8825. }
  8826. if (mi.isComplete()) {
  8827. this._onMediaInfo(mi);
  8828. }
  8829. } else if (aacData.packetType === 1) { // AAC raw frame data
  8830. let dts = this._timestampBase + tagTimestamp;
  8831. let aacSample = { unit: aacData.data, length: aacData.data.byteLength, dts: dts, pts: dts };
  8832. track.samples.push(aacSample);
  8833. track.length += aacData.data.length;
  8834. } else {
  8835. Log.e(this.TAG, `Flv: Unsupported AAC data type ${aacData.packetType}`);
  8836. }
  8837. } else if (soundFormat === 2) { // MP3
  8838. if (!meta.codec) {
  8839. // We need metadata for mp3 audio track, extract info from frame header
  8840. let misc = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, true);
  8841. if (misc == undefined) {
  8842. return;
  8843. }
  8844. meta.audioSampleRate = misc.samplingRate;
  8845. meta.channelCount = misc.channelCount;
  8846. meta.codec = misc.codec;
  8847. meta.originalCodec = misc.originalCodec;
  8848. // The decode result of an mp3 sample is 1152 PCM samples
  8849. meta.refSampleDuration = 1152 / meta.audioSampleRate * meta.timescale;
  8850. Log.v(this.TAG, 'Parsed MPEG Audio Frame Header');
  8851.  
  8852. this._audioInitialMetadataDispatched = true;
  8853. this._onTrackMetadata('audio', meta);
  8854.  
  8855. let mi = this._mediaInfo;
  8856. mi.audioCodec = meta.codec;
  8857. mi.audioSampleRate = meta.audioSampleRate;
  8858. mi.audioChannelCount = meta.channelCount;
  8859. mi.audioDataRate = misc.bitRate;
  8860. if (mi.hasVideo) {
  8861. if (mi.videoCodec != null) {
  8862. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  8863. }
  8864. } else {
  8865. mi.mimeType = 'video/x-flv; codecs="' + mi.audioCodec + '"';
  8866. }
  8867. if (mi.isComplete()) {
  8868. this._onMediaInfo(mi);
  8869. }
  8870. }
  8871.  
  8872. // This packet is always a valid audio packet, extract it
  8873. let data = this._parseMP3AudioData(arrayBuffer, dataOffset + 1, dataSize - 1, false);
  8874. if (data == undefined) {
  8875. return;
  8876. }
  8877. let dts = this._timestampBase + tagTimestamp;
  8878. let mp3Sample = { unit: data, length: data.byteLength, dts: dts, pts: dts };
  8879. track.samples.push(mp3Sample);
  8880. track.length += data.length;
  8881. }
  8882. }
  8883.  
  8884. _parseAACAudioData(arrayBuffer, dataOffset, dataSize) {
  8885. if (dataSize <= 1) {
  8886. Log.w(this.TAG, 'Flv: Invalid AAC packet, missing AACPacketType or/and Data!');
  8887. return;
  8888. }
  8889.  
  8890. let result = {};
  8891. let array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  8892.  
  8893. result.packetType = array[0];
  8894.  
  8895. if (array[0] === 0) {
  8896. result.data = this._parseAACAudioSpecificConfig(arrayBuffer, dataOffset + 1, dataSize - 1);
  8897. } else {
  8898. result.data = array.subarray(1);
  8899. }
  8900.  
  8901. return result;
  8902. }
  8903.  
  8904. _parseAACAudioSpecificConfig(arrayBuffer, dataOffset, dataSize) {
  8905. let array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  8906. let config = null;
  8907.  
  8908. /* Audio Object Type:
  8909. 0: Null
  8910. 1: AAC Main
  8911. 2: AAC LC
  8912. 3: AAC SSR (Scalable Sample Rate)
  8913. 4: AAC LTP (Long Term Prediction)
  8914. 5: HE-AAC / SBR (Spectral Band Replication)
  8915. 6: AAC Scalable
  8916. */
  8917.  
  8918. let audioObjectType = 0;
  8919. let originalAudioObjectType = 0;
  8920. let samplingIndex = 0;
  8921. let extensionSamplingIndex = null;
  8922.  
  8923. // 5 bits
  8924. audioObjectType = originalAudioObjectType = array[0] >>> 3;
  8925. // 4 bits
  8926. samplingIndex = ((array[0] & 0x07) << 1) | (array[1] >>> 7);
  8927. if (samplingIndex < 0 || samplingIndex >= this._mpegSamplingRates.length) {
  8928. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: AAC invalid sampling frequency index!');
  8929. return;
  8930. }
  8931.  
  8932. let samplingFrequence = this._mpegSamplingRates[samplingIndex];
  8933.  
  8934. // 4 bits
  8935. let channelConfig = (array[1] & 0x78) >>> 3;
  8936. if (channelConfig < 0 || channelConfig >= 8) {
  8937. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: AAC invalid channel configuration');
  8938. return;
  8939. }
  8940.  
  8941. if (audioObjectType === 5) { // HE-AAC?
  8942. // 4 bits
  8943. extensionSamplingIndex = ((array[1] & 0x07) << 1) | (array[2] >>> 7);
  8944. }
  8945.  
  8946. // workarounds for various browsers
  8947. let userAgent = _navigator.userAgent.toLowerCase();
  8948.  
  8949. if (userAgent.indexOf('firefox') !== -1) {
  8950. // firefox: use SBR (HE-AAC) if freq less than 24kHz
  8951. if (samplingIndex >= 6) {
  8952. audioObjectType = 5;
  8953. config = new Array(4);
  8954. extensionSamplingIndex = samplingIndex - 3;
  8955. } else { // use LC-AAC
  8956. audioObjectType = 2;
  8957. config = new Array(2);
  8958. extensionSamplingIndex = samplingIndex;
  8959. }
  8960. } else if (userAgent.indexOf('android') !== -1) {
  8961. // android: always use LC-AAC
  8962. audioObjectType = 2;
  8963. config = new Array(2);
  8964. extensionSamplingIndex = samplingIndex;
  8965. } else {
  8966. // for other browsers, e.g. chrome...
  8967. // Always use HE-AAC to make it easier to switch aac codec profile
  8968. audioObjectType = 5;
  8969. extensionSamplingIndex = samplingIndex;
  8970. config = new Array(4);
  8971.  
  8972. if (samplingIndex >= 6) {
  8973. extensionSamplingIndex = samplingIndex - 3;
  8974. } else if (channelConfig === 1) { // Mono channel
  8975. audioObjectType = 2;
  8976. config = new Array(2);
  8977. extensionSamplingIndex = samplingIndex;
  8978. }
  8979. }
  8980.  
  8981. config[0] = audioObjectType << 3;
  8982. config[0] |= (samplingIndex & 0x0F) >>> 1;
  8983. config[1] = (samplingIndex & 0x0F) << 7;
  8984. config[1] |= (channelConfig & 0x0F) << 3;
  8985. if (audioObjectType === 5) {
  8986. config[1] |= ((extensionSamplingIndex & 0x0F) >>> 1);
  8987. config[2] = (extensionSamplingIndex & 0x01) << 7;
  8988. // extended audio object type: force to 2 (LC-AAC)
  8989. config[2] |= (2 << 2);
  8990. config[3] = 0;
  8991. }
  8992.  
  8993. return {
  8994. audioObjectType, // audio_object_type, added by Xmader
  8995. samplingIndex, // sampling_frequency_index, added by Xmader
  8996. configRaw: array, // added by qli5
  8997. config: config,
  8998. samplingRate: samplingFrequence,
  8999. channelCount: channelConfig, // channel_config
  9000. codec: 'mp4a.40.' + audioObjectType,
  9001. originalCodec: 'mp4a.40.' + originalAudioObjectType
  9002. };
  9003. }
  9004.  
  9005. _parseMP3AudioData(arrayBuffer, dataOffset, dataSize, requestHeader) {
  9006. if (dataSize < 4) {
  9007. Log.w(this.TAG, 'Flv: Invalid MP3 packet, header missing!');
  9008. return;
  9009. }
  9010.  
  9011. let le = this._littleEndian;
  9012. let array = new Uint8Array(arrayBuffer, dataOffset, dataSize);
  9013. let result = null;
  9014.  
  9015. if (requestHeader) {
  9016. if (array[0] !== 0xFF) {
  9017. return;
  9018. }
  9019. let ver = (array[1] >>> 3) & 0x03;
  9020. let layer = (array[1] & 0x06) >> 1;
  9021.  
  9022. let bitrate_index = (array[2] & 0xF0) >>> 4;
  9023. let sampling_freq_index = (array[2] & 0x0C) >>> 2;
  9024.  
  9025. let channel_mode = (array[3] >>> 6) & 0x03;
  9026. let channel_count = channel_mode !== 3 ? 2 : 1;
  9027.  
  9028. let sample_rate = 0;
  9029. let bit_rate = 0;
  9030.  
  9031. let codec = 'mp3';
  9032.  
  9033. switch (ver) {
  9034. case 0: // MPEG 2.5
  9035. sample_rate = this._mpegAudioV25SampleRateTable[sampling_freq_index];
  9036. break;
  9037. case 2: // MPEG 2
  9038. sample_rate = this._mpegAudioV20SampleRateTable[sampling_freq_index];
  9039. break;
  9040. case 3: // MPEG 1
  9041. sample_rate = this._mpegAudioV10SampleRateTable[sampling_freq_index];
  9042. break;
  9043. }
  9044.  
  9045. switch (layer) {
  9046. case 1: // Layer 3
  9047. if (bitrate_index < this._mpegAudioL3BitRateTable.length) {
  9048. bit_rate = this._mpegAudioL3BitRateTable[bitrate_index];
  9049. }
  9050. break;
  9051. case 2: // Layer 2
  9052. if (bitrate_index < this._mpegAudioL2BitRateTable.length) {
  9053. bit_rate = this._mpegAudioL2BitRateTable[bitrate_index];
  9054. }
  9055. break;
  9056. case 3: // Layer 1
  9057. if (bitrate_index < this._mpegAudioL1BitRateTable.length) {
  9058. bit_rate = this._mpegAudioL1BitRateTable[bitrate_index];
  9059. }
  9060. break;
  9061. }
  9062.  
  9063. result = {
  9064. bitRate: bit_rate,
  9065. samplingRate: sample_rate,
  9066. channelCount: channel_count,
  9067. codec: codec,
  9068. originalCodec: codec
  9069. };
  9070. } else {
  9071. result = array;
  9072. }
  9073.  
  9074. return result;
  9075. }
  9076.  
  9077. _parseVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition) {
  9078. if (dataSize <= 1) {
  9079. Log.w(this.TAG, 'Flv: Invalid video packet, missing VideoData payload!');
  9080. return;
  9081. }
  9082.  
  9083. if (this._hasVideoFlagOverrided === true && this._hasVideo === false) {
  9084. // If hasVideo: false indicated explicitly in MediaDataSource,
  9085. // Ignore all the video packets
  9086. return;
  9087. }
  9088.  
  9089. let spec = (new Uint8Array(arrayBuffer, dataOffset, dataSize))[0];
  9090.  
  9091. let frameType = (spec & 240) >>> 4;
  9092. let codecId = spec & 15;
  9093.  
  9094. if (codecId !== 7) {
  9095. this._onError(DemuxErrors.CODEC_UNSUPPORTED, `Flv: Unsupported codec in video frame: ${codecId}`);
  9096. return;
  9097. }
  9098.  
  9099. this._parseAVCVideoPacket(arrayBuffer, dataOffset + 1, dataSize - 1, tagTimestamp, tagPosition, frameType);
  9100. }
  9101.  
  9102. _parseAVCVideoPacket(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType) {
  9103. if (dataSize < 4) {
  9104. Log.w(this.TAG, 'Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime');
  9105. return;
  9106. }
  9107.  
  9108. let le = this._littleEndian;
  9109. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  9110.  
  9111. let packetType = v.getUint8(0);
  9112. let cts = v.getUint32(0, !le) & 0x00FFFFFF;
  9113.  
  9114. if (packetType === 0) { // AVCDecoderConfigurationRecord
  9115. this._parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset + 4, dataSize - 4);
  9116. } else if (packetType === 1) { // One or more Nalus
  9117. this._parseAVCVideoData(arrayBuffer, dataOffset + 4, dataSize - 4, tagTimestamp, tagPosition, frameType, cts);
  9118. } else if (packetType === 2) {
  9119. // empty, AVC end of sequence
  9120. } else {
  9121. this._onError(DemuxErrors.FORMAT_ERROR, `Flv: Invalid video packet type ${packetType}`);
  9122. return;
  9123. }
  9124. }
  9125.  
  9126. _parseAVCDecoderConfigurationRecord(arrayBuffer, dataOffset, dataSize) {
  9127. if (dataSize < 7) {
  9128. Log.w(this.TAG, 'Flv: Invalid AVCDecoderConfigurationRecord, lack of data!');
  9129. return;
  9130. }
  9131.  
  9132. let meta = this._videoMetadata;
  9133. let track = this._videoTrack;
  9134. let le = this._littleEndian;
  9135. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  9136.  
  9137. if (!meta) {
  9138. if (this._hasVideo === false && this._hasVideoFlagOverrided === false) {
  9139. this._hasVideo = true;
  9140. this._mediaInfo.hasVideo = true;
  9141. }
  9142.  
  9143. meta = this._videoMetadata = {};
  9144. meta.type = 'video';
  9145. meta.id = track.id;
  9146. meta.timescale = this._timescale;
  9147. meta.duration = this._duration;
  9148. } else {
  9149. if (typeof meta.avcc !== 'undefined') {
  9150. Log.w(this.TAG, 'Found another AVCDecoderConfigurationRecord!');
  9151. }
  9152. }
  9153.  
  9154. let version = v.getUint8(0); // configurationVersion
  9155. let avcProfile = v.getUint8(1); // avcProfileIndication
  9156. let profileCompatibility = v.getUint8(2); // profile_compatibility
  9157. let avcLevel = v.getUint8(3); // AVCLevelIndication
  9158.  
  9159. if (version !== 1 || avcProfile === 0) {
  9160. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord');
  9161. return;
  9162. }
  9163.  
  9164. this._naluLengthSize = (v.getUint8(4) & 3) + 1; // lengthSizeMinusOne
  9165. if (this._naluLengthSize !== 3 && this._naluLengthSize !== 4) { // holy shit!!!
  9166. this._onError(DemuxErrors.FORMAT_ERROR, `Flv: Strange NaluLengthSizeMinusOne: ${this._naluLengthSize - 1}`);
  9167. return;
  9168. }
  9169.  
  9170. let spsCount = v.getUint8(5) & 31; // numOfSequenceParameterSets
  9171. if (spsCount === 0) {
  9172. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No SPS');
  9173. return;
  9174. } else if (spsCount > 1) {
  9175. Log.w(this.TAG, `Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ${spsCount}`);
  9176. }
  9177.  
  9178. let offset = 6;
  9179.  
  9180. for (let i = 0; i < spsCount; i++) {
  9181. let len = v.getUint16(offset, !le); // sequenceParameterSetLength
  9182. offset += 2;
  9183.  
  9184. if (len === 0) {
  9185. continue;
  9186. }
  9187.  
  9188. // Notice: Nalu without startcode header (00 00 00 01)
  9189. let sps = new Uint8Array(arrayBuffer, dataOffset + offset, len);
  9190. offset += len;
  9191.  
  9192. let config = SPSParser.parseSPS(sps);
  9193. if (i !== 0) {
  9194. // ignore other sps's config
  9195. continue;
  9196. }
  9197.  
  9198. meta.codecWidth = config.codec_size.width;
  9199. meta.codecHeight = config.codec_size.height;
  9200. meta.presentWidth = config.present_size.width;
  9201. meta.presentHeight = config.present_size.height;
  9202.  
  9203. meta.profile = config.profile_string;
  9204. meta.level = config.level_string;
  9205. meta.bitDepth = config.bit_depth;
  9206. meta.chromaFormat = config.chroma_format;
  9207. meta.sarRatio = config.sar_ratio;
  9208. meta.frameRate = config.frame_rate;
  9209.  
  9210. if (config.frame_rate.fixed === false ||
  9211. config.frame_rate.fps_num === 0 ||
  9212. config.frame_rate.fps_den === 0) {
  9213. meta.frameRate = this._referenceFrameRate;
  9214. }
  9215.  
  9216. let fps_den = meta.frameRate.fps_den;
  9217. let fps_num = meta.frameRate.fps_num;
  9218. meta.refSampleDuration = meta.timescale * (fps_den / fps_num);
  9219.  
  9220. let codecArray = sps.subarray(1, 4);
  9221. let codecString = 'avc1.';
  9222. for (let j = 0; j < 3; j++) {
  9223. let h = codecArray[j].toString(16);
  9224. if (h.length < 2) {
  9225. h = '0' + h;
  9226. }
  9227. codecString += h;
  9228. }
  9229. meta.codec = codecString;
  9230.  
  9231. let mi = this._mediaInfo;
  9232. mi.width = meta.codecWidth;
  9233. mi.height = meta.codecHeight;
  9234. mi.fps = meta.frameRate.fps;
  9235. mi.profile = meta.profile;
  9236. mi.level = meta.level;
  9237. mi.chromaFormat = config.chroma_format_string;
  9238. mi.sarNum = meta.sarRatio.width;
  9239. mi.sarDen = meta.sarRatio.height;
  9240. mi.videoCodec = codecString;
  9241.  
  9242. if (mi.hasAudio) {
  9243. if (mi.audioCodec != null) {
  9244. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + ',' + mi.audioCodec + '"';
  9245. }
  9246. } else {
  9247. mi.mimeType = 'video/x-flv; codecs="' + mi.videoCodec + '"';
  9248. }
  9249. if (mi.isComplete()) {
  9250. this._onMediaInfo(mi);
  9251. }
  9252. }
  9253.  
  9254. let ppsCount = v.getUint8(offset); // numOfPictureParameterSets
  9255. if (ppsCount === 0) {
  9256. this._onError(DemuxErrors.FORMAT_ERROR, 'Flv: Invalid AVCDecoderConfigurationRecord: No PPS');
  9257. return;
  9258. } else if (ppsCount > 1) {
  9259. Log.w(this.TAG, `Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ${ppsCount}`);
  9260. }
  9261.  
  9262. offset++;
  9263.  
  9264. for (let i = 0; i < ppsCount; i++) {
  9265. let len = v.getUint16(offset, !le); // pictureParameterSetLength
  9266. offset += 2;
  9267.  
  9268. if (len === 0) {
  9269. continue;
  9270. }
  9271.  
  9272. // pps is useless for extracting video information
  9273. offset += len;
  9274. }
  9275.  
  9276. meta.avcc = new Uint8Array(dataSize);
  9277. meta.avcc.set(new Uint8Array(arrayBuffer, dataOffset, dataSize), 0);
  9278. Log.v(this.TAG, 'Parsed AVCDecoderConfigurationRecord');
  9279.  
  9280. if (this._isInitialMetadataDispatched()) {
  9281. // flush parsed frames
  9282. if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {
  9283. this._onDataAvailable(this._audioTrack, this._videoTrack);
  9284. }
  9285. } else {
  9286. this._videoInitialMetadataDispatched = true;
  9287. }
  9288. // notify new metadata
  9289. this._dispatch = false;
  9290. this._onTrackMetadata('video', meta);
  9291. }
  9292.  
  9293. _parseAVCVideoData(arrayBuffer, dataOffset, dataSize, tagTimestamp, tagPosition, frameType, cts) {
  9294. let le = this._littleEndian;
  9295. let v = new DataView(arrayBuffer, dataOffset, dataSize);
  9296.  
  9297. let units = [], length = 0;
  9298.  
  9299. let offset = 0;
  9300. const lengthSize = this._naluLengthSize;
  9301. let dts = this._timestampBase + tagTimestamp;
  9302. let keyframe = (frameType === 1); // from FLV Frame Type constants
  9303. let refIdc = 1; // added by qli5
  9304.  
  9305. while (offset < dataSize) {
  9306. if (offset + 4 >= dataSize) {
  9307. Log.w(this.TAG, `Malformed Nalu near timestamp ${dts}, offset = ${offset}, dataSize = ${dataSize}`);
  9308. break; // data not enough for next Nalu
  9309. }
  9310. // Nalu with length-header (AVC1)
  9311. let naluSize = v.getUint32(offset, !le); // Big-Endian read
  9312. if (lengthSize === 3) {
  9313. naluSize >>>= 8;
  9314. }
  9315. if (naluSize > dataSize - lengthSize) {
  9316. Log.w(this.TAG, `Malformed Nalus near timestamp ${dts}, NaluSize > DataSize!`);
  9317. return;
  9318. }
  9319.  
  9320. let unitType = v.getUint8(offset + lengthSize) & 0x1F;
  9321. // added by qli5
  9322. refIdc = v.getUint8(offset + lengthSize) & 0x60;
  9323.  
  9324. if (unitType === 5) { // IDR
  9325. keyframe = true;
  9326. }
  9327.  
  9328. let data = new Uint8Array(arrayBuffer, dataOffset + offset, lengthSize + naluSize);
  9329. let unit = { type: unitType, data: data };
  9330. units.push(unit);
  9331. length += data.byteLength;
  9332.  
  9333. offset += lengthSize + naluSize;
  9334. }
  9335.  
  9336. if (units.length) {
  9337. let track = this._videoTrack;
  9338. let avcSample = {
  9339. units: units,
  9340. length: length,
  9341. isKeyframe: keyframe,
  9342. refIdc: refIdc,
  9343. dts: dts,
  9344. cts: cts,
  9345. pts: (dts + cts)
  9346. };
  9347. if (keyframe) {
  9348. avcSample.fileposition = tagPosition;
  9349. }
  9350. track.samples.push(avcSample);
  9351. track.length += length;
  9352. }
  9353. }
  9354.  
  9355. }
  9356.  
  9357. /**
  9358. * Copyright (C) 2018 Xmader.
  9359. * @author Xmader
  9360. */
  9361.  
  9362. /**
  9363. * 计算adts头部
  9364. * @see https://blog.jianchihu.net/flv-aac-add-adtsheader.html
  9365. * @typedef {Object} AdtsHeadersInit
  9366. * @property {number} audioObjectType
  9367. * @property {number} samplingFrequencyIndex
  9368. * @property {number} channelConfig
  9369. * @property {number} adtsLen
  9370. * @param {AdtsHeadersInit} init
  9371. */
  9372. const getAdtsHeaders = (init) => {
  9373. const { audioObjectType, samplingFrequencyIndex, channelConfig, adtsLen } = init;
  9374. const headers = new Uint8Array(7);
  9375.  
  9376. headers[0] = 0xff; // syncword:0xfff 高8bits
  9377. headers[1] = 0xf0; // syncword:0xfff 低4bits
  9378. headers[1] |= (0 << 3); // MPEG Version:0 for MPEG-4,1 for MPEG-2 1bit
  9379. headers[1] |= (0 << 1); // Layer:0 2bits
  9380. headers[1] |= 1; // protection absent:1 1bit
  9381.  
  9382. headers[2] = (audioObjectType - 1) << 6; // profile:audio_object_type - 1 2bits
  9383. headers[2] |= (samplingFrequencyIndex & 0x0f) << 2; // sampling frequency index:sampling_frequency_index 4bits
  9384. headers[2] |= (0 << 1); // private bit:0 1bit
  9385. headers[2] |= (channelConfig & 0x04) >> 2; // channel configuration:channel_config 高1bit
  9386.  
  9387. headers[3] = (channelConfig & 0x03) << 6; // channel configuration:channel_config 低2bits
  9388. headers[3] |= (0 << 5); // original:0 1bit
  9389. headers[3] |= (0 << 4); // home:0 1bit
  9390. headers[3] |= (0 << 3); // copyright id bit:0 1bit
  9391. headers[3] |= (0 << 2); // copyright id start:0 1bit
  9392.  
  9393. headers[3] |= (adtsLen & 0x1800) >> 11; // frame length:value 高2bits
  9394. headers[4] = (adtsLen & 0x7f8) >> 3; // frame length:value 中间8bits
  9395. headers[5] = (adtsLen & 0x7) << 5; // frame length:value 低3bits
  9396. headers[5] |= 0x1f; // buffer fullness:0x7ff 高5bits
  9397. headers[6] = 0xfc;
  9398.  
  9399. return headers
  9400. };
  9401.  
  9402. /**
  9403. * Copyright (C) 2018 Xmader.
  9404. * @author Xmader
  9405. */
  9406.  
  9407. /**
  9408. * Demux FLV into H264 + AAC stream into line stream then
  9409. * remux it into a AAC file.
  9410. * @param {Blob|Buffer|ArrayBuffer|string} flv
  9411. */
  9412. const FLV2AAC = async (flv) => {
  9413.  
  9414. // load flv as arraybuffer
  9415. /** @type {ArrayBuffer} */
  9416. const flvArrayBuffer = await new Promise((r, j) => {
  9417. if ((typeof Blob != "undefined") && (flv instanceof Blob)) {
  9418. const reader = new FileReader();
  9419. reader.onload = () => {
  9420. /** @type {ArrayBuffer} */
  9421. // @ts-ignore
  9422. const result = reader.result;
  9423. r(result);
  9424. };
  9425. reader.onerror = j;
  9426. reader.readAsArrayBuffer(flv);
  9427. } else if ((typeof Buffer != "undefined") && (flv instanceof Buffer)) {
  9428. r(new Uint8Array(flv).buffer);
  9429. } else if (flv instanceof ArrayBuffer) {
  9430. r(flv);
  9431. } else if (typeof flv == 'string') {
  9432. const req = new XMLHttpRequest();
  9433. req.responseType = "arraybuffer";
  9434. req.onload = () => r(req.response);
  9435. req.onerror = j;
  9436. req.open('get', flv);
  9437. req.send();
  9438. } else {
  9439. j(new TypeError("@type {Blob|Buffer|ArrayBuffer} flv"));
  9440. }
  9441. });
  9442.  
  9443. const flvProbeData = FLVDemuxer.probe(flvArrayBuffer);
  9444. const flvDemuxer = new FLVDemuxer(flvProbeData);
  9445.  
  9446. // 只解析音频
  9447. flvDemuxer.overridedHasVideo = false;
  9448.  
  9449. /**
  9450. * @typedef {Object} Sample
  9451. * @property {Uint8Array} unit
  9452. * @property {number} length
  9453. * @property {number} dts
  9454. * @property {number} pts
  9455. */
  9456.  
  9457. /** @type {{ type: "audio"; id: number; sequenceNumber: number; length: number; samples: Sample[]; }} */
  9458. let aac = null;
  9459. let metadata = null;
  9460.  
  9461. flvDemuxer.onTrackMetadata = (type, _metaData) => {
  9462. if (type == "audio") {
  9463. metadata = _metaData;
  9464. }
  9465. };
  9466.  
  9467. flvDemuxer.onMediaInfo = () => { };
  9468.  
  9469. flvDemuxer.onError = (e) => {
  9470. throw new Error(e)
  9471. };
  9472.  
  9473. flvDemuxer.onDataAvailable = (...args) => {
  9474. args.forEach(data => {
  9475. if (data.type == "audio") {
  9476. aac = data;
  9477. }
  9478. });
  9479. };
  9480.  
  9481. const finalOffset = flvDemuxer.parseChunks(flvArrayBuffer, flvProbeData.dataOffset);
  9482. if (finalOffset != flvArrayBuffer.byteLength) {
  9483. throw new Error("FLVDemuxer: unexpected EOF")
  9484. }
  9485.  
  9486. const {
  9487. audioObjectType,
  9488. samplingFrequencyIndex,
  9489. channelCount: channelConfig
  9490. } = metadata;
  9491.  
  9492. /** @type {number[]} */
  9493. let output = [];
  9494.  
  9495. aac.samples.forEach((sample) => {
  9496. const headers = getAdtsHeaders({
  9497. audioObjectType,
  9498. samplingFrequencyIndex,
  9499. channelConfig,
  9500. adtsLen: sample.length + 7
  9501. });
  9502. output.push(...headers, ...sample.unit);
  9503. });
  9504.  
  9505. return new Uint8Array(output)
  9506. };
  9507.  
  9508. /***
  9509. * Copyright (C) 2018 Xmader. All Rights Reserved.
  9510. *
  9511. * @author Xmader
  9512. *
  9513. * This Source Code Form is subject to the terms of the Mozilla Public
  9514. * License, v. 2.0. If a copy of the MPL was not distributed with this
  9515. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9516. */
  9517.  
  9518. class WebWorker extends Worker {
  9519. constructor(stringUrl) {
  9520. super(stringUrl);
  9521.  
  9522. this.importFnAsAScript(TwentyFourDataView);
  9523. this.importFnAsAScript(FLVTag);
  9524. this.importFnAsAScript(FLV);
  9525. }
  9526.  
  9527. /**
  9528. * @param {string} method
  9529. * @param {*} data
  9530. */
  9531. async getReturnValue(method, data) {
  9532. const callbackNum = window.crypto.getRandomValues(new Uint32Array(1))[0];
  9533.  
  9534. this.postMessage([
  9535. method,
  9536. data,
  9537. callbackNum
  9538. ]);
  9539.  
  9540. return await new Promise((resolve, reject) => {
  9541. this.addEventListener("message", (e) => {
  9542. const [_method, incomingData, _callbackNum] = e.data;
  9543. if (_callbackNum == callbackNum) {
  9544. if (_method == method) {
  9545. resolve(incomingData);
  9546. } else if (_method == "error") {
  9547. console.error(incomingData);
  9548. reject(new Error("Web Worker 内部错误"));
  9549. }
  9550. }
  9551. });
  9552. })
  9553. }
  9554.  
  9555. async registerAllMethods() {
  9556. const methods = await this.getReturnValue("getAllMethods");
  9557.  
  9558. methods.forEach(method => {
  9559. Object.defineProperty(this, method, {
  9560. value: (arg) => this.getReturnValue(method, arg)
  9561. });
  9562. });
  9563. }
  9564.  
  9565. /**
  9566. * @param {Function | ClassDecorator} c
  9567. */
  9568. importFnAsAScript(c) {
  9569. const blob = new Blob([c.toString()], { type: 'application/javascript' });
  9570. return this.getReturnValue("importScripts", URL.createObjectURL(blob))
  9571. }
  9572.  
  9573. /**
  9574. * @param {() => void} fn
  9575. */
  9576. static fromAFunction(fn) {
  9577. const blob = new Blob(['(' + fn.toString() + ')()'], { type: 'application/javascript' });
  9578. return new WebWorker(URL.createObjectURL(blob))
  9579. }
  9580. }
  9581.  
  9582. // 用于批量下载的 Web Worker , 请将函数中的内容想象成一个独立的js文件
  9583. const BatchDownloadWorkerFn = () => {
  9584.  
  9585. class BatchDownloadWorker {
  9586. async mergeFLVFiles(files) {
  9587. return await FLV.mergeBlobs(files);
  9588. }
  9589.  
  9590. /**
  9591. * 引入脚本与库
  9592. * @param {string[]} scripts
  9593. */
  9594. importScripts(...scripts) {
  9595. importScripts(...scripts);
  9596. }
  9597.  
  9598. getAllMethods() {
  9599. return Object.getOwnPropertyNames(BatchDownloadWorker.prototype).slice(1, -1)
  9600. }
  9601. }
  9602.  
  9603. const worker = new BatchDownloadWorker();
  9604.  
  9605. onmessage = async (e) => {
  9606. const [method, incomingData, callbackNum] = e.data;
  9607.  
  9608. try {
  9609. const returnValue = await worker[method](incomingData);
  9610. if (returnValue) {
  9611. postMessage([
  9612. method,
  9613. returnValue,
  9614. callbackNum
  9615. ]);
  9616. }
  9617. } catch (e) {
  9618. postMessage([
  9619. "error",
  9620. e.message,
  9621. callbackNum
  9622. ]);
  9623. throw e
  9624. }
  9625. };
  9626. };
  9627.  
  9628. // @ts-check
  9629.  
  9630. /**
  9631. * @param {number} alpha 0~255
  9632. */
  9633. const formatColorChannel$1 = (alpha) => {
  9634. return (alpha & 255).toString(16).toUpperCase().padStart(2, '0')
  9635. };
  9636.  
  9637. /**
  9638. * @param {number} opacity 0 ~ 1 -> alpha 0 ~ 255
  9639. */
  9640. const formatOpacity = (opacity) => {
  9641. const alpha = 0xFF * (100 - +opacity * 100) / 100;
  9642. return formatColorChannel$1(alpha)
  9643. };
  9644.  
  9645. /**
  9646. * "#xxxxxx" -> "xxxxxx"
  9647. * @param {string} colorStr
  9648. */
  9649. const formatColor$1 = (colorStr) => {
  9650. colorStr = colorStr.toUpperCase();
  9651. const m = colorStr.match(/^#?(\w{6})$/);
  9652. return m[1]
  9653. };
  9654.  
  9655. const buildHeader = ({
  9656. title = "",
  9657. original = "",
  9658. fontFamily = "Arial",
  9659. bold = false,
  9660. textColor = "#FFFFFF",
  9661. bgColor = "#000000",
  9662. textOpacity = 1.0,
  9663. bgOpacity = 0.5,
  9664. fontsizeRatio = 0.4,
  9665. baseFontsize = 50,
  9666. playResX = 560,
  9667. playResY = 420,
  9668. }) => {
  9669. textColor = formatColor$1(textColor);
  9670. bgColor = formatColor$1(bgColor);
  9671.  
  9672. const boldFlag = bold ? -1 : 0;
  9673. const fontSize = Math.round(fontsizeRatio * baseFontsize);
  9674. const textAlpha = formatOpacity(textOpacity);
  9675. const bgAlpha = formatOpacity(bgOpacity);
  9676.  
  9677. return [
  9678. "[Script Info]",
  9679. `Title: ${title}`,
  9680. `Original Script: ${original}`,
  9681. "ScriptType: v4.00+",
  9682. "Collisions: Normal",
  9683. `PlayResX: ${playResX}`,
  9684. `PlayResY: ${playResY}`,
  9685. "Timer: 100.0000",
  9686. "",
  9687. "[V4+ Styles]",
  9688. "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
  9689. `Style: CC,${fontFamily},${fontSize},&H${textAlpha}${textColor},&H${textAlpha}${textColor},&H${textAlpha}000000,&H${bgAlpha}${bgColor},${boldFlag},0,0,0,100,100,0,0,1,2,0,2,20,20,2,0`,
  9690. "",
  9691. "[Events]",
  9692. "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
  9693. ]
  9694. };
  9695.  
  9696. /**
  9697. * @param {number} time
  9698. */
  9699. const formatTimestamp$1 = (time) => {
  9700. const value = Math.round(time * 100) * 10;
  9701. const rem = value % 3600000;
  9702. const hour = (value - rem) / 3600000;
  9703. const fHour = hour.toFixed(0).padStart(2, '0');
  9704. const fRem = new Date(rem).toISOString().slice(-11, -2);
  9705. return fHour + fRem
  9706. };
  9707.  
  9708. /**
  9709. * @param {string} str
  9710. */
  9711. const textEscape$1 = (str) => {
  9712. // VSFilter do not support escaped "{" or "}"; we use full-width version instead
  9713. return str.replace(/{/g, '{').replace(/}/g, '}').replace(/\s/g, ' ')
  9714. };
  9715.  
  9716. /**
  9717. * @param {import("./index").Dialogue} dialogue
  9718. */
  9719. const buildLine = (dialogue) => {
  9720. const start = formatTimestamp$1(dialogue.from);
  9721. const end = formatTimestamp$1(dialogue.to);
  9722. const text = textEscape$1(dialogue.content);
  9723. return `Dialogue: 0,${start},${end},CC,,20,20,2,,${text}`
  9724. };
  9725.  
  9726. /**
  9727. * @param {import("./index").SubtitleData} subtitleData
  9728. * @param {string} languageDoc 字幕语言描述,例如 "英语(美国)"
  9729. */
  9730. const buildAss = (subtitleData, languageDoc = "") => {
  9731. const pageTitle = top.document.title.replace(/_哔哩哔哩 \(゜-゜\)つロ 干杯~-bilibili$/, "");
  9732. const title = `${pageTitle} ${languageDoc || ""}字幕`;
  9733. const url = top.location.href;
  9734. const original = `Generated by Xmader/bilitwin based on ${url}`;
  9735.  
  9736. const header = buildHeader({
  9737. title,
  9738. original,
  9739. fontsizeRatio: subtitleData.font_size,
  9740. textColor: subtitleData.font_color,
  9741. bgOpacity: subtitleData.background_alpha,
  9742. bgColor: subtitleData.background_color,
  9743. });
  9744.  
  9745. const lines = subtitleData.body.map(buildLine);
  9746.  
  9747. return [
  9748. ...header,
  9749. ...lines,
  9750. ].join('\r\n')
  9751. };
  9752.  
  9753. // @ts-check
  9754.  
  9755. /**
  9756. * 获取视频信息
  9757. * @param {number} aid
  9758. * @param {number} cid
  9759. */
  9760. const getVideoInfo = async (aid, cid) => {
  9761. const url = `https://api.bilibili.com/x/web-interface/view?aid=${aid}&cid=${cid}`;
  9762.  
  9763. const res = await fetch(url);
  9764. if (!res.ok) {
  9765. throw new Error(`${res.status} ${res.statusText}`)
  9766. }
  9767.  
  9768. const json = await res.json();
  9769. return json.data
  9770. };
  9771.  
  9772. /**
  9773. * @typedef {Object} SubtitleInfo 字幕信息
  9774. * @property {number} id
  9775. * @property {string} lan 字幕语言,例如 "en-US"
  9776. * @property {string} lan_doc 字幕语言描述,例如 "英语(美国)"
  9777. * @property {boolean} is_lock 是否字幕可以在视频上拖动
  9778. * @property {string} subtitle_url 指向字幕数据 json 的 url
  9779. * @property {object} author 作者信息
  9780. */
  9781.  
  9782. /**
  9783. * 获取字幕信息列表
  9784. * @param {number} aid
  9785. * @param {number} cid
  9786. * @returns {Promise<SubtitleInfo[]>}
  9787. */
  9788. const getSubtitleInfoList = async (aid, cid) => {
  9789. try {
  9790. const videoinfo = await getVideoInfo(aid, cid);
  9791. return videoinfo.subtitle.list
  9792. } catch (error) {
  9793. return []
  9794. }
  9795. };
  9796.  
  9797. /**
  9798. * @typedef {Object} Dialogue
  9799. * @property {number} from 开始时间
  9800. * @property {number} to 结束时间
  9801. * @property {number} location 默认 2
  9802. * @property {string} content 字幕内容
  9803. */
  9804.  
  9805. /**
  9806. * @typedef {Object} SubtitleData 字幕数据
  9807. * @property {number} font_size 默认 0.4
  9808. * @property {string} font_color 默认 "#FFFFFF"
  9809. * @property {number} background_alpha 默认 0.5
  9810. * @property {string} background_color 默认 "#9C27B0"
  9811. * @property {string} Stroke 默认 "none"
  9812. * @property {Dialogue[]} body
  9813. */
  9814.  
  9815. /**
  9816. * @param {string} subtitle_url 指向字幕数据 json 的 url
  9817. * @returns {Promise<SubtitleData>}
  9818. */
  9819. const getSubtitleData = async (subtitle_url) => {
  9820. subtitle_url = subtitle_url.replace(/^http:/, "https:");
  9821.  
  9822. const res = await fetch(subtitle_url);
  9823. if (!res.ok) {
  9824. throw new Error(`${res.status} ${res.statusText}`)
  9825. }
  9826.  
  9827. const data = await res.json();
  9828. return data
  9829. };
  9830.  
  9831. /**
  9832. * @param {number} aid
  9833. * @param {number} cid
  9834. */
  9835. const getSubtitles = async (aid, cid) => {
  9836. const list = await getSubtitleInfoList(aid, cid);
  9837. return await Promise.all(
  9838. list.map(async (info) => {
  9839. const subtitleData = await getSubtitleData(info.subtitle_url);
  9840. return {
  9841. language: info.lan,
  9842. language_doc: info.lan_doc,
  9843. url: info.subtitle_url,
  9844. data: subtitleData,
  9845. ass: buildAss(subtitleData, info.lan_doc),
  9846. }
  9847. })
  9848. )
  9849. };
  9850.  
  9851. /***
  9852. * Copyright (C) 2018 Qli5. All Rights Reserved.
  9853. *
  9854. * @author qli5 <goodlq11[at](163|gmail).com>
  9855. *
  9856. * This Source Code Form is subject to the terms of the Mozilla Public
  9857. * License, v. 2.0. If a copy of the MPL was not distributed with this
  9858. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9859. */
  9860.  
  9861. class UI {
  9862. constructor(twin, option = UI.optionDefaults) {
  9863. this.twin = twin;
  9864. this.option = option;
  9865.  
  9866. this.destroy = new HookedFunction();
  9867. this.dom = {};
  9868. this.cidSessionDestroy = new HookedFunction();
  9869. this.cidSessionDom = {};
  9870.  
  9871. this.destroy.addCallback(this.cidSessionDestroy.bind(this));
  9872.  
  9873. this.destroy.addCallback(() => {
  9874. Object.values(this.dom).forEach(e => typeof e.remove == "function" && e.remove());
  9875. this.dom = {};
  9876. });
  9877. this.cidSessionDestroy.addCallback(() => {
  9878. Object.values(this.cidSessionDom).forEach(e => typeof e.remove == "function" && e.remove());
  9879. this.cidSessionDom = {};
  9880. });
  9881.  
  9882. this.styleClearance();
  9883. }
  9884.  
  9885. styleClearance() {
  9886. let ret = `
  9887. .bilibili-player-context-menu-container.black ul.bilitwin li.context-menu-function > a:hover {
  9888. background: rgba(255,255,255,.12);
  9889. transition: all .3s ease-in-out;
  9890. cursor: pointer;
  9891. }
  9892.  
  9893. .bilitwin a {
  9894. cursor: pointer;
  9895. color: #00a1d6;
  9896. }
  9897.  
  9898. .bilitwin a:hover {
  9899. color: #f25d8e;
  9900. }
  9901.  
  9902. .bilitwin button {
  9903. color: #fff;
  9904. cursor: pointer;
  9905. text-align: center;
  9906. border-radius: 4px;
  9907. background-color: #00a1d6;
  9908. vertical-align: middle;
  9909. border: 1px solid #00a1d6;
  9910. transition: .1s;
  9911. transition-property: background-color,border,color;
  9912. user-select: none;
  9913. }
  9914.  
  9915. .bilitwin button:hover {
  9916. background-color: #00b5e5;
  9917. border-color: #00b5e5;
  9918. }
  9919.  
  9920. .bilitwin progress {
  9921. -webkit-appearance: progress-bar;
  9922. -moz-appearance: progress-bar;
  9923. appearance: progress-bar;
  9924. }
  9925.  
  9926. .bilitwin input[type="checkbox" i] {
  9927. -webkit-appearance: checkbox;
  9928. -moz-appearance: checkbox;
  9929. appearance: checkbox;
  9930. }
  9931.  
  9932. .bilitwin.context-menu-menu:hover {
  9933. background: hsla(0,0%,100%,.12);
  9934. }
  9935.  
  9936. .bilitwin.context-menu-menu:hover > a {
  9937. background: hsla(0,0%,100%,0) !important;
  9938. }
  9939. `;
  9940.  
  9941. const style = document.createElement('style');
  9942. style.type = 'text/css';
  9943. style.textContent = ret;
  9944. document.head.append(style);
  9945.  
  9946. return this.dom.style = style;
  9947. }
  9948.  
  9949. cidSessionRender() {
  9950. this.buildTitle();
  9951.  
  9952. if (this.option.title) this.appendTitle(); // 在视频标题旁添加链接
  9953. this.appendMenu(); // 在视频菜单栏添加链接
  9954. }
  9955.  
  9956. // Title Append
  9957. buildTitle(monkey = this.twin.monkey) {
  9958. // 1. build videoA, assA
  9959. const fontSize = '15px';
  9960. /** @type {HTMLAnchorElement} */
  9961. const videoA = document.createElement('a');
  9962. /** @type {HTMLAnchorElement} */
  9963. videoA.style.fontSize = fontSize;
  9964. videoA.textContent = '\u89C6\u9891FLV';
  9965. const assA = document.createElement('a');
  9966.  
  9967. // 1.1 build videoA
  9968. assA.style.fontSize = fontSize;
  9969. assA.textContent = '\u5F39\u5E55ASS';
  9970. videoA.onmouseover = async () => {
  9971. // 1.1.1 give processing hint
  9972. videoA.textContent = '正在FLV';
  9973. videoA.onmouseover = null;
  9974.  
  9975. // 1.1.2 query video
  9976. const video_format = await monkey.queryInfo('video');
  9977.  
  9978. // 1.1.3 display video
  9979. videoA.textContent = `视频${video_format ? video_format.toUpperCase() : 'FLV'}`;
  9980. videoA.onclick = () => this.displayFLVDiv();
  9981. };
  9982.  
  9983. // 1.2 build assA
  9984. assA.onmouseover = async () => {
  9985. // 1.2.1 give processing hint
  9986. assA.textContent = '正在ASS';
  9987. assA.onmouseover = null;
  9988.  
  9989. let clicked = false;
  9990. assA.addEventListener("click", () => {
  9991. clicked = true;
  9992. }, { once: true });
  9993.  
  9994. // 1.2.2 query flv
  9995. assA.href = await monkey.queryInfo('ass');
  9996.  
  9997. // 1.2.3 response mp4
  9998. assA.textContent = '弹幕ASS';
  9999. if (monkey.mp4 && monkey.mp4.match) {
  10000. assA.download = monkey.mp4.match(/\d(?:\d|-|hd)*(?=\.mp4)/)[0] + '.ass';
  10001. } else {
  10002. assA.download = monkey.cid + '.ass';
  10003. }
  10004.  
  10005. if (clicked) {
  10006. assA.click();
  10007. }
  10008. };
  10009.  
  10010. // 2. save to cache
  10011. Object.assign(this.cidSessionDom, { videoA, assA });
  10012. return this.cidSessionDom;
  10013. }
  10014.  
  10015. appendTitle({ videoA, assA } = this.cidSessionDom) {
  10016. // 1. build div
  10017. const div = document.createElement('div');
  10018.  
  10019. // 2. append to title
  10020. div.addEventListener('click', e => e.stopPropagation());
  10021. div.className = 'bilitwin';
  10022. div.append(...[videoA, ' ', assA]);
  10023. const tminfo = document.querySelector('div.tminfo') || document.querySelector('div.info-second') || document.querySelector('div.video-data') || document.querySelector("#h1_module") || document.querySelector(".media-title");
  10024. tminfo.style.float = 'none';
  10025. tminfo.after(div);
  10026.  
  10027. const h1_module = document.querySelector("#h1_module") || document.querySelector(".media-title");
  10028. if (h1_module) {
  10029. h1_module.style.marginBottom = "0px";
  10030. }
  10031.  
  10032. // 3. save to cache
  10033. this.cidSessionDom.titleDiv = div;
  10034.  
  10035. this.appendSubtitleAs(div);
  10036.  
  10037. return div;
  10038. }
  10039.  
  10040. async buildSubtitleAs() {
  10041. if (this.cidSessionDom && this.cidSessionDom.subtitleAs) {
  10042. return this.cidSessionDom.subtitleAs;
  10043. }
  10044.  
  10045. const subtitleList = await getSubtitles(aid, cid);
  10046.  
  10047. const fontSize = '15px';
  10048.  
  10049. const monkey = this.twin.monkey;
  10050.  
  10051. const subtitleAs = subtitleList.map(subtitle => {
  10052. const lanDoc = subtitle.language_doc.replace(/(/g, "(").replace(/)/g, ")");
  10053.  
  10054. /** @type {HTMLAnchorElement} */
  10055. const a = document.createElement('a');
  10056. a.style.fontSize = fontSize;
  10057. a.textContent = `${lanDoc}字幕ASS`;
  10058. a.lan = subtitle.language;
  10059.  
  10060. a.onclick = () => {
  10061. const blob = new Blob([subtitle.ass]);
  10062. a.href = URL.createObjectURL(blob);
  10063.  
  10064. let name = "";
  10065. if (monkey.mp4 && monkey.mp4.match) {
  10066. name = monkey.mp4.match(/\d(?:\d|-|hd)*(?=\.mp4)/)[0];
  10067. } else {
  10068. name = monkey.cid || cid;
  10069. }
  10070.  
  10071. a.download = `${name}.${subtitle.language}.ass`;
  10072.  
  10073. a.onclick = null;
  10074. };
  10075.  
  10076. return a;
  10077. });
  10078.  
  10079. this.cidSessionDom.subtitleAs = subtitleAs;
  10080. return subtitleAs;
  10081. }
  10082.  
  10083. async appendSubtitleAs(div) {
  10084. const subtitleAs = await this.buildSubtitleAs();
  10085.  
  10086. const items = subtitleAs.reduce((p, c) => {
  10087. // 在每一项前添加空格
  10088. return p.concat(' ', c);
  10089. }, []);
  10090.  
  10091. div.append(...items);
  10092. }
  10093.  
  10094. appendShortVideoTitle({ video_playurl, cover_img }) {
  10095. const fontSize = '15px';
  10096. const marginRight = '15px';
  10097. const videoA = document.createElement('a');
  10098. videoA.style.fontSize = fontSize;
  10099. videoA.style.marginRight = marginRight;
  10100. videoA.href = video_playurl;
  10101. videoA.target = '_blank';
  10102. videoA.textContent = '\u4E0B\u8F7D\u89C6\u9891';
  10103. const coverA = document.createElement('a');
  10104.  
  10105. coverA.style.fontSize = fontSize;
  10106. coverA.href = cover_img;
  10107. coverA.target = '_blank';
  10108. coverA.textContent = '\u83B7\u53D6\u5C01\u9762';
  10109. videoA.onclick = e => {
  10110. e.preventDefault();alert("请使用右键另存为下载视频");
  10111. };
  10112.  
  10113. const span = document.createElement('span');
  10114.  
  10115. span.addEventListener('click', e => e.stopPropagation());
  10116. span.className = 'bilitwin';
  10117. span.append(...[videoA, ' ', coverA]);
  10118. const infoDiv = document.querySelector('div.base-info div.info');
  10119. infoDiv.appendChild(span);
  10120. }
  10121.  
  10122. buildFLVDiv(monkey = this.twin.monkey, flvs = monkey.flvs, cache = monkey.cache, format = monkey.video_format) {
  10123. // 1. build video splits
  10124. const flvTrs = flvs.map((href, index) => {
  10125. const tr = document.createElement('tr');
  10126. {
  10127. const td1 = document.createElement('td');
  10128. const a1 = document.createElement('a');
  10129. a1.href = href;
  10130. a1.download = cid + '-' + (index + 1) + '.' + (format || "flv");
  10131. a1.textContent = `视频分段 ${index + 1}`;
  10132. td1.append(a1);
  10133. tr.append(td1);
  10134. const td2 = document.createElement('td');
  10135. const a2 = document.createElement('a');
  10136.  
  10137. a2.onclick = e => this.downloadFLV({
  10138. monkey,
  10139. index,
  10140. a: e.target,
  10141. progress: tr.children[2].children[0]
  10142. });
  10143.  
  10144. a2.textContent = '\u7F13\u5B58\u672C\u6BB5';
  10145. td2.append(a2);
  10146. tr.append(td2);
  10147. const td3 = document.createElement('td');
  10148. const progress1 = document.createElement('progress');
  10149. progress1.setAttribute('value', '0');
  10150. progress1.setAttribute('max', '100');
  10151. progress1.textContent = '\u8FDB\u5EA6\u6761';
  10152. td3.append(progress1);
  10153. tr.append(td3);
  10154. }
  10155. return tr;
  10156. });
  10157.  
  10158. // 2. build exporter a
  10159. const exporterA = document.createElement('a');
  10160. if (this.option.aria2) {
  10161. exporterA.textContent = '导出Aria2';
  10162. exporterA.download = 'bilitwin.session';
  10163. exporterA.href = URL.createObjectURL(new Blob([Exporter.exportAria2(flvs, top.location.origin)]));
  10164. } else if (this.option.aria2RPC) {
  10165. exporterA.textContent = '发送Aria2 RPC';
  10166. exporterA.onclick = () => Exporter.sendToAria2RPC(flvs, top.location.origin);
  10167. } else if (this.option.m3u8) {
  10168. exporterA.textContent = '导出m3u8';
  10169. exporterA.download = 'bilitwin.m3u8';
  10170. exporterA.href = URL.createObjectURL(new Blob([Exporter.exportM3U8(flvs, top.location.origin, top.navigator.userAgent)]));
  10171. } else if (this.option.clipboard) {
  10172. exporterA.textContent = '全部复制到剪贴板';
  10173. exporterA.onclick = () => Exporter.copyToClipboard(flvs.join('\n'));
  10174. } else {
  10175. exporterA.textContent = '导出IDM';
  10176. exporterA.download = 'bilitwin.ef2';
  10177. exporterA.href = URL.createObjectURL(new Blob([Exporter.exportIDM(flvs, top.location.origin)]));
  10178. }
  10179.  
  10180. // 3. build body table
  10181. const table = document.createElement('table');
  10182. table.style.width = '100%';
  10183. table.style.lineHeight = '2em';
  10184. table.append(...flvTrs, (() => {
  10185. const tr1 = document.createElement('tr');
  10186. const td1 = document.createElement('td');
  10187. td1.append(...[exporterA]);
  10188. tr1.append(td1);
  10189. const td2 = document.createElement('td');
  10190. const a1 = document.createElement('a');
  10191.  
  10192. a1.onclick = e => format != "mp4" ? this.downloadAllFLVs({
  10193. a: e.target,
  10194. monkey,
  10195. table
  10196. }) : top.alert("不支持合并MP4视频");
  10197.  
  10198. a1.textContent = '\u7F13\u5B58\u5168\u90E8+\u81EA\u52A8\u5408\u5E76';
  10199. td2.append(a1);
  10200. tr1.append(td2);
  10201. const td3 = document.createElement('td');
  10202. const progress1 = document.createElement('progress');
  10203. progress1.setAttribute('value', '0');
  10204. progress1.setAttribute('max', flvs.length + 1);
  10205. progress1.textContent = '\u8FDB\u5EA6\u6761';
  10206. td3.append(progress1);
  10207. tr1.append(td3);
  10208. return tr1;
  10209. })(), (() => {
  10210. const tr1 = document.createElement('tr');
  10211. const td1 = document.createElement('td');
  10212. td1.colSpan = '3';
  10213. 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~';
  10214. tr1.append(td1);
  10215. return tr1;
  10216. })(), cache ? (() => {
  10217. const tr1 = document.createElement('tr');
  10218. const td1 = document.createElement('td');
  10219. td1.colSpan = '3';
  10220. 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';
  10221. tr1.append(td1);
  10222. return tr1;
  10223. })() : (() => {
  10224. const tr1 = document.createElement('tr');
  10225. const td1 = document.createElement('td');
  10226. td1.colSpan = '3';
  10227. 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';
  10228. tr1.append(td1);
  10229. return tr1;
  10230. })(), (() => {
  10231. const tr1 = document.createElement('tr');
  10232. const td1 = document.createElement('td');
  10233. td1.colSpan = '3';
  10234. this.displayQuota.bind(this)(td1);
  10235. tr1.append(td1);
  10236. return tr1;
  10237. })());
  10238. this.cidSessionDom.flvTable = table;
  10239.  
  10240. // 4. build container dlv
  10241. const div = UI.genDiv();
  10242. div.ondragenter = div.ondragover = e => UI.allowDrag(e);
  10243. div.ondrop = async e => {
  10244. // 4.1 allow drag
  10245. UI.allowDrag(e);
  10246.  
  10247. // 4.2 sort files if possible
  10248. const files = Array.from(e.dataTransfer.files);
  10249. if (files.every(e => e.name.search(/\d+-\d+(?:\d|-|hd)*\.flv/) != -1)) {
  10250. files.sort((a, b) => a.name.match(/\d+-(\d+)(?:\d|-|hd)*\.flv/)[1] - b.name.match(/\d+-(\d+)(?:\d|-|hd)*\.flv/)[1]);
  10251. }
  10252.  
  10253. // 4.3 give loaded files hint
  10254. table.append(...files.map(e => {
  10255. const tr1 = document.createElement('tr');
  10256. const td1 = document.createElement('td');
  10257. td1.colSpan = '3';
  10258. td1.textContent = e.name;
  10259. tr1.append(td1);
  10260. return tr1;
  10261. }));
  10262.  
  10263. // 4.4 determine output name
  10264. let outputName = files[0].name.match(/\d+-\d+(?:\d|-|hd)*\.flv/);
  10265. if (outputName) outputName = outputName[0].replace(/-\d/, "");else outputName = 'merge_' + files[0].name;
  10266.  
  10267. // 4.5 build output ui
  10268. const href = await this.twin.mergeFLVFiles(files);
  10269. table.append((() => {
  10270. const tr1 = document.createElement('tr');
  10271. const td1 = document.createElement('td');
  10272. td1.colSpan = '3';
  10273. const a1 = document.createElement('a');
  10274. a1.href = href;
  10275. a1.download = outputName;
  10276. a1.textContent = outputName;
  10277. td1.append(a1);
  10278. tr1.append(td1);
  10279. return tr1;
  10280. })());
  10281. };
  10282.  
  10283. // 5. build util buttons
  10284. div.append(table, (() => {
  10285. const button = document.createElement('button');
  10286. button.style.padding = '0.5em';
  10287. button.style.margin = '0.2em';
  10288.  
  10289. button.onclick = () => div.style.display = 'none';
  10290.  
  10291. button.textContent = '\u5173\u95ED';
  10292. return button;
  10293. })(), (() => {
  10294. const button = document.createElement('button');
  10295. button.style.padding = '0.5em';
  10296. button.style.margin = '0.2em';
  10297.  
  10298. button.onclick = () => monkey.cleanAllFLVsInCache();
  10299.  
  10300. button.textContent = '\u6E05\u7A7A\u8FD9\u4E2A\u89C6\u9891\u7684\u7F13\u5B58';
  10301. return button;
  10302. })(), (() => {
  10303. const button = document.createElement('button');
  10304. button.style.padding = '0.5em';
  10305. button.style.margin = '0.2em';
  10306.  
  10307. button.onclick = () => this.twin.clearCacheDB(cache);
  10308.  
  10309. button.textContent = '\u6E05\u7A7A\u6240\u6709\u89C6\u9891\u7684\u7F13\u5B58';
  10310. return button;
  10311. })());
  10312.  
  10313. // 6. cancel on destroy
  10314. this.cidSessionDestroy.addCallback(() => {
  10315. flvTrs.map(tr => {
  10316. const a = tr.children[1].children[0];
  10317. if (a.textContent == '取消') a.click();
  10318. });
  10319. });
  10320.  
  10321. return this.cidSessionDom.flvDiv = div;
  10322. }
  10323.  
  10324. displayFLVDiv(flvDiv = this.cidSessionDom.flvDiv) {
  10325. if (!flvDiv) {
  10326. flvDiv = this.buildFLVDiv();
  10327. document.body.append(flvDiv);
  10328. }
  10329. flvDiv.style.display = '';
  10330. return flvDiv;
  10331. }
  10332.  
  10333. async downloadAllFLVs({ a, monkey = this.twin.monkey, table = this.cidSessionDom.flvTable }) {
  10334. if (this.cidSessionDom.downloadAllTr) return;
  10335.  
  10336. // 1. hang player
  10337. monkey.hangPlayer();
  10338.  
  10339. // 2. give hang player hint
  10340. this.cidSessionDom.downloadAllTr = (() => {
  10341. const tr1 = document.createElement('tr');
  10342. const td1 = document.createElement('td');
  10343. td1.colSpan = '3';
  10344. td1.textContent = '\u5DF2\u5C4F\u853D\u7F51\u9875\u64AD\u653E\u5668\u7684\u7F51\u7EDC\u94FE\u63A5\u3002\u5237\u65B0\u9875\u9762\u53EF\u91CD\u65B0\u6FC0\u6D3B\u64AD\u653E\u5668\u3002';
  10345. tr1.append(td1);
  10346. return tr1;
  10347. })();
  10348. table.append(this.cidSessionDom.downloadAllTr);
  10349.  
  10350. // 3. click download all split
  10351. for (let i = 0; i < monkey.flvs.length; i++) {
  10352. if (table.rows[i].cells[1].children[0].textContent == '缓存本段') table.rows[i].cells[1].children[0].click();
  10353. }
  10354.  
  10355. // 4. set progress
  10356. const progress = a.parentElement.nextElementSibling.children[0];
  10357. progress.max = monkey.flvs.length + 1;
  10358. progress.value = 0;
  10359. for (let i = 0; i < monkey.flvs.length; i++) monkey.getFLV(i).then(e => progress.value++);
  10360.  
  10361. // 5. merge splits
  10362. const files = await monkey.getAllFLVs();
  10363. const flv = await FLV.mergeBlobs(files);
  10364. const href = URL.createObjectURL(flv);
  10365. const ass = await monkey.getASS();
  10366.  
  10367. /** @type {HTMLAnchorElement[]} */
  10368. const subtitleAs = await this.buildSubtitleAs();
  10369. const subtitleAssList = subtitleAs.map(a => {
  10370. if (a.onclick && typeof a.onclick === "function") {
  10371. a.onclick();
  10372. }
  10373. return {
  10374. name: a.text.replace(/ASS$/, ""),
  10375. file: a.href
  10376. };
  10377. });
  10378.  
  10379. let outputName = top.document.getElementsByTagName('h1')[0].textContent.trim();
  10380. const pageNameElement = document.querySelector(".bilibili-player-video-top-title, .multi-page .on");
  10381. if (pageNameElement) {
  10382. const pageName = pageNameElement.textContent;
  10383. if (pageName && pageName != outputName) outputName += ` - ${pageName}`;
  10384. }
  10385.  
  10386. // 6. build download all ui
  10387. progress.value++;
  10388. table.prepend((() => {
  10389. const tr1 = document.createElement('tr');
  10390. const td1 = document.createElement('td');
  10391. td1.colSpan = '3';
  10392. td1.style = 'border: 1px solid black; word-break: keep-all;';
  10393. const a1 = document.createElement('a');
  10394. a1.href = href;
  10395. a1.download = `${outputName}.flv`;
  10396.  
  10397. (a => {
  10398. if (this.option.autoDanmaku) a.onclick = () => a.nextElementSibling.click();
  10399. })(a1);
  10400.  
  10401. a1.textContent = '\u4FDD\u5B58\u5408\u5E76\u540EFLV';
  10402. td1.append(a1);
  10403. td1.append(' ');
  10404. const a2 = document.createElement('a');
  10405. a2.href = ass;
  10406. a2.download = `${outputName}.danmaku.ass`;
  10407. a2.textContent = '\u5F39\u5E55ASS';
  10408. td1.append(a2);
  10409. td1.append(' ');
  10410. const a3 = document.createElement('a');
  10411. a3.download = `${outputName}.aac`;
  10412.  
  10413. a3.onclick = e => {
  10414. const aacA = e.target;
  10415. FLV2AAC(flv).then(aacData => {
  10416. const blob = new Blob([aacData]);
  10417. aacA.href = URL.createObjectURL(blob);
  10418. aacA.onclick = null;
  10419. aacA.click();
  10420. });
  10421. };
  10422.  
  10423. a3.textContent = '\u97F3\u9891AAC';
  10424. td1.append(a3);
  10425. td1.append(...subtitleAs.reduce((p, c) => {
  10426. // 在每一项前添加空格
  10427. return p.concat(' ', (() => {
  10428. const a4 = document.createElement('a');
  10429. a4.href = c.href;
  10430. a4.download = `${outputName}.${c.lan}.ass`;
  10431. a4.textContent = c.textContent;
  10432. return a4;
  10433. })());
  10434. }, []));
  10435. td1.append(' ');
  10436. const a4 = document.createElement('a');
  10437.  
  10438. a4.onclick = e => new MKVTransmuxer().exec(href, ass, `${outputName}.mkv`, e.target, subtitleAssList);
  10439.  
  10440. a4.textContent = '\u6253\u5305MKV(\u8F6F\u5B57\u5E55\u5C01\u88C5)';
  10441. td1.append(a4);
  10442. td1.append(' ');
  10443. td1.append('\u8BB0\u5F97\u6E05\u7406\u5206\u6BB5\u7F13\u5B58\u54E6~');
  10444. tr1.append(td1);
  10445. return tr1;
  10446. })());
  10447.  
  10448. return href;
  10449. }
  10450.  
  10451. async downloadFLV({ a, monkey = this.twin.monkey, index, progress = {} }) {
  10452. // 1. add beforeUnloadHandler
  10453. const handler = e => UI.beforeUnloadHandler(e);
  10454. window.addEventListener('beforeunload', handler);
  10455.  
  10456. // 2. switch to cancel ui
  10457. a.textContent = '取消';
  10458. a.onclick = () => {
  10459. a.onclick = null;
  10460. window.removeEventListener('beforeunload', handler);
  10461. a.textContent = '已取消';
  10462. monkey.abortFLV(index);
  10463. };
  10464.  
  10465. // 3. try download
  10466. let url;
  10467. try {
  10468. url = await monkey.getFLV(index, (loaded, total) => {
  10469. progress.value = loaded;
  10470. progress.max = total;
  10471. });
  10472. url = URL.createObjectURL(url);
  10473. if (progress.value == 0) progress.value = progress.max = 1;
  10474. } catch (e) {
  10475. a.onclick = null;
  10476. window.removeEventListener('beforeunload', handler);
  10477. a.textContent = '错误';
  10478. throw e;
  10479. }
  10480.  
  10481. // 4. switch to complete ui
  10482. a.onclick = null;
  10483. window.removeEventListener('beforeunload', handler);
  10484. a.textContent = '另存为';
  10485. a.download = monkey.flvs[index].match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  10486. a.href = url;
  10487. return url;
  10488. }
  10489.  
  10490. async displayQuota(td) {
  10491. return new Promise(resolve => {
  10492. const temporaryStorage = window.navigator.temporaryStorage || window.navigator.webkitTemporaryStorage || window.navigator.mozTemporaryStorage || window.navigator.msTemporaryStorage;
  10493. if (!temporaryStorage) return resolve(td.textContent = '这个浏览器不支持缓存呢~关掉标签页后,缓存马上就会消失哦');
  10494. temporaryStorage.queryUsageAndQuota((usage, quota) => resolve(td.textContent = `缓存已用空间:${Math.round(usage / 1048576)} MB / ${Math.round(quota / 1048576)} MB 也包括了B站本来的缓存`));
  10495. });
  10496. }
  10497.  
  10498. // Menu Append
  10499. async appendMenu(playerWin = this.twin.playerWin) {
  10500. // 1. build monkey menu and polyfill menu
  10501. const monkeyMenu = this.buildMonkeyMenu();
  10502. const polyfillMenu = this.buildPolyfillMenu();
  10503.  
  10504. // 2. build ul
  10505. const ul = document.createElement('ul');
  10506.  
  10507. // 3. append to menu
  10508. ul.className = 'bilitwin';
  10509. ul.style.borderBottom = '1px solid rgba(255,255,255,.12)';
  10510. ul.append(...[monkeyMenu, polyfillMenu]);
  10511. const menus0 = playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black bilibili-player-context-menu-origin');
  10512. if (menus0.length == 0) {
  10513. await new Promise(resolve => {
  10514. const observer = new MutationObserver(() => {
  10515. const menus1 = playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black bilibili-player-context-menu-origin');
  10516. const menus2 = playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black');
  10517. if (menus1.length > 0 || menus2.length >= 2) {
  10518. observer.disconnect();
  10519. resolve();
  10520. }
  10521. });
  10522. observer.observe(playerWin.document.querySelector("#bilibiliPlayer"), {
  10523. childList: true,
  10524. attributeFilter: ["class"]
  10525. });
  10526. });
  10527. }
  10528.  
  10529. const div = playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black bilibili-player-context-menu-origin')[0] || [...playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black')].pop();
  10530. div.prepend(ul);
  10531.  
  10532. // 4. save to cache
  10533. this.cidSessionDom.menuUl = ul;
  10534.  
  10535. return ul;
  10536. }
  10537.  
  10538. buildMonkeyMenu({
  10539. playerWin = this.twin.playerWin,
  10540. BiliMonkey = this.twin.BiliMonkey,
  10541. monkey = this.twin.monkey,
  10542. videoA = this.cidSessionDom.videoA,
  10543. assA = this.cidSessionDom.assA
  10544. } = {}) {
  10545. let context_menu_videoA = document.createElement('li');
  10546.  
  10547. {
  10548. context_menu_videoA.className = 'context-menu-function';
  10549.  
  10550. context_menu_videoA.onmouseover = async ({ target }) => {
  10551. if (videoA.onmouseover) await videoA.onmouseover();
  10552. const textNode = target.querySelector('#download-btn-vformat');
  10553. if (textNode && textNode.textContent) {
  10554. textNode.textContent = monkey.video_format ? monkey.video_format.toUpperCase() : 'FLV';
  10555. }
  10556. };
  10557.  
  10558. context_menu_videoA.onclick = () => videoA.click();
  10559.  
  10560. const a1 = document.createElement('a');
  10561. a1.className = 'context-menu-a';
  10562. const span1 = document.createElement('span');
  10563. span1.className = 'video-contextmenu-icon';
  10564. a1.append(span1);
  10565. a1.append(' \u4E0B\u8F7D\u89C6\u9891');
  10566. const downloadBtnVformat = document.createElement('span');
  10567. downloadBtnVformat.id = 'download-btn-vformat';
  10568. downloadBtnVformat.textContent = 'FLV';
  10569. a1.append(downloadBtnVformat);
  10570. context_menu_videoA.append(a1);
  10571. }
  10572.  
  10573. Object.assign(this.cidSessionDom, { context_menu_videoA });
  10574.  
  10575. /** @type {HTMLLIElement} */
  10576. const downloadSubtitlesContextMenu = document.createElement('li');
  10577.  
  10578. {
  10579. downloadSubtitlesContextMenu.className = 'context-menu-menu';
  10580.  
  10581. downloadSubtitlesContextMenu.onmouseover = async () => {
  10582. /** @type {HTMLAnchorElement[]} */
  10583. const subtitleAs = await this.buildSubtitleAs();
  10584.  
  10585. if (subtitleAs && subtitleAs.length > 0) {
  10586.  
  10587. downloadSubtitlesContextMenu.appendChild((() => {
  10588. const ul1 = document.createElement('ul');
  10589. ul1.append(...subtitleAs.map(a => {
  10590. const li = document.createElement('li');
  10591. li.className = 'context-menu-function';
  10592. const a1 = document.createElement('a');
  10593. a1.className = 'context-menu-a';
  10594.  
  10595. a1.onclick = () => a.click();
  10596.  
  10597. const span1 = document.createElement('span');
  10598. span1.className = 'video-contextmenu-icon';
  10599. a1.append(span1);
  10600. a1.append(a.text.replace(/字幕ASS$/, ""));
  10601. li.append(a1);
  10602.  
  10603. return li;
  10604. }));
  10605. return ul1;
  10606. })());
  10607. } else {
  10608.  
  10609. downloadSubtitlesContextMenu.appendChild((() => {
  10610. const ul1 = document.createElement('ul');
  10611. const li = document.createElement('li');
  10612. li.className = 'context-menu-function';
  10613. const a1 = document.createElement('a');
  10614. a1.className = 'context-menu-a';
  10615. const span1 = document.createElement('span');
  10616. span1.className = 'video-contextmenu-icon';
  10617. a1.append(span1);
  10618. a1.append(' \u65E0\u5B57\u5E55');
  10619. li.append(a1);
  10620. ul1.append(li);
  10621. return ul1;
  10622. })());
  10623. }
  10624.  
  10625. downloadSubtitlesContextMenu.onmouseover = null;
  10626. };
  10627.  
  10628. const a1 = document.createElement('a');
  10629. a1.className = 'context-menu-a';
  10630. const span1 = document.createElement('span');
  10631. span1.className = 'video-contextmenu-icon';
  10632. a1.append(span1);
  10633. a1.append(' \u4E0B\u8F7D\u5B57\u5E55ASS');
  10634. const span2 = document.createElement('span');
  10635. span2.className = 'bpui-icon bpui-icon-arrow-down';
  10636. span2.style = 'transform:rotate(-90deg);margin-top:3px;';
  10637. a1.append(span2);
  10638. downloadSubtitlesContextMenu.append(a1);
  10639. }const li = document.createElement('li');
  10640. li.className = 'context-menu-menu bilitwin';
  10641.  
  10642. li.onclick = () => playerWin.document.getElementById('bilibiliPlayer').click();
  10643.  
  10644. const a1 = document.createElement('a');
  10645. a1.className = 'context-menu-a';
  10646. a1.append('BiliMonkey');
  10647. const span1 = document.createElement('span');
  10648. span1.className = 'bpui-icon bpui-icon-arrow-down';
  10649. span1.style = 'transform:rotate(-90deg);margin-top:3px;';
  10650. a1.append(span1);
  10651. li.append(a1);
  10652. const ul1 = document.createElement('ul');
  10653. ul1.append(context_menu_videoA);
  10654. const li1 = document.createElement('li');
  10655. li1.className = 'context-menu-function';
  10656.  
  10657. li1.onclick = async () => {
  10658. if (assA.onmouseover) await assA.onmouseover();
  10659. assA.click();
  10660. };
  10661.  
  10662. const a2 = document.createElement('a');
  10663. a2.className = 'context-menu-a';
  10664. const span2 = document.createElement('span');
  10665. span2.className = 'video-contextmenu-icon';
  10666. a2.append(span2);
  10667. a2.append(' \u4E0B\u8F7D\u5F39\u5E55ASS');
  10668. li1.append(a2);
  10669. ul1.append(li1);
  10670. ul1.append(downloadSubtitlesContextMenu);
  10671. const li2 = document.createElement('li');
  10672. li2.className = 'context-menu-function';
  10673.  
  10674. li2.onclick = async () => UI.displayDownloadAllPageDefaultFormatsBody((await BiliMonkey.getAllPageDefaultFormats(playerWin, monkey)));
  10675.  
  10676. const a3 = document.createElement('a');
  10677. a3.className = 'context-menu-a';
  10678. const span3 = document.createElement('span');
  10679. span3.className = 'video-contextmenu-icon';
  10680. a3.append(span3);
  10681. a3.append(' \u6279\u91CF\u4E0B\u8F7D');
  10682. li2.append(a3);
  10683. ul1.append(li2);
  10684. const li3 = document.createElement('li');
  10685. li3.className = 'context-menu-function';
  10686.  
  10687. li3.onclick = () => this.displayOptionDiv();
  10688.  
  10689. const a4 = document.createElement('a');
  10690. a4.className = 'context-menu-a';
  10691. const span4 = document.createElement('span');
  10692. span4.className = 'video-contextmenu-icon';
  10693. a4.append(span4);
  10694. a4.append(' \u8BBE\u7F6E/\u5E2E\u52A9/\u5173\u4E8E');
  10695. li3.append(a4);
  10696. ul1.append(li3);
  10697. const li4 = document.createElement('li');
  10698. li4.className = 'context-menu-function';
  10699.  
  10700. li4.onclick = async () => {
  10701. monkey.proxy = true;
  10702. monkey.flvs = null;
  10703. UI.hintInfo('请稍候,可能需要10秒时间……', playerWin);
  10704. // Yes, I AM lazy.
  10705. playerWin.document.querySelector('div.bilibili-player-video-btn-quality > div ul li[data-value="80"]').click();
  10706. await new Promise(r => playerWin.document.getElementsByTagName('video')[0].addEventListener('emptied', r));
  10707. return monkey.queryInfo('video');
  10708. };
  10709.  
  10710. const a5 = document.createElement('a');
  10711. a5.className = 'context-menu-a';
  10712. const span5 = document.createElement('span');
  10713. span5.className = 'video-contextmenu-icon';
  10714. a5.append(span5);
  10715. a5.append(' (\u6D4B)\u8F7D\u5165\u7F13\u5B58FLV');
  10716. li4.append(a5);
  10717. ul1.append(li4);
  10718. const li5 = document.createElement('li');
  10719. li5.className = 'context-menu-function';
  10720.  
  10721. li5.onclick = () => top.location.reload(true);
  10722.  
  10723. const a6 = document.createElement('a');
  10724. a6.className = 'context-menu-a';
  10725. const span6 = document.createElement('span');
  10726. span6.className = 'video-contextmenu-icon';
  10727. a6.append(span6);
  10728. a6.append(' (\u6D4B)\u5F3A\u5236\u5237\u65B0');
  10729. li5.append(a6);
  10730. ul1.append(li5);
  10731. const li6 = document.createElement('li');
  10732. li6.className = 'context-menu-function';
  10733.  
  10734. li6.onclick = () => this.cidSessionDestroy() && this.cidSessionRender();
  10735.  
  10736. const a7 = document.createElement('a');
  10737. a7.className = 'context-menu-a';
  10738. const span7 = document.createElement('span');
  10739. span7.className = 'video-contextmenu-icon';
  10740. a7.append(span7);
  10741. a7.append(' (\u6D4B)\u91CD\u542F\u811A\u672C');
  10742. li6.append(a7);
  10743. ul1.append(li6);
  10744. const li7 = document.createElement('li');
  10745. li7.className = 'context-menu-function';
  10746.  
  10747. li7.onclick = () => playerWin.player && playerWin.player.destroy();
  10748.  
  10749. const a8 = document.createElement('a');
  10750. a8.className = 'context-menu-a';
  10751. const span8 = document.createElement('span');
  10752. span8.className = 'video-contextmenu-icon';
  10753. a8.append(span8);
  10754. a8.append(' (\u6D4B)\u9500\u6BC1\u64AD\u653E\u5668');
  10755. li7.append(a8);
  10756. ul1.append(li7);
  10757. li.append(ul1);
  10758.  
  10759.  
  10760. return li;
  10761. }
  10762.  
  10763. buildPolyfillMenu({
  10764. playerWin = this.twin.playerWin,
  10765. BiliPolyfill = this.twin.BiliPolyfill,
  10766. polyfill = this.twin.polyfill
  10767. } = {}) {
  10768. let oped = [];
  10769. const BiliDanmakuSettings = polyfill.BiliDanmakuSettings;
  10770. const refreshSession = new HookedFunction(() => oped = polyfill.userdata.oped[polyfill.getCollectionId()] || []); // as a convenient callback register
  10771. const li1 = document.createElement('li');
  10772. li1.className = 'context-menu-menu bilitwin';
  10773.  
  10774. li1.onclick = () => playerWin.document.getElementById('bilibiliPlayer').click();
  10775.  
  10776. const a2 = document.createElement('a');
  10777. a2.className = 'context-menu-a';
  10778.  
  10779. a2.onmouseover = () => refreshSession();
  10780.  
  10781. a2.append('BiliPolyfill');
  10782. const span2 = document.createElement('span');
  10783. span2.className = 'bpui-icon bpui-icon-arrow-down';
  10784. span2.style = 'transform:rotate(-90deg);margin-top:3px;';
  10785. a2.append(span2);
  10786. li1.append(a2);
  10787. const ul2 = document.createElement('ul');
  10788. const li2 = document.createElement('li');
  10789. li2.className = 'context-menu-function';
  10790.  
  10791. li2.onclick = async () => {
  10792. const w = top.window.open("", '_blank');w.location = await polyfill.getCoverImage();
  10793. };
  10794.  
  10795. const a3 = document.createElement('a');
  10796. a3.className = 'context-menu-a';
  10797. const span3 = document.createElement('span');
  10798. span3.className = 'video-contextmenu-icon';
  10799. a3.append(span3);
  10800. a3.append(' \u83B7\u53D6\u5C01\u9762');
  10801. li2.append(a3);
  10802. ul2.append(li2);
  10803. const li3 = document.createElement('li');
  10804. li3.className = 'context-menu-menu';
  10805. const a4 = document.createElement('a');
  10806. a4.className = 'context-menu-a';
  10807. const span4 = document.createElement('span');
  10808. span4.className = 'video-contextmenu-icon';
  10809. a4.append(span4);
  10810. a4.append(' \u66F4\u591A\u64AD\u653E\u901F\u5EA6');
  10811. const span5 = document.createElement('span');
  10812. span5.className = 'bpui-icon bpui-icon-arrow-down';
  10813. span5.style = 'transform:rotate(-90deg);margin-top:3px;';
  10814. a4.append(span5);
  10815. li3.append(a4);
  10816. const ul3 = document.createElement('ul');
  10817. const li4 = document.createElement('li');
  10818. li4.className = 'context-menu-function';
  10819.  
  10820. li4.onclick = () => {
  10821. polyfill.setVideoSpeed(0.1);
  10822. };
  10823.  
  10824. const a5 = document.createElement('a');
  10825. a5.className = 'context-menu-a';
  10826. const span6 = document.createElement('span');
  10827. span6.className = 'video-contextmenu-icon';
  10828. a5.append(span6);
  10829. a5.append(' 0.1');
  10830. li4.append(a5);
  10831. ul3.append(li4);
  10832. const li5 = document.createElement('li');
  10833. li5.className = 'context-menu-function';
  10834.  
  10835. li5.onclick = () => {
  10836. polyfill.setVideoSpeed(3);
  10837. };
  10838.  
  10839. const a6 = document.createElement('a');
  10840. a6.className = 'context-menu-a';
  10841. const span7 = document.createElement('span');
  10842. span7.className = 'video-contextmenu-icon';
  10843. a6.append(span7);
  10844. a6.append(' 3');
  10845. li5.append(a6);
  10846. ul3.append(li5);
  10847. const li6 = document.createElement('li');
  10848. li6.className = 'context-menu-function';
  10849.  
  10850. li6.onclick = e => polyfill.setVideoSpeed(e.target.children[1].value);
  10851.  
  10852. const a7 = document.createElement('a');
  10853. a7.className = 'context-menu-a';
  10854. const span8 = document.createElement('span');
  10855. span8.className = 'video-contextmenu-icon';
  10856. a7.append(span8);
  10857. a7.append(' \u70B9\u51FB\u786E\u8BA4');
  10858. const input = document.createElement('input');
  10859. input.type = 'text';
  10860. input.style = 'width: 35px; height: 70%; color:black;';
  10861.  
  10862. input.onclick = e => e.stopPropagation();
  10863.  
  10864. (e => refreshSession.addCallback(() => e.value = polyfill.video.playbackRate))(input);
  10865.  
  10866. a7.append(input);
  10867. li6.append(a7);
  10868. ul3.append(li6);
  10869. li3.append(ul3);
  10870. ul2.append(li3);
  10871. const li7 = document.createElement('li');
  10872. li7.className = 'context-menu-menu';
  10873. const a8 = document.createElement('a');
  10874. a8.className = 'context-menu-a';
  10875. const span9 = document.createElement('span');
  10876. span9.className = 'video-contextmenu-icon';
  10877. a8.append(span9);
  10878. a8.append(' \u81EA\u5B9A\u4E49\u5F39\u5E55\u5B57\u4F53');
  10879. const span10 = document.createElement('span');
  10880. span10.className = 'bpui-icon bpui-icon-arrow-down';
  10881. span10.style = 'transform:rotate(-90deg);margin-top:3px;';
  10882. a8.append(span10);
  10883. li7.append(a8);
  10884. const ul4 = document.createElement('ul');
  10885. const li8 = document.createElement('li');
  10886. li8.className = 'context-menu-function';
  10887.  
  10888. li8.onclick = e => {
  10889. BiliDanmakuSettings.set('fontfamily', e.target.lastChild.value);
  10890. playerWin.location.reload();
  10891. };
  10892.  
  10893. const a9 = document.createElement('a');
  10894. a9.className = 'context-menu-a';
  10895. const input1 = document.createElement('input');
  10896. input1.type = 'text';
  10897. input1.style = 'width: 108px; height: 70%; color:black;';
  10898.  
  10899. input1.onclick = e => e.stopPropagation();
  10900.  
  10901. (e => refreshSession.addCallback(() => e.value = BiliDanmakuSettings.get('fontfamily')))(input1);
  10902.  
  10903. a9.append(input1);
  10904. li8.append(a9);
  10905. ul4.append(li8);
  10906. const li9 = document.createElement('li');
  10907. li9.className = 'context-menu-function';
  10908.  
  10909. li9.onclick = e => {
  10910. BiliDanmakuSettings.set('fontfamily', e.target.parentElement.previousElementSibling.querySelector("input").value);
  10911. playerWin.location.reload();
  10912. };
  10913.  
  10914. const a10 = document.createElement('a');
  10915. a10.className = 'context-menu-a';
  10916. a10.textContent = `
  10917. 点击确认并刷新
  10918. `;
  10919. li9.append(a10);
  10920. ul4.append(li9);
  10921. li7.append(ul4);
  10922. ul2.append(li7);
  10923. const li10 = document.createElement('li');
  10924. li10.className = 'context-menu-menu';
  10925. const a11 = document.createElement('a');
  10926. a11.className = 'context-menu-a';
  10927. const span11 = document.createElement('span');
  10928. span11.className = 'video-contextmenu-icon';
  10929. a11.append(span11);
  10930. a11.append(' \u7247\u5934\u7247\u5C3E');
  10931. const span12 = document.createElement('span');
  10932. span12.className = 'bpui-icon bpui-icon-arrow-down';
  10933. span12.style = 'transform:rotate(-90deg);margin-top:3px;';
  10934. a11.append(span12);
  10935. li10.append(a11);
  10936. const ul5 = document.createElement('ul');
  10937. const li11 = document.createElement('li');
  10938. li11.className = 'context-menu-function';
  10939.  
  10940. li11.onclick = () => polyfill.markOPEDPosition(0);
  10941.  
  10942. const a12 = document.createElement('a');
  10943. a12.className = 'context-menu-a';
  10944. const span13 = document.createElement('span');
  10945. span13.className = 'video-contextmenu-icon';
  10946. a12.append(span13);
  10947. a12.append(' \u7247\u5934\u5F00\u59CB:');
  10948. const span14 = document.createElement('span');
  10949.  
  10950. (e => refreshSession.addCallback(() => e.textContent = oped[0] ? BiliPolyfill.secondToReadable(oped[0]) : '无'))(span14);
  10951.  
  10952. a12.append(span14);
  10953. li11.append(a12);
  10954. ul5.append(li11);
  10955. const li12 = document.createElement('li');
  10956. li12.className = 'context-menu-function';
  10957.  
  10958. li12.onclick = () => polyfill.markOPEDPosition(1);
  10959.  
  10960. const a13 = document.createElement('a');
  10961. a13.className = 'context-menu-a';
  10962. const span15 = document.createElement('span');
  10963. span15.className = 'video-contextmenu-icon';
  10964. a13.append(span15);
  10965. a13.append(' \u7247\u5934\u7ED3\u675F:');
  10966. const span16 = document.createElement('span');
  10967.  
  10968. (e => refreshSession.addCallback(() => e.textContent = oped[1] ? BiliPolyfill.secondToReadable(oped[1]) : '无'))(span16);
  10969.  
  10970. a13.append(span16);
  10971. li12.append(a13);
  10972. ul5.append(li12);
  10973. const li13 = document.createElement('li');
  10974. li13.className = 'context-menu-function';
  10975.  
  10976. li13.onclick = () => polyfill.markOPEDPosition(2);
  10977.  
  10978. const a14 = document.createElement('a');
  10979. a14.className = 'context-menu-a';
  10980. const span17 = document.createElement('span');
  10981. span17.className = 'video-contextmenu-icon';
  10982. a14.append(span17);
  10983. a14.append(' \u7247\u5C3E\u5F00\u59CB:');
  10984. const span18 = document.createElement('span');
  10985.  
  10986. (e => refreshSession.addCallback(() => e.textContent = oped[2] ? BiliPolyfill.secondToReadable(oped[2]) : '无'))(span18);
  10987.  
  10988. a14.append(span18);
  10989. li13.append(a14);
  10990. ul5.append(li13);
  10991. const li14 = document.createElement('li');
  10992. li14.className = 'context-menu-function';
  10993.  
  10994. li14.onclick = () => polyfill.markOPEDPosition(3);
  10995.  
  10996. const a15 = document.createElement('a');
  10997. a15.className = 'context-menu-a';
  10998. const span19 = document.createElement('span');
  10999. span19.className = 'video-contextmenu-icon';
  11000. a15.append(span19);
  11001. a15.append(' \u7247\u5C3E\u7ED3\u675F:');
  11002. const span20 = document.createElement('span');
  11003.  
  11004. (e => refreshSession.addCallback(() => e.textContent = oped[3] ? BiliPolyfill.secondToReadable(oped[3]) : '无'))(span20);
  11005.  
  11006. a15.append(span20);
  11007. li14.append(a15);
  11008. ul5.append(li14);
  11009. const li15 = document.createElement('li');
  11010. li15.className = 'context-menu-function';
  11011.  
  11012. li15.onclick = () => polyfill.clearOPEDPosition();
  11013.  
  11014. const a16 = document.createElement('a');
  11015. a16.className = 'context-menu-a';
  11016. const span21 = document.createElement('span');
  11017. span21.className = 'video-contextmenu-icon';
  11018. a16.append(span21);
  11019. a16.append(' \u53D6\u6D88\u6807\u8BB0');
  11020. li15.append(a16);
  11021. ul5.append(li15);
  11022. const li16 = document.createElement('li');
  11023. li16.className = 'context-menu-function';
  11024.  
  11025. li16.onclick = () => this.displayPolyfillDataDiv();
  11026.  
  11027. const a17 = document.createElement('a');
  11028. a17.className = 'context-menu-a';
  11029. const span22 = document.createElement('span');
  11030. span22.className = 'video-contextmenu-icon';
  11031. a17.append(span22);
  11032. a17.append(' \u68C0\u89C6\u6570\u636E/\u8BF4\u660E');
  11033. li16.append(a17);
  11034. ul5.append(li16);
  11035. li10.append(ul5);
  11036. ul2.append(li10);
  11037. const li17 = document.createElement('li');
  11038. li17.className = 'context-menu-menu';
  11039. const a18 = document.createElement('a');
  11040. a18.className = 'context-menu-a';
  11041. const span23 = document.createElement('span');
  11042. span23.className = 'video-contextmenu-icon';
  11043. a18.append(span23);
  11044. a18.append(' \u627E\u4E0A\u4E0B\u96C6');
  11045. const span24 = document.createElement('span');
  11046. span24.className = 'bpui-icon bpui-icon-arrow-down';
  11047. span24.style = 'transform:rotate(-90deg);margin-top:3px;';
  11048. a18.append(span24);
  11049. li17.append(a18);
  11050. const ul6 = document.createElement('ul');
  11051. const li18 = document.createElement('li');
  11052. li18.className = 'context-menu-function';
  11053.  
  11054. li18.onclick = () => {
  11055. if (polyfill.series[0]) {
  11056. top.window.open(`https://www.bilibili.com/video/av${polyfill.series[0].aid}`, '_blank');
  11057. }
  11058. };
  11059.  
  11060. const a19 = document.createElement('a');
  11061. a19.className = 'context-menu-a';
  11062. a19.style.width = 'initial';
  11063. const span25 = document.createElement('span');
  11064. span25.className = 'video-contextmenu-icon';
  11065. a19.append(span25);
  11066. const span26 = document.createElement('span');
  11067.  
  11068. (e => refreshSession.addCallback(() => e.textContent = polyfill.series[0] ? polyfill.series[0].title : '找不到'))(span26);
  11069.  
  11070. a19.append(span26);
  11071. li18.append(a19);
  11072. ul6.append(li18);
  11073. const li19 = document.createElement('li');
  11074. li19.className = 'context-menu-function';
  11075.  
  11076. li19.onclick = () => {
  11077. if (polyfill.series[1]) {
  11078. top.window.open(`https://www.bilibili.com/video/av${polyfill.series[1].aid}`, '_blank');
  11079. }
  11080. };
  11081.  
  11082. const a20 = document.createElement('a');
  11083. a20.className = 'context-menu-a';
  11084. a20.style.width = 'initial';
  11085. const span27 = document.createElement('span');
  11086. span27.className = 'video-contextmenu-icon';
  11087. a20.append(span27);
  11088. const span28 = document.createElement('span');
  11089.  
  11090. (e => refreshSession.addCallback(() => e.textContent = polyfill.series[1] ? polyfill.series[1].title : '找不到'))(span28);
  11091.  
  11092. a20.append(span28);
  11093. li19.append(a20);
  11094. ul6.append(li19);
  11095. li17.append(ul6);
  11096. ul2.append(li17);
  11097. const li20 = document.createElement('li');
  11098. li20.className = 'context-menu-function';
  11099.  
  11100. li20.onclick = () => BiliPolyfill.openMinimizedPlayer();
  11101.  
  11102. const a21 = document.createElement('a');
  11103. a21.className = 'context-menu-a';
  11104. const span29 = document.createElement('span');
  11105. span29.className = 'video-contextmenu-icon';
  11106. a21.append(span29);
  11107. a21.append(' \u5C0F\u7A97\u64AD\u653E');
  11108. li20.append(a21);
  11109. ul2.append(li20);
  11110. const li21 = document.createElement('li');
  11111. li21.className = 'context-menu-function';
  11112.  
  11113. li21.onclick = () => this.displayOptionDiv();
  11114.  
  11115. const a22 = document.createElement('a');
  11116. a22.className = 'context-menu-a';
  11117. const span30 = document.createElement('span');
  11118. span30.className = 'video-contextmenu-icon';
  11119. a22.append(span30);
  11120. a22.append(' \u8BBE\u7F6E/\u5E2E\u52A9/\u5173\u4E8E');
  11121. li21.append(a22);
  11122. ul2.append(li21);
  11123. const li22 = document.createElement('li');
  11124. li22.className = 'context-menu-function';
  11125.  
  11126. li22.onclick = () => polyfill.saveUserdata();
  11127.  
  11128. const a23 = document.createElement('a');
  11129. a23.className = 'context-menu-a';
  11130. const span31 = document.createElement('span');
  11131. span31.className = 'video-contextmenu-icon';
  11132. a23.append(span31);
  11133. a23.append(' (\u6D4B)\u7ACB\u5373\u4FDD\u5B58\u6570\u636E');
  11134. li22.append(a23);
  11135. ul2.append(li22);
  11136. const li23 = document.createElement('li');
  11137. li23.className = 'context-menu-function';
  11138.  
  11139. li23.onclick = () => {
  11140. BiliPolyfill.clearAllUserdata(playerWin);
  11141. polyfill.retrieveUserdata();
  11142. };
  11143.  
  11144. const a24 = document.createElement('a');
  11145. a24.className = 'context-menu-a';
  11146. const span32 = document.createElement('span');
  11147. span32.className = 'video-contextmenu-icon';
  11148. a24.append(span32);
  11149. a24.append(' (\u6D4B)\u5F3A\u5236\u6E05\u7A7A\u6570\u636E');
  11150. li23.append(a24);
  11151. ul2.append(li23);
  11152. li1.append(ul2);
  11153. return li1;
  11154. }
  11155.  
  11156. buildOptionDiv(twin = this.twin) {
  11157. const div = UI.genDiv();
  11158.  
  11159. div.append(this.buildMonkeyOptionTable(), this.buildPolyfillOptionTable(), this.buildUIOptionTable(), (() => {
  11160. const table1 = document.createElement('table');
  11161. table1.style.width = '100%';
  11162. table1.style.lineHeight = '2em';
  11163. const tr1 = document.createElement('tr');
  11164. const td1 = document.createElement('td');
  11165. td1.textContent = '\u8BBE\u7F6E\u81EA\u52A8\u4FDD\u5B58\uFF0C\u5237\u65B0\u540E\u751F\u6548\u3002';
  11166. tr1.append(td1);
  11167. table1.append(tr1);
  11168. const tr2 = document.createElement('tr');
  11169. const td2 = document.createElement('td');
  11170. 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';
  11171. tr2.append(td2);
  11172. table1.append(tr2);
  11173. const tr3 = document.createElement('tr');
  11174. const td3 = document.createElement('td');
  11175. 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';
  11176. tr3.append(td3);
  11177. table1.append(tr3);
  11178. const tr4 = document.createElement('tr');
  11179. const td4 = document.createElement('td');
  11180. 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';
  11181. tr4.append(td4);
  11182. table1.append(tr4);
  11183. const tr5 = document.createElement('tr');
  11184. const td5 = document.createElement('td');
  11185. const a2 = document.createElement('a');
  11186. a2.href = 'https://gf.qytechs.cn/zh-CN/scripts/372516';
  11187. a2.target = '_blank';
  11188. a2.textContent = '\u66F4\u65B0';
  11189. td5.append(a2);
  11190. td5.append(' ');
  11191. const a3 = document.createElement('a');
  11192. a3.href = 'https://github.com/Xmader/bilitwin/issues';
  11193. a3.target = '_blank';
  11194. a3.textContent = '\u8BA8\u8BBA';
  11195. td5.append(a3);
  11196. td5.append(' ');
  11197. const a4 = document.createElement('a');
  11198. a4.href = 'https://github.com/Xmader/bilitwin/';
  11199. a4.target = '_blank';
  11200. a4.textContent = 'GitHub';
  11201. td5.append(a4);
  11202. td5.append(' ');
  11203. td5.append('Author: qli5. Copyright: qli5, 2014+, \u7530\u751F, grepmusic, xmader');
  11204. tr5.append(td5);
  11205. table1.append(tr5);
  11206. return table1;
  11207. })(), (() => {
  11208. const button = document.createElement('button');
  11209. button.style.padding = '0.5em';
  11210. button.style.margin = '0.2em';
  11211.  
  11212. button.onclick = () => div.style.display = 'none';
  11213.  
  11214. button.textContent = '\u5173\u95ED';
  11215. return button;
  11216. })(), (() => {
  11217. const button = document.createElement('button');
  11218. button.style.padding = '0.5em';
  11219. button.style.margin = '0.2em';
  11220.  
  11221. button.onclick = () => top.location.reload();
  11222.  
  11223. button.textContent = '\u4FDD\u5B58\u5E76\u5237\u65B0';
  11224. return button;
  11225. })(), (() => {
  11226. const button = document.createElement('button');
  11227. button.style.padding = '0.5em';
  11228. button.style.margin = '0.2em';
  11229.  
  11230. button.onclick = () => twin.resetOption() && top.location.reload();
  11231.  
  11232. button.textContent = '\u91CD\u7F6E\u5E76\u5237\u65B0';
  11233. return button;
  11234. })());
  11235.  
  11236. return this.dom.optionDiv = div;
  11237. }
  11238.  
  11239. buildMonkeyOptionTable(twin = this.twin, BiliMonkey = this.twin.BiliMonkey) {
  11240. const table = document.createElement('table');
  11241. {
  11242. table.style.width = '100%';
  11243. table.style.lineHeight = '2em';
  11244. const tr1 = document.createElement('tr');
  11245. const td1 = document.createElement('td');
  11246. td1.style = 'text-align:center';
  11247. td1.textContent = 'BiliMonkey\uFF08\u89C6\u9891\u6293\u53D6\u7EC4\u4EF6\uFF09';
  11248. tr1.append(td1);
  11249. table.append(tr1);
  11250. }
  11251.  
  11252. table.append(...BiliMonkey.optionDescriptions.map(([name, description]) => {
  11253. const tr1 = document.createElement('tr');
  11254. const label = document.createElement('label');
  11255. const input = document.createElement('input');
  11256. input.type = 'checkbox';
  11257. input.checked = twin.option[name];
  11258.  
  11259. input.onchange = e => {
  11260. twin.option[name] = e.target.checked;
  11261. twin.saveOption(twin.option);
  11262. };
  11263.  
  11264. label.append(input);
  11265. label.append(description);
  11266. tr1.append(label);
  11267. return tr1;
  11268. }));
  11269.  
  11270. table.append((() => {
  11271. const tr1 = document.createElement('tr');
  11272. const label = document.createElement('label');
  11273. const input = document.createElement('input');
  11274. input.type = 'number';
  11275. input.value = +twin.option["resolutionX"] || 560;
  11276. input.min = 480;
  11277.  
  11278. input.onchange = e => {
  11279. twin.option["resolutionX"] = +e.target.value;
  11280. twin.saveOption(twin.option);
  11281. };
  11282.  
  11283. label.append(input);
  11284. label.append(" x ");
  11285. const input1 = document.createElement('input');
  11286. input1.type = 'number';
  11287. input1.value = +twin.option["resolutionY"] || 420;
  11288. input1.min = 360;
  11289.  
  11290. input1.onchange = e => {
  11291. twin.option["resolutionY"] = +e.target.value;
  11292. twin.saveOption(twin.option);
  11293. };
  11294.  
  11295. label.append(input1);
  11296. tr1.append(label);
  11297. return tr1;
  11298. })());
  11299.  
  11300. table.append((() => {
  11301. const tr1 = document.createElement('tr');
  11302. const label = document.createElement('label');
  11303. const input = document.createElement('input');
  11304. input.type = 'checkbox';
  11305. input.checked = twin.option["enableVideoMaxResolution"];
  11306.  
  11307. input.onchange = e => {
  11308. twin.option["enableVideoMaxResolution"] = e.target.checked;
  11309. twin.saveOption(twin.option);
  11310. };
  11311.  
  11312. label.append(input);
  11313. label.append('\u81EA\u5B9A\u4E49\u4E0B\u8F7D\u7684\u89C6\u9891\u7684');
  11314. const b1 = document.createElement('b');
  11315. b1.textContent = '\u6700\u9AD8';
  11316. label.append(b1);
  11317. label.append('\u5206\u8FA8\u7387\uFF1A');
  11318. const select = document.createElement('select');
  11319.  
  11320. select.onchange = e => {
  11321. twin.option["videoMaxResolution"] = e.target.value;
  11322. twin.saveOption(twin.option);
  11323. };
  11324.  
  11325. select.append(...BiliMonkey.resolutionPreferenceOptions.map(([name, value]) => {
  11326. const option1 = document.createElement('option');
  11327. option1.value = value;
  11328. option1.selected = (twin.option["videoMaxResolution"] || "116") == value;
  11329. option1.textContent = name;
  11330. return option1;
  11331. }));
  11332. label.append(select);
  11333. tr1.append(label);
  11334. return tr1;
  11335. })());
  11336.  
  11337. return table;
  11338. }
  11339.  
  11340. buildPolyfillOptionTable(twin = this.twin, BiliPolyfill = this.twin.BiliPolyfill) {
  11341. const table = document.createElement('table');
  11342. {
  11343. table.style.width = '100%';
  11344. table.style.lineHeight = '2em';
  11345. const tr1 = document.createElement('tr');
  11346. const td1 = document.createElement('td');
  11347. td1.style = 'text-align:center';
  11348. td1.textContent = 'BiliPolyfill\uFF08\u529F\u80FD\u589E\u5F3A\u7EC4\u4EF6\uFF09';
  11349. tr1.append(td1);
  11350. table.append(tr1);
  11351. const tr2 = document.createElement('tr');
  11352. const td2 = document.createElement('td');
  11353. td2.style = 'text-align:center';
  11354. 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';
  11355. tr2.append(td2);
  11356. table.append(tr2);
  11357. }
  11358.  
  11359. table.append(...BiliPolyfill.optionDescriptions.map(([name, description, disabled]) => {
  11360. const tr1 = document.createElement('tr');
  11361. const label = document.createElement('label');
  11362. label.style.textDecoration = disabled == 'disabled' ? 'line-through' : undefined;
  11363. const input = document.createElement('input');
  11364. input.type = 'checkbox';
  11365. input.checked = twin.option[name];
  11366.  
  11367. input.onchange = e => {
  11368. twin.option[name] = e.target.checked;
  11369. twin.saveOption(twin.option);
  11370. };
  11371.  
  11372. input.disabled = disabled == 'disabled';
  11373. label.append(input);
  11374. label.append(description);
  11375. tr1.append(label);
  11376. return tr1;
  11377. }));
  11378.  
  11379. return table;
  11380. }
  11381.  
  11382. buildUIOptionTable(twin = this.twin) {
  11383. const table = document.createElement('table');
  11384. {
  11385. table.style.width = '100%';
  11386. table.style.lineHeight = '2em';
  11387. const tr1 = document.createElement('tr');
  11388. const td1 = document.createElement('td');
  11389. td1.style = 'text-align:center';
  11390. td1.textContent = 'UI\uFF08\u7528\u6237\u754C\u9762\uFF09';
  11391. tr1.append(td1);
  11392. table.append(tr1);
  11393. }
  11394.  
  11395. table.append(...UI.optionDescriptions.map(([name, description]) => {
  11396. const tr1 = document.createElement('tr');
  11397. const label = document.createElement('label');
  11398. const input = document.createElement('input');
  11399. input.type = 'checkbox';
  11400. input.checked = twin.option[name];
  11401. input.disabled = name == "menu" /** 在视频菜单栏不添加后无法更改设置,所以禁用此选项 */;
  11402.  
  11403. input.onchange = e => {
  11404. twin.option[name] = e.target.checked;
  11405. twin.saveOption(twin.option);
  11406. };
  11407.  
  11408. label.append(input);
  11409. label.append(description);
  11410. tr1.append(label);
  11411. return tr1;
  11412. }));
  11413.  
  11414. return table;
  11415. }
  11416.  
  11417. displayOptionDiv(optionDiv = this.dom.optionDiv) {
  11418. if (!optionDiv) {
  11419. optionDiv = this.buildOptionDiv();
  11420. document.body.append(optionDiv);
  11421. }
  11422. optionDiv.style.display = '';
  11423. return optionDiv;
  11424. }
  11425.  
  11426. buildPolyfillDataDiv(polyfill = this.twin.polyfill) {
  11427. const textarea = document.createElement('textarea');
  11428.  
  11429. textarea.style.resize = 'vertical';
  11430. textarea.style.width = '100%';
  11431. textarea.style.height = '200px';
  11432. textarea.textContent = `
  11433. ${JSON.stringify(polyfill.userdata.oped).replace(/{/, '{\n').replace(/}/, '\n}').replace(/],/g, '],\n')}
  11434. `;
  11435. const div = UI.genDiv();
  11436.  
  11437. div.append((() => {
  11438. const p1 = document.createElement('p');
  11439. p1.style.margin = '0.3em';
  11440. p1.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';
  11441. return p1;
  11442. })(), (() => {
  11443. const p1 = document.createElement('p');
  11444. p1.style.margin = '0.3em';
  11445. p1.textContent = 'B\u7AD9\u5DF2\u4E0A\u7EBF\u539F\u751F\u7684\u7A0D\u540E\u89C2\u770B\u529F\u80FD\u3002';
  11446. return p1;
  11447. })(), (() => {
  11448. const p1 = document.createElement('p');
  11449. p1.style.margin = '0.3em';
  11450. p1.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';
  11451. return p1;
  11452. })(), textarea, (() => {
  11453. const p1 = document.createElement('p');
  11454. p1.style.margin = '0.3em';
  11455. p1.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';
  11456. return p1;
  11457. })(), (() => {
  11458. const button = document.createElement('button');
  11459. button.style.padding = '0.5em';
  11460. button.style.margin = '0.2em';
  11461.  
  11462. button.onclick = () => div.remove();
  11463.  
  11464. button.textContent = '\u5173\u95ED';
  11465. return button;
  11466. })(), (() => {
  11467. const button = document.createElement('button');
  11468. button.style.padding = '0.5em';
  11469. button.style.margin = '0.2em';
  11470.  
  11471. button.onclick = e => {
  11472. if (!textarea.value) textarea.value = '{\n\n}';
  11473. textarea.value = textarea.value.replace(/,(\s|\n)*}/, '\n}').replace(/,(\s|\n),/g, ',\n').replace(/,(\s|\n)*]/g, ']');
  11474. const userdata = {};
  11475. try {
  11476. userdata.oped = JSON.parse(textarea.value);
  11477. } catch (e) {
  11478. alert('片头片尾: ' + e);throw e;
  11479. }
  11480. e.target.textContent = '格式没有问题!';
  11481. return userdata;
  11482. };
  11483.  
  11484. button.textContent = '\u9A8C\u8BC1\u683C\u5F0F';
  11485. return button;
  11486. })(), (() => {
  11487. const button = document.createElement('button');
  11488. button.style.padding = '0.5em';
  11489. button.style.margin = '0.2em';
  11490.  
  11491. button.onclick = e => {
  11492. polyfill.userdata = e.target.previousElementSibling.onclick({ target: e.target.previousElementSibling });
  11493. polyfill.saveUserdata();
  11494. e.target.textContent = '保存成功';
  11495. };
  11496.  
  11497. button.textContent = '\u5C1D\u8BD5\u4FDD\u5B58';
  11498. return button;
  11499. })());
  11500.  
  11501. return div;
  11502. }
  11503.  
  11504. displayPolyfillDataDiv(polyfill) {
  11505. const div = this.buildPolyfillDataDiv();
  11506. document.body.append(div);
  11507. div.style.display = 'block';
  11508.  
  11509. return div;
  11510. }
  11511.  
  11512. // Common
  11513. static buildDownloadAllPageDefaultFormatsBody(ret, videoTitle) {
  11514. const table = document.createElement('table');
  11515.  
  11516. table.onclick = e => e.stopPropagation();
  11517.  
  11518. let flvsBlob = [];
  11519. const loadFLVFromCache = async (name, partial = false) => {
  11520. if (partial) name = 'PC_' + name;
  11521. const cache = new CacheDB();
  11522. let item = await cache.getData(name);
  11523. return item && item.data;
  11524. };
  11525. const saveFLVToCache = async (name, blob) => {
  11526. const cache = new CacheDB();
  11527. return cache.addData({ name, data: blob });
  11528. };
  11529. const cleanPartialFLVInCache = async name => {
  11530. const cache = new CacheDB();
  11531. name = 'PC_' + name;
  11532. return cache.deleteData(name);
  11533. };
  11534. const getFLVs = async videoIndex => {
  11535. if (!flvsBlob[videoIndex]) flvsBlob[videoIndex] = [];
  11536.  
  11537. const { durl } = ret[videoIndex];
  11538.  
  11539. return await Promise.all(durl.map(async (_, durlIndex) => {
  11540. if (flvsBlob[videoIndex][durlIndex]) {
  11541. return flvsBlob[videoIndex][durlIndex];
  11542. } else {
  11543. let burl = durl[durlIndex];
  11544. const outputName = burl.match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  11545.  
  11546. const burlA = top.document.querySelector(`a[download][href="${burl}"]`);
  11547. burlA.after((() => {
  11548. const progress1 = document.createElement('progress');
  11549. progress1.setAttribute('value', '0');
  11550. progress1.setAttribute('max', '100');
  11551. progress1.textContent = '\u8FDB\u5EA6\u6761';
  11552. return progress1;
  11553. })());
  11554. const progress = burlA.parentElement.querySelector("progress");
  11555.  
  11556. let flvCache = await loadFLVFromCache(outputName);
  11557. if (flvCache) {
  11558. progress.value = progress.max;
  11559. progress.after((() => {
  11560. const a2 = document.createElement('a');
  11561. a2.href = top.URL.createObjectURL(flvCache);
  11562. a2.download = outputName;
  11563. a2.textContent = '\u53E6\u5B58\u4E3A';
  11564. return a2;
  11565. })());
  11566. return flvsBlob[videoIndex][durlIndex] = flvCache;
  11567. }
  11568.  
  11569. let partialFLVFromCache = await loadFLVFromCache(outputName, true);
  11570. if (partialFLVFromCache) burl += `&bstart=${partialFLVFromCache.size}`;
  11571.  
  11572. const opt = {
  11573. method: 'GET',
  11574. mode: 'cors',
  11575. cache: 'default',
  11576. referrerPolicy: 'no-referrer-when-downgrade',
  11577. cacheLoaded: partialFLVFromCache ? partialFLVFromCache.size : 0,
  11578. headers: partialFLVFromCache && !burl.includes('wsTime') ? { Range: `bytes=${partialFLVFromCache.size}-` } : undefined
  11579. };
  11580.  
  11581. opt.onprogress = (loaded, total) => {
  11582. progress.value = loaded;
  11583. progress.max = total;
  11584. };
  11585.  
  11586. const fch = new DetailedFetchBlob(burl, opt);
  11587. let fullFLV = await fch.getBlob();
  11588. if (partialFLVFromCache) {
  11589. fullFLV = new Blob([partialFLVFromCache, fullFLV]);
  11590. cleanPartialFLVInCache(outputName);
  11591. }
  11592. saveFLVToCache(outputName, fullFLV);
  11593.  
  11594. progress.after((() => {
  11595. const a2 = document.createElement('a');
  11596. a2.href = top.URL.createObjectURL(fullFLV);
  11597. a2.download = outputName;
  11598. a2.textContent = '\u53E6\u5B58\u4E3A';
  11599. return a2;
  11600. })());
  11601.  
  11602. return flvsBlob[videoIndex][durlIndex] = fullFLV;
  11603. }
  11604. }));
  11605. };
  11606. const getSize = async videoIndex => {
  11607. const { res: { durl: durlObjects } } = ret[videoIndex];
  11608.  
  11609. if (durlObjects && durlObjects[0] && durlObjects[0].size) {
  11610. const totalSize = durlObjects.reduce((total, burlObj) => total + parseInt(burlObj.size), 0);
  11611. if (totalSize) return totalSize;
  11612. }
  11613.  
  11614. const { durl } = ret[videoIndex];
  11615.  
  11616. /** @type {number[]} */
  11617. const sizes = await Promise.all(durl.map(async burl => {
  11618. const r = await fetch(burl, { method: "HEAD" });
  11619. return +r.headers.get("content-length");
  11620. }));
  11621.  
  11622. return sizes.reduce((total, _size) => total + _size);
  11623. };
  11624.  
  11625. ret.forEach((i, index) => {
  11626. const sizeSpan = document.createElement('span');
  11627. getSize(index).then(size => {
  11628. const sizeMB = size / 1024 / 1024;
  11629. sizeSpan.textContent = ` (${sizeMB.toFixed(1)} MiB)`;
  11630. });
  11631.  
  11632. const iName = i.name;
  11633. let pName = `P${index + 1}`;
  11634. if (typeof iName == "string" && iName.toUpperCase() !== pName) {
  11635. pName += ` - ${iName}`;
  11636. }
  11637.  
  11638. const outputName = videoTitle.match(/:第\d+话 .+?$/) ? videoTitle.replace(/:第\d+话 .+?$/, `:第${iName}话`) : `${videoTitle} - ${pName}`;
  11639.  
  11640. table.append((() => {
  11641. const tr1 = document.createElement('tr');
  11642. const td1 = document.createElement('td');
  11643. td1.append(iName);
  11644. const br = document.createElement('br');
  11645. td1.append(br);
  11646. const a2 = document.createElement('a');
  11647.  
  11648. a2.onclick = async e => {
  11649. // add beforeUnloadHandler
  11650. const handler = e => UI.beforeUnloadHandler(e);
  11651. window.addEventListener('beforeunload', handler);
  11652.  
  11653. const targetA = e.target.parentElement;
  11654. targetA.title = "";
  11655. targetA.onclick = null;
  11656. targetA.textContent = "缓存中……";
  11657.  
  11658. const format = i.durl[0].match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[1];
  11659. const flvs = await getFLVs(index);
  11660.  
  11661. targetA.textContent = "合并中……";
  11662. const worker = WebWorker.fromAFunction(BatchDownloadWorkerFn);
  11663. await worker.registerAllMethods();
  11664. const href = URL.createObjectURL(format == "flv" ? await worker.mergeFLVFiles(flvs) : flvs[0]);
  11665. worker.terminate();
  11666.  
  11667. targetA.href = href;
  11668. targetA.download = `${outputName}.flv`;
  11669. targetA.textContent = "保存合并后FLV";
  11670. targetA.style["margin-right"] = "20px";
  11671.  
  11672. const ass = top.URL.createObjectURL(i.danmuku);
  11673. targetA.after((() => {
  11674. const a3 = document.createElement('a');
  11675.  
  11676. a3.onclick = e => {
  11677. new MKVTransmuxer().exec(href, ass, `${outputName}.mkv`, e.target);
  11678. };
  11679.  
  11680. a3.textContent = '\u6253\u5305MKV(\u8F6F\u5B57\u5E55\u5C01\u88C5)';
  11681. return a3;
  11682. })());
  11683.  
  11684. window.removeEventListener('beforeunload', handler);
  11685.  
  11686. targetA.click();
  11687. };
  11688.  
  11689. a2.title = '\u7F13\u5B58\u6240\u6709\u5206\u6BB5+\u81EA\u52A8\u5408\u5E76';
  11690. const span2 = document.createElement('span');
  11691. span2.textContent = '\u7F13\u5B58\u6240\u6709\u5206\u6BB5+\u81EA\u52A8\u5408\u5E76';
  11692. a2.append(span2);
  11693. a2.append(sizeSpan);
  11694. td1.append(a2);
  11695. tr1.append(td1);
  11696. const td2 = document.createElement('td');
  11697. const a3 = document.createElement('a');
  11698. a3.href = i.durl[0];
  11699. a3.download = '';
  11700. a3.setAttribute('referrerpolicy', 'origin');
  11701. a3.textContent = i.durl[0].match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  11702. td2.append(a3);
  11703. tr1.append(td2);
  11704. const td3 = document.createElement('td');
  11705. const a4 = document.createElement('a');
  11706. a4.href = top.URL.createObjectURL(i.danmuku);
  11707. a4.download = `${i.outputName}.ass`;
  11708. a4.setAttribute('referrerpolicy', 'origin');
  11709. a4.textContent = `${i.outputName}.ass`;
  11710. td3.append(a4);
  11711. tr1.append(td3);
  11712. return tr1;
  11713. })(), ...i.durl.slice(1).map(href => {
  11714. const tr1 = document.createElement('tr');
  11715. const td1 = document.createElement('td');
  11716. td1.textContent = `
  11717. `;
  11718. tr1.append(td1);
  11719. const td2 = document.createElement('td');
  11720. const a2 = document.createElement('a');
  11721. a2.href = href;
  11722. a2.download = '';
  11723. a2.setAttribute('referrerpolicy', 'origin');
  11724. a2.textContent = href.match(/\d+-\d+(?:\d|-|hd)*\.(flv|mp4)/)[0];
  11725. td2.append(a2);
  11726. tr1.append(td2);
  11727. const td3 = document.createElement('td');
  11728. td3.textContent = `
  11729. `;
  11730. tr1.append(td3);
  11731. return tr1;
  11732. }), (() => {
  11733. const tr1 = document.createElement('tr');
  11734. const td1 = document.createElement('td');
  11735. td1.textContent = ` `;
  11736. tr1.append(td1);
  11737. return tr1;
  11738. })());
  11739. });
  11740.  
  11741. const fragment = document.createDocumentFragment();
  11742. const style1 = document.createElement('style');
  11743. style1.textContent = `
  11744. table {
  11745. width: 100%;
  11746. table-layout: fixed;
  11747. }
  11748. td {
  11749. overflow: hidden;
  11750. white-space: nowrap;
  11751. text-overflow: ellipsis;
  11752. text-align: center;
  11753. vertical-align: bottom;
  11754. }
  11755.  
  11756. progress {
  11757. margin-left: 15px;
  11758. }
  11759.  
  11760. a {
  11761. cursor: pointer;
  11762. color: #00a1d6;
  11763. }
  11764. a:hover {
  11765. color: #f25d8e;
  11766. }
  11767. `;
  11768. fragment.append(style1);
  11769. const h1 = document.createElement('h1');
  11770. h1.textContent = '\u6279\u91CF\u4E0B\u8F7D';
  11771. fragment.append(h1);
  11772. const ul2 = document.createElement('ul');
  11773. const li1 = document.createElement('li');
  11774. const p1 = document.createElement('p');
  11775. p1.textContent = '\u6293\u53D6\u7684\u89C6\u9891\u7684\u6700\u9AD8\u5206\u8FA8\u7387\u53EF\u5728\u8BBE\u7F6E\u4E2D\u81EA\u5B9A\u4E49\uFF0C\u756A\u5267\u53EA\u80FD\u6293\u53D6\u5230\u5F53\u524D\u6E05\u6670\u5EA6';
  11776. li1.append(p1);
  11777. ul2.append(li1);
  11778. const li2 = document.createElement('li');
  11779. const p2 = document.createElement('p');
  11780. p2.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';
  11781. li2.append(p2);
  11782. const p3 = document.createElement('p');
  11783. const em = document.createElement('em');
  11784. em.textContent = '\u5F00\u53D1\u8005\uFF1A\u9700\u8981\u6821\u9A8Creferrer\u548Cuser agent';
  11785. p3.append(em);
  11786. li2.append(p3);
  11787. ul2.append(li2);
  11788. const li3 = document.createElement('li');
  11789. const p4 = document.createElement('p');
  11790. p4.append('(\u6D4B)');
  11791. const a2 = document.createElement('a');
  11792.  
  11793. a2.onclick = e => document.querySelectorAll('a[title="缓存所有分段+自动合并"] span:first-child').forEach(a => a.click());
  11794.  
  11795. a2.textContent = `
  11796. 一键开始缓存+批量合并
  11797. `;
  11798. p4.append(a2);
  11799. li3.append(p4);
  11800. ul2.append(li3);
  11801. fragment.append(ul2);
  11802. fragment.append(table);
  11803. return fragment;
  11804. }
  11805.  
  11806. static displayDownloadAllPageDefaultFormatsBody(ret) {
  11807. const videoTitle = top.document.getElementsByTagName('h1')[0].textContent.trim();
  11808.  
  11809. if (top.player) top.player.destroy(); // 销毁播放器
  11810.  
  11811. top.document.head.remove();
  11812. top.document.body.replaceWith(document.createElement("body"));
  11813.  
  11814. top.document.body.append(UI.buildDownloadAllPageDefaultFormatsBody(ret, videoTitle));
  11815.  
  11816. return ret;
  11817. }
  11818.  
  11819. static genDiv() {
  11820. const div1 = document.createElement('div');
  11821. div1.style.position = 'fixed';
  11822. div1.style.zIndex = '10036';
  11823. div1.style.top = '50%';
  11824. div1.style.marginTop = '-200px';
  11825. div1.style.left = '50%';
  11826. div1.style.marginLeft = '-320px';
  11827. div1.style.width = '540px';
  11828. div1.style.maxHeight = '400px';
  11829. div1.style.overflowY = 'auto';
  11830. div1.style.padding = '30px 50px';
  11831. div1.style.backgroundColor = 'white';
  11832. div1.style.borderRadius = '6px';
  11833. div1.style.boxShadow = 'rgba(0, 0, 0, 0.6) 1px 1px 40px 0px';
  11834. div1.style.display = 'none';
  11835. div1.addEventListener('click', e => e.stopPropagation());
  11836. div1.className = 'bilitwin';
  11837.  
  11838. return div1;
  11839. }
  11840.  
  11841. static requestH5Player() {
  11842. const h = document.querySelector('div.tminfo');
  11843. h.prepend('[[脚本需要HTML5播放器(弹幕列表右上角三个点的按钮切换)]] ');
  11844. }
  11845.  
  11846. static allowDrag(e) {
  11847. e.stopPropagation();
  11848. e.preventDefault();
  11849. }
  11850.  
  11851. static beforeUnloadHandler(e) {
  11852. return e.returnValue = '脚本还没做完工作,真的要退出吗?';
  11853. }
  11854.  
  11855. static hintInfo(text, playerWin) {
  11856. const div = document.createElement('div');
  11857. {
  11858. div.className = 'bilibili-player-video-toast-bottom';
  11859. const div1 = document.createElement('div');
  11860. div1.className = 'bilibili-player-video-toast-item';
  11861. const div2 = document.createElement('div');
  11862. div2.className = 'bilibili-player-video-toast-item-text';
  11863. const span2 = document.createElement('span');
  11864. span2.textContent = text;
  11865. div2.append(span2);
  11866. div1.append(div2);
  11867. div.append(div1);
  11868. }
  11869. playerWin.document.getElementsByClassName('bilibili-player-video-toast-wrp')[0].append(div);
  11870. setTimeout(() => div.remove(), 3000);
  11871. }
  11872.  
  11873. static get optionDescriptions() {
  11874. return [
  11875. // 1. automation
  11876. ['autoDanmaku', '下载视频也触发下载弹幕'],
  11877.  
  11878. // 2. user interface
  11879. ['title', '在视频标题旁添加链接'], ['menu', '在视频菜单栏添加链接'], ['autoDisplayDownloadBtn', '(测)无需右键播放器就能显示下载按钮'],
  11880.  
  11881. // 3. download
  11882. ['aria2', '导出aria2'], ['aria2RPC', '(请自行解决阻止混合活动内容的问题)发送到aria2 RPC'], ['m3u8', '(限VLC兼容播放器)导出m3u8'], ['clipboard', '(测)(请自行解决referrer)强制导出剪贴板']];
  11883. }
  11884.  
  11885. static get optionDefaults() {
  11886. return {
  11887. // 1. automation
  11888. autoDanmaku: false,
  11889.  
  11890. // 2. user interface
  11891. title: true,
  11892. menu: true,
  11893. autoDisplayDownloadBtn: true,
  11894.  
  11895. // 3. download
  11896. aria2: false,
  11897. aria2RPC: false,
  11898. m3u8: false,
  11899. clipboard: false
  11900. };
  11901. }
  11902. }
  11903.  
  11904. /***
  11905. * Copyright (C) 2018 Qli5. All Rights Reserved.
  11906. *
  11907. * @author qli5 <goodlq11[at](163|gmail).com>
  11908. *
  11909. * This Source Code Form is subject to the terms of the Mozilla Public
  11910. * License, v. 2.0. If a copy of the MPL was not distributed with this
  11911. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  11912. */
  11913.  
  11914. let debugOption = { debug: 1 };
  11915.  
  11916. class BiliTwin extends BiliUserJS {
  11917. static get debugOption() {
  11918. return debugOption;
  11919. }
  11920.  
  11921. static set debugOption(option) {
  11922. debugOption = option;
  11923. }
  11924.  
  11925. constructor(option = {}, ui) {
  11926. super();
  11927. this.BiliMonkey = BiliMonkey;
  11928. this.BiliPolyfill = BiliPolyfill;
  11929. this.playerWin = null;
  11930. this.monkey = null;
  11931. this.polifill = null;
  11932. this.ui = ui || new UI(this);
  11933. this.option = option;
  11934. }
  11935.  
  11936. async runCidSession() {
  11937. // 1. playerWin and option
  11938. try {
  11939. // you know what? it is a race, data race for jq! try not to yield to others!
  11940. this.playerWin = BiliUserJS.tryGetPlayerWinSync() || await BiliTwin.getPlayerWin();
  11941. }
  11942. catch (e) {
  11943. if (e == 'Need H5 Player') UI.requestH5Player();
  11944. throw e;
  11945. }
  11946. const href = location.href;
  11947. this.option = this.getOption();
  11948. if (this.option.debug) {
  11949. if (top.console) top.console.clear();
  11950. }
  11951.  
  11952. // 2. monkey and polyfill
  11953. this.monkey = new BiliMonkey(this.playerWin, this.option);
  11954. this.polyfill = new BiliPolyfill(this.playerWin, this.option, t => UI.hintInfo(t, this.playerWin));
  11955.  
  11956. const cidRefresh = BiliTwin.getCidRefreshPromise(this.playerWin);
  11957.  
  11958. const videoRightClick = (video) => {
  11959. let event = new MouseEvent('contextmenu', {
  11960. 'bubbles': true
  11961. });
  11962.  
  11963. video.dispatchEvent(event);
  11964. video.dispatchEvent(event);
  11965. };
  11966. if (this.option.autoDisplayDownloadBtn) {
  11967. // 无需右键播放器就能显示下载按钮
  11968. await new Promise(resolve => {
  11969. const i = setInterval(() => {
  11970. const video = document.querySelector("video");
  11971. if (video) {
  11972. videoRightClick(video);
  11973. if (
  11974. this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black').length
  11975. && (this.playerWin.document.getElementsByClassName('bilibili-player-context-menu-container black bilibili-player-context-menu-origin').length
  11976. || (this.playerWin.document.querySelectorAll("#bilibiliPlayer > div").length >= 4 && this.playerWin.document.querySelector(".video-data .view") && this.playerWin.document.querySelector(".video-data .view").textContent.slice(0, 2) != "--")
  11977. || (this.playerWin.document.querySelector(".bilibili-player-video-sendbar").children.length > 0 && this.playerWin.document.querySelector("#media_module .media-cover img"))
  11978. )
  11979. ) {
  11980. clearInterval(i);
  11981. resolve();
  11982. }
  11983. }
  11984. }, 10);
  11985. });
  11986. } else {
  11987. const video = document.querySelector("video");
  11988. if (video) {
  11989. video.addEventListener('play', () => videoRightClick(video), { once: true });
  11990. }
  11991. }
  11992.  
  11993. await this.polyfill.setFunctions();
  11994.  
  11995. // 3. async consistent => render UI
  11996. if (href == location.href) {
  11997. this.ui.option = this.option;
  11998. this.ui.cidSessionRender();
  11999.  
  12000. let videoA = this.ui.cidSessionDom.context_menu_videoA || this.ui.cidSessionDom.videoA;
  12001. if (videoA && videoA.onmouseover) videoA.onmouseover({ target: videoA.lastChild });
  12002. }
  12003. else {
  12004. cidRefresh.resolve();
  12005. }
  12006.  
  12007. // 4. debug
  12008. if (this.option.debug) {
  12009. [(top.unsafeWindow || top).monkey, (top.unsafeWindow || top).polyfill] = [this.monkey, this.polyfill];
  12010. }
  12011.  
  12012. // 5. refresh => session expire
  12013. await cidRefresh;
  12014. this.monkey.destroy();
  12015. this.polyfill.destroy();
  12016. this.ui.cidSessionDestroy();
  12017. }
  12018.  
  12019. async mergeFLVFiles(files) {
  12020. return URL.createObjectURL(await FLV.mergeBlobs(files));
  12021. }
  12022.  
  12023. async clearCacheDB(cache) {
  12024. if (cache) return cache.deleteEntireDB();
  12025. }
  12026.  
  12027. resetOption(option = this.option) {
  12028. option.setStorage('BiliTwin', JSON.stringify({}));
  12029. return this.option = {};
  12030. }
  12031.  
  12032. getOption(playerWin = this.playerWin) {
  12033. let rawOption = null;
  12034. try {
  12035. rawOption = JSON.parse(playerWin.localStorage.getItem('BiliTwin'));
  12036. }
  12037. catch (e) { }
  12038. finally {
  12039. if (!rawOption) rawOption = {};
  12040. rawOption.setStorage = (n, i) => playerWin.localStorage.setItem(n, i);
  12041. rawOption.getStorage = n => playerWin.localStorage.getItem(n);
  12042. return Object.assign(
  12043. {},
  12044. BiliMonkey.optionDefaults,
  12045. BiliPolyfill.optionDefaults,
  12046. UI.optionDefaults,
  12047. rawOption,
  12048. BiliTwin.debugOption,
  12049. );
  12050. }
  12051. }
  12052.  
  12053. saveOption(option = this.option) {
  12054. return option.setStorage('BiliTwin', JSON.stringify(option));
  12055. }
  12056.  
  12057. static async init() {
  12058. if (!document.body) return;
  12059.  
  12060. if (location.hostname == "www.biligame.com") {
  12061. return BiliPolyfill.biligameInit();
  12062. }
  12063. else if (location.pathname.startsWith("/bangumi/media/md")) {
  12064. return BiliPolyfill.showBangumiCoverImage();
  12065. }
  12066.  
  12067. BiliTwin.outdatedEngineClearance();
  12068. BiliTwin.firefoxClearance();
  12069.  
  12070. const twin = new BiliTwin();
  12071.  
  12072. if (location.hostname == "vc.bilibili.com") {
  12073. const vc_info = await BiliMonkey.getBiliShortVideoInfo();
  12074. return twin.ui.appendShortVideoTitle(vc_info);
  12075. }
  12076.  
  12077. while (1) {
  12078. await twin.runCidSession();
  12079. }
  12080. }
  12081.  
  12082. static outdatedEngineClearance() {
  12083. if (typeof Promise != 'function' || typeof MutationObserver != 'function') {
  12084. alert('这个浏览器实在太老了,脚本决定罢工。');
  12085. throw 'BiliTwin: browser outdated: Promise or MutationObserver unsupported';
  12086. }
  12087. }
  12088.  
  12089. static firefoxClearance() {
  12090. if (navigator.userAgent.includes('Firefox')) {
  12091. BiliTwin.debugOption.proxy = false;
  12092. if (!window.navigator.temporaryStorage && !window.navigator.mozTemporaryStorage) window.navigator.temporaryStorage = { queryUsageAndQuota: func => func(-1048576, 10484711424) };
  12093. }
  12094. }
  12095.  
  12096. static xpcWrapperClearance() {
  12097. if (top.unsafeWindow) {
  12098. Object.defineProperty(window, 'cid', {
  12099. configurable: true,
  12100. get: () => String(unsafeWindow.cid)
  12101. });
  12102. Object.defineProperty(window, 'player', {
  12103. configurable: true,
  12104. get: () => ({ destroy: unsafeWindow.player.destroy, reloadAccess: unsafeWindow.player.reloadAccess })
  12105. });
  12106. Object.defineProperty(window, 'jQuery', {
  12107. configurable: true,
  12108. get: () => unsafeWindow.jQuery,
  12109. });
  12110. Object.defineProperty(window, 'fetch', {
  12111. configurable: true,
  12112. get: () => unsafeWindow.fetch.bind(unsafeWindow),
  12113. set: _fetch => unsafeWindow.fetch = _fetch.bind(unsafeWindow)
  12114. });
  12115. }
  12116. }
  12117. }
  12118.  
  12119. BiliTwin.domContentLoadedThen(BiliTwin.init);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址