bilibili merged flv+mp4+ass+enhance

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

目前为 2018-10-05 提交的版本。查看 最新版本

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

QingJ © 2025

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