(function webpackuniversalmoduledefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["flvjs"] = factory(); else root["flvjs"] = factory(); })(self, function() { return /******/ (function() { // webpackbootstrap /******/ var __webpack_modules__ = ({ /***/ "./node_modules/es6-promise/dist/es6-promise.js": /*!******************************************************!*\ !*** ./node_modules/es6-promise/dist/es6-promise.js ***! \******************************************************/ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*! * @overview es6-promise - a tiny implementation of promises/a+. * @copyright copyright (c) 2014 yehuda katz, tom dale, stefan penner and contributors (conversion to es6 api by jake archibald) * @license licensed under mit license * see https://raw.githubusercontent.com/stefanpenner/es6-promise/master/license * @version v4.2.8+1e68dce6 */ (function (global, factory) { true ? module.exports = factory() : 0; }(this, (function () { 'use strict'; function objectorfunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function isfunction(x) { return typeof x === 'function'; } var _isarray = void 0; if (array.isarray) { _isarray = array.isarray; } else { _isarray = function (x) { return object.prototype.tostring.call(x) === '[object array]'; }; } var isarray = _isarray; var len = 0; var vertxnext = void 0; var customschedulerfn = void 0; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // if len is 2, that means that we need to schedule an async flush. // if additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customschedulerfn) { customschedulerfn(flush); } else { scheduleflush(); } } }; function setscheduler(schedulefn) { customschedulerfn = schedulefn; } function setasap(asapfn) { asap = asapfn; } var browserwindow = typeof window !== 'undefined' ? window : undefined; var browserglobal = browserwindow || {}; var browsermutationobserver = browserglobal.mutationobserver || browserglobal.webkitmutationobserver; var isnode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.tostring.call(process) === '[object process]'; // test for web worker but not in ie10 var isworker = typeof uint8clampedarray !== 'undefined' && typeof importscripts !== 'undefined' && typeof messagechannel !== 'undefined'; // node function usenexttick() { // node version 0.10.x displays a deprecation warning when nexttick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nexttick(flush); }; } // vertx function usevertxtimer() { if (typeof vertxnext !== 'undefined') { return function () { vertxnext(flush); }; } return usesettimeout(); } function usemutationobserver() { var iterations = 0; var observer = new browsermutationobserver(flush); var node = document.createtextnode(''); observer.observe(node, { characterdata: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function usemessagechannel() { var channel = new messagechannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postmessage(0); }; } function usesettimeout() { // store settimeout reference so es6-promise will be unaffected by // other code modifying settimeout (like sinon.usefaketimers()) var globalsettimeout = settimeout; return function () { return globalsettimeout(flush, 1); }; } var queue = new array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptvertx() { try { var vertx = function('return this')().require('vertx'); vertxnext = vertx.runonloop || vertx.runoncontext; return usevertxtimer(); } catch (e) { return usesettimeout(); } } var scheduleflush = void 0; // decide what async method to use to triggering processing of queued callbacks: if (isnode) { scheduleflush = usenexttick(); } else if (browsermutationobserver) { scheduleflush = usemutationobserver(); } else if (isworker) { scheduleflush = usemessagechannel(); } else if (browserwindow === undefined && "function" === 'function') { scheduleflush = attemptvertx(); } else { scheduleflush = usesettimeout(); } function then(onfulfillment, onrejection) { var parent = this; var child = new this.constructor(noop); if (child[promise_id] === undefined) { makepromise(child); } var _state = parent._state; if (_state) { var callback = arguments[_state - 1]; asap(function () { return invokecallback(_state, child, callback, parent._result); }); } else { subscribe(parent, child, onfulfillment, onrejection); } return child; } /** `promise.resolve` returns a promise that will become resolved with the passed `value`. it is shorthand for the following: ```javascript let promise = new promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` instead of writing the above, your code now simply becomes the following: ```javascript let promise = promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {any} value value that the returned promise will be resolved with useful for tooling. @return {promise} a promise that will become fulfilled with the given `value` */ function resolve$1(object) { /*jshint validthis:true */ var constructor = this; if (object && typeof object === 'object' && object.constructor === constructor) { return object; } var promise = new constructor(noop); resolve(promise, object); return promise; } var promise_id = math.random().tostring(36).substring(2); function noop() { } var pending = void 0; var fulfilled = 1; var rejected = 2; function selffulfillment() { return new typeerror("you cannot resolve a promise with itself"); } function cannotreturnown() { return new typeerror('a promises callback cannot return that same promise.'); } function trythen(then$$1, value, fulfillmenthandler, rejectionhandler) { try { then$$1.call(value, fulfillmenthandler, rejectionhandler); } catch (e) { return e; } } function handleforeignthenable(promise, thenable, then$$1) { asap(function (promise) { var sealed = false; var error = trythen(then$$1, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; reject(promise, reason); }, 'settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; reject(promise, error); } }, promise); } function handleownthenable(promise, thenable) { if (thenable._state === fulfilled) { fulfill(promise, thenable._result); } else if (thenable._state === rejected) { reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return resolve(promise, value); }, function (reason) { return reject(promise, reason); }); } } function handlemaybethenable(promise, maybethenable, then$$1) { if (maybethenable.constructor === promise.constructor && then$$1 === then && maybethenable.constructor.resolve === resolve$1) { handleownthenable(promise, maybethenable); } else { if (then$$1 === undefined) { fulfill(promise, maybethenable); } else if (isfunction(then$$1)) { handleforeignthenable(promise, maybethenable, then$$1); } else { fulfill(promise, maybethenable); } } } function resolve(promise, value) { if (promise === value) { reject(promise, selffulfillment()); } else if (objectorfunction(value)) { var then$$1 = void 0; try { then$$1 = value.then; } catch (error) { reject(promise, error); return; } handlemaybethenable(promise, value, then$$1); } else { fulfill(promise, value); } } function publishrejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== pending) { return; } promise._result = value; promise._state = fulfilled; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function reject(promise, reason) { if (promise._state !== pending) { return; } promise._state = rejected; promise._result = reason; asap(publishrejection, promise); } function subscribe(parent, child, onfulfillment, onrejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + fulfilled] = onfulfillment; _subscribers[length + rejected] = onrejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = void 0, callback = void 0, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokecallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function invokecallback(settled, promise, callback, detail) { var hascallback = isfunction(callback), value = void 0, error = void 0, succeeded = true; if (hascallback) { try { value = callback(detail); } catch (e) { succeeded = false; error = e; } if (promise === value) { reject(promise, cannotreturnown()); return; } } else { value = detail; } if (promise._state !== pending) { // noop } else if (hascallback && succeeded) { resolve(promise, value); } else if (succeeded === false) { reject(promise, error); } else if (settled === fulfilled) { fulfill(promise, value); } else if (settled === rejected) { reject(promise, value); } } function initializepromise(promise, resolver) { try { resolver(function resolvepromise(value) { resolve(promise, value); }, function rejectpromise(reason) { reject(promise, reason); }); } catch (e) { reject(promise, e); } } var id = 0; function nextid() { return id++; } function makepromise(promise) { promise[promise_id] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function validationerror() { return new error('array methods must be provided an array'); } var enumerator = function () { function enumerator(constructor, input) { this._instanceconstructor = constructor; this.promise = new constructor(noop); if (!this.promise[promise_id]) { makepromise(this.promise); } if (isarray(input)) { this.length = input.length; this._remaining = input.length; this._result = new array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(input); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { reject(this.promise, validationerror()); } } enumerator.prototype._enumerate = function _enumerate(input) { for (var i = 0; this._state === pending && i < input.length; i++) { this._eachentry(input[i], i); } }; enumerator.prototype._eachentry = function _eachentry(entry, i) { var c = this._instanceconstructor; var resolve$$1 = c.resolve; if (resolve$$1 === resolve$1) { var _then = void 0; var error = void 0; var diderror = false; try { _then = entry.then; } catch (e) { diderror = true; error = e; } if (_then === then && entry._state !== pending) { this._settledat(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === promise$1) { var promise = new c(noop); if (diderror) { reject(promise, error); } else { handlemaybethenable(promise, entry, _then); } this._willsettleat(promise, i); } else { this._willsettleat(new c(function (resolve$$1) { return resolve$$1(entry); }), i); } } else { this._willsettleat(resolve$$1(entry), i); } }; enumerator.prototype._settledat = function _settledat(state, i, value) { var promise = this.promise; if (promise._state === pending) { this._remaining--; if (state === rejected) { reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; enumerator.prototype._willsettleat = function _willsettleat(promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledat(fulfilled, i, value); }, function (reason) { return enumerator._settledat(rejected, i, reason); }); }; return enumerator; }(); /** `promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. it casts all elements of the passed iterable to promises as it runs this algorithm. example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; promise.all(promises).then(function(array){ // the array here would be [ 1, 2, 3 ]; }); ``` if any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. for example: example: ```javascript let promise1 = resolve(1); let promise2 = reject(new error("2")); let promise3 = reject(new error("3")); let promises = [ promise1, promise2, promise3 ]; promise.all(promises).then(function(array){ // code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {array} entries array of promises @param {string} label optional string for labeling the promise. useful for tooling. @return {promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new enumerator(this, entries).promise; } /** `promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. example: ```javascript let promise1 = new promise(function(resolve, reject){ settimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new promise(function(resolve, reject){ settimeout(function(){ resolve('promise 2'); }, 100); }); promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `promise.race` is deterministic in that only the state of the first settled promise matters. for example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new promise(function(resolve, reject){ settimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new promise(function(resolve, reject){ settimeout(function(){ reject(new error('promise 2')); }, 100); }); promise.race([promise1, promise2]).then(function(result){ // code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` an example real-world use case is implementing timeouts: ```javascript promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {array} promises array of promises to observe useful for tooling. @return {promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var constructor = this; if (!isarray(entries)) { return new constructor(function (_, reject) { return reject(new typeerror('you must pass an array to race.')); }); } else { return new constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `promise.reject` returns a promise rejected with the passed `reason`. it is shorthand for the following: ```javascript let promise = new promise(function(resolve, reject){ reject(new error('whoops')); }); promise.then(function(value){ // code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'whoops' }); ``` instead of writing the above, your code now simply becomes the following: ```javascript let promise = promise.reject(new error('whoops')); promise.then(function(value){ // code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'whoops' }); ``` @method reject @static @param {any} reason value that the returned promise will be rejected with. useful for tooling. @return {promise} a promise rejected with the given `reason`. */ function reject$1(reason) { /*jshint validthis:true */ var constructor = this; var promise = new constructor(noop); reject(promise, reason); return promise; } function needsresolver() { throw new typeerror('you must pass a resolver function as the first argument to the promise constructor'); } function needsnew() { throw new typeerror("failed to construct 'promise': please use the 'new' operator, this object constructor cannot be called as a function."); } /** promise objects represent the eventual result of an asynchronous operation. the primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal javascript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. a promise can be in one of three states: pending, fulfilled, or rejected. promises that are fulfilled have a fulfillment value and are in the fulfilled state. promises that are rejected have a rejection reason and are in the rejected state. a fulfillment value is never a thenable. promises can also be said to *resolve* a value. if this value is also a promise, then the original promise's settled state will match the value's settled state. so a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. basic usage: ------------ ```js let promise = new promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` advanced usage: --------------- promises shine when abstracting away asynchronous interactions such as `xmlhttprequest`s. ```js function getjson(url) { return new promise(function(resolve, reject){ let xhr = new xmlhttprequest(); xhr.open('get', url); xhr.onreadystatechange = handler; xhr.responsetype = 'json'; xhr.setrequestheader('accept', 'application/json'); xhr.send(); function handler() { if (this.readystate === this.done) { if (this.status === 200) { resolve(this.response); } else { reject(new error('getjson: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getjson('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` unlike callbacks, promises are great composable primitives. ```js promise.all([ getjson('/posts'), getjson('/comments') ]).then(function(values){ values[0] // => postsjson values[1] // => commentsjson return values; }); ``` @class promise @param {function} resolver useful for tooling. @constructor */ var promise$1 = function () { function promise(resolver) { this[promise_id] = nextid(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsresolver(); this instanceof promise ? initializepromise(this, resolver) : needsnew(); } } /** the primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js finduser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` chaining -------- the return value of `then` is itself a promise. this second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js finduser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (username) { // if `finduser` fulfilled, `username` will be the user's name, otherwise it // will be `'default name'` }); finduser().then(function (user) { throw new error('found user, but still unhappy'); }, function (reason) { throw new error('`finduser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `finduser` fulfilled, `reason` will be 'found user, but still unhappy'. // if `finduser` rejected, `reason` will be '`finduser` rejected and we're unhappy'. }); ``` if the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js finduser().then(function (user) { throw new pedagogicalexception('upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // the `pedgagocialexception` is propagated all the way down to here }); ``` assimilation ------------ sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. this can be achieved by returning a promise in the fulfillment or rejection handler. the downstream promise will then be pending until the returned promise is settled. this is called *assimilation*. ```js finduser().then(function (user) { return findcommentsbyauthor(user); }).then(function (comments) { // the user's comments are now available }); ``` if the assimliated promise rejects, then the downstream promise will also reject. ```js finduser().then(function (user) { return findcommentsbyauthor(user); }).then(function (comments) { // if `findcommentsbyauthor` fulfills, we'll have the value here }, function (reason) { // if `findcommentsbyauthor` rejects, we'll have the reason here }); ``` simple example -------------- synchronous example ```javascript let result; try { result = findresult(); // success } catch(reason) { // failure } ``` errback example ```js findresult(function(result, err){ if (err) { // failure } else { // success } }); ``` promise example; ```javascript findresult().then(function(result){ // success }, function(reason){ // failure }); ``` advanced example -------------- synchronous example ```javascript let author, books; try { author = findauthor(); books = findbooksbyauthor(author); // success } catch(reason) { // failure } ``` errback example ```js function foundbooks(books) { } function failure(reason) { } findauthor(function(author, err){ if (err) { failure(err); // failure } else { try { findboooksbyauthor(author, function(books, err) { if (err) { failure(err); } else { try { foundbooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` promise example; ```javascript findauthor(). then(findbooksbyauthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {function} onfulfilled @param {function} onrejected useful for tooling. @return {promise} */ /** `catch` is simply sugar for `then(undefined, onrejection)` which makes it the same as the catch block of a try/catch statement. ```js function findauthor(){ throw new error('couldn't find that author'); } // synchronous try { findauthor(); } catch(reason) { // something went wrong } // async with promises findauthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {function} onrejection useful for tooling. @return {promise} */ promise.prototype.catch = function _catch(onrejection) { return this.then(null, onrejection); }; /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves synchronous example: ```js findauthor() { if (math.random() > 0.5) { throw new error(); } return new author(); } try { return findauthor(); // succeed or fail } catch(error) { return findotherauther(); } finally { // always runs // doesn't affect the return value } ``` asynchronous example: ```js findauthor().catch(function(reason){ return findotherauther(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {function} callback @return {promise} */ promise.prototype.finally = function _finally(callback) { var promise = this; var constructor = promise.constructor; if (isfunction(callback)) { return promise.then(function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { throw reason; }); }); } return promise.then(callback, callback); }; return promise; }(); promise$1.prototype.then = then; promise$1.all = all; promise$1.race = race; promise$1.resolve = resolve$1; promise$1.reject = reject$1; promise$1._setscheduler = setscheduler; promise$1._setasap = setasap; promise$1._asap = asap; /*global self*/ function polyfill() { var local = void 0; if (typeof __webpack_require__.g !== 'undefined') { local = __webpack_require__.g; } else if (typeof self !== 'undefined') { local = self; } else { try { local = function('return this')(); } catch (e) { throw new error('polyfill failed because global object is unavailable in this environment'); } } var p = local.promise; if (p) { var promisetostring = null; try { promisetostring = object.prototype.tostring.call(p.resolve()); } catch (e) { // silently ignored } if (promisetostring === '[object promise]' && !p.cast) { return; } } local.promise = promise$1; } // strange compat.. promise$1.polyfill = polyfill; promise$1.promise = promise$1; return promise$1; }))); /***/ }), /***/ "./node_modules/events/events.js": /*!***************************************!*\ !*** ./node_modules/events/events.js ***! \***************************************/ /***/ (function(module) { "use strict"; // copyright joyent, inc. and other node contributors. // // permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "software"), to deal in the software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the software, and to permit // persons to whom the software is furnished to do so, subject to the // following conditions: // // the above copyright notice and this permission notice shall be included // in all copies or substantial portions of the software. // // the software is provided "as is", without warranty of any kind, express // or implied, including but not limited to the warranties of // merchantability, fitness for a particular purpose and noninfringement. in // no event shall the authors or copyright holders be liable for any claim, // damages or other liability, whether in an action of contract, tort or // otherwise, arising from, out of or in connection with the software or the // use or other dealings in the software. var r = typeof reflect === 'object' ? reflect : null; var reflectapply = r && typeof r.apply === 'function' ? r.apply : function reflectapply(target, receiver, args) { return function.prototype.apply.call(target, receiver, args); }; var reflectownkeys; if (r && typeof r.ownkeys === 'function') { reflectownkeys = r.ownkeys; } else if (object.getownpropertysymbols) { reflectownkeys = function reflectownkeys(target) { return object.getownpropertynames(target) .concat(object.getownpropertysymbols(target)); }; } else { reflectownkeys = function reflectownkeys(target) { return object.getownpropertynames(target); }; } function processemitwarning(warning) { if (console && console.warn) console.warn(warning); } var numberisnan = number.isnan || function numberisnan(value) { return value !== value; }; function eventemitter() { eventemitter.init.call(this); } module.exports = eventemitter; module.exports.once = once; // backwards-compat with node 0.10.x eventemitter.eventemitter = eventemitter; eventemitter.prototype._events = undefined; eventemitter.prototype._eventscount = 0; eventemitter.prototype._maxlisteners = undefined; // by default eventemitters will print a warning if more than 10 listeners are // added to it. this is a useful default which helps finding memory leaks. var defaultmaxlisteners = 10; function checklistener(listener) { if (typeof listener !== 'function') { throw new typeerror('the "listener" argument must be of type function. received type ' + typeof listener); } } object.defineproperty(eventemitter, 'defaultmaxlisteners', { enumerable: true, get: function () { return defaultmaxlisteners; }, set: function (arg) { if (typeof arg !== 'number' || arg < 0 || numberisnan(arg)) { throw new rangeerror('the value of "defaultmaxlisteners" is out of range. it must be a non-negative number. received ' + arg + '.'); } defaultmaxlisteners = arg; } }); eventemitter.init = function () { if (this._events === undefined || this._events === object.getprototypeof(this)._events) { this._events = object.create(null); this._eventscount = 0; } this._maxlisteners = this._maxlisteners || undefined; }; // obviously not all emitters should be limited to 10. this function allows // that to be increased. set to zero for unlimited. eventemitter.prototype.setmaxlisteners = function setmaxlisteners(n) { if (typeof n !== 'number' || n < 0 || numberisnan(n)) { throw new rangeerror('the value of "n" is out of range. it must be a non-negative number. received ' + n + '.'); } this._maxlisteners = n; return this; }; function _getmaxlisteners(that) { if (that._maxlisteners === undefined) return eventemitter.defaultmaxlisteners; return that._maxlisteners; } eventemitter.prototype.getmaxlisteners = function getmaxlisteners() { return _getmaxlisteners(this); }; eventemitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doerror = (type === 'error'); var events = this._events; if (events !== undefined) doerror = (doerror && events.error === undefined); else if (!doerror) return false; // if there is no 'error' event listener then throw. if (doerror) { var er; if (args.length > 0) er = args[0]; if (er instanceof error) { // note: the comments on the `throw` lines are intentional, they show // up in node's output if this results in an unhandled exception. throw er; // unhandled 'error' event } // at least give some kind of context to the user var err = new error('unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { reflectapply(handler, this, args); } else { var len = handler.length; var listeners = arrayclone(handler, len); for (var i = 0; i < len; ++i) reflectapply(listeners[i], this, args); } return true; }; function _addlistener(target, type, listener, prepend) { var m; var events; var existing; checklistener(listener); events = target._events; if (events === undefined) { events = target._events = object.create(null); target._eventscount = 0; } else { // to avoid recursion in the case that type === "newlistener"! before // adding it to the listeners, first emit "newlistener". if (events.newlistener !== undefined) { target.emit('newlistener', type, listener.listener ? listener.listener : listener); // re-assign `events` because a newlistener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // optimize the case of one listener. don't need the extra array object. existing = events[type] = listener; ++target._eventscount; } else { if (typeof existing === 'function') { // adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // if we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // check for listener leak m = _getmaxlisteners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // no error code for this since it is a warning // eslint-disable-next-line no-restricted-syntax var w = new error('possible eventemitter memory leak detected. ' + existing.length + ' ' + string(type) + ' listeners ' + 'added. use emitter.setmaxlisteners() to ' + 'increase limit'); w.name = 'maxlistenersexceededwarning'; w.emitter = target; w.type = type; w.count = existing.length; processemitwarning(w); } } return target; } eventemitter.prototype.addlistener = function addlistener(type, listener) { return _addlistener(this, type, listener, false); }; eventemitter.prototype.on = eventemitter.prototype.addlistener; eventemitter.prototype.prependlistener = function prependlistener(type, listener) { return _addlistener(this, type, listener, true); }; function oncewrapper() { if (!this.fired) { this.target.removelistener(this.type, this.wrapfn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _oncewrap(target, type, listener) { var state = { fired: false, wrapfn: undefined, target: target, type: type, listener: listener }; var wrapped = oncewrapper.bind(state); wrapped.listener = listener; state.wrapfn = wrapped; return wrapped; } eventemitter.prototype.once = function once(type, listener) { checklistener(listener); this.on(type, _oncewrap(this, type, listener)); return this; }; eventemitter.prototype.prependoncelistener = function prependoncelistener(type, listener) { checklistener(listener); this.prependlistener(type, _oncewrap(this, type, listener)); return this; }; // emits a 'removelistener' event if and only if the listener was removed. eventemitter.prototype.removelistener = function removelistener(type, listener) { var list, events, position, i, originallistener; checklistener(listener); events = this._events; if (events === undefined) return this; list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventscount === 0) this._events = object.create(null); else { delete events[type]; if (events.removelistener) this.emit('removelistener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originallistener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceone(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removelistener !== undefined) this.emit('removelistener', type, originallistener || listener); } return this; }; eventemitter.prototype.off = eventemitter.prototype.removelistener; eventemitter.prototype.removealllisteners = function removealllisteners(type) { var listeners, events, i; events = this._events; if (events === undefined) return this; // not listening for removelistener, no need to emit if (events.removelistener === undefined) { if (arguments.length === 0) { this._events = object.create(null); this._eventscount = 0; } else if (events[type] !== undefined) { if (--this._eventscount === 0) this._events = object.create(null); else delete events[type]; } return this; } // emit removelistener for all listeners on all events if (arguments.length === 0) { var keys = object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removelistener') continue; this.removealllisteners(key); } this.removealllisteners('removelistener'); this._events = object.create(null); this._eventscount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removelistener(type, listeners); } else if (listeners !== undefined) { // lifo order for (i = listeners.length - 1; i >= 0; i--) { this.removelistener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwraplisteners(evlistener) : arrayclone(evlistener, evlistener.length); } eventemitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; eventemitter.prototype.rawlisteners = function rawlisteners(type) { return _listeners(this, type, false); }; eventemitter.listenercount = function (emitter, type) { if (typeof emitter.listenercount === 'function') { return emitter.listenercount(type); } else { return listenercount.call(emitter, type); } }; eventemitter.prototype.listenercount = listenercount; function listenercount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } eventemitter.prototype.eventnames = function eventnames() { return this._eventscount > 0 ? reflectownkeys(this._events) : []; }; function arrayclone(arr, n) { var copy = new array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function spliceone(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwraplisteners(arr) { var ret = new array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function once(emitter, name) { return new promise(function (resolve, reject) { function errorlistener(err) { emitter.removelistener(name, resolver); reject(err); } function resolver() { if (typeof emitter.removelistener === 'function') { emitter.removelistener('error', errorlistener); } resolve([].slice.call(arguments)); } ; eventtargetagnosticaddlistener(emitter, name, resolver, { once: true }); if (name !== 'error') { adderrorhandlerifeventemitter(emitter, errorlistener, { once: true }); } }); } function adderrorhandlerifeventemitter(emitter, handler, flags) { if (typeof emitter.on === 'function') { eventtargetagnosticaddlistener(emitter, 'error', handler, flags); } } function eventtargetagnosticaddlistener(emitter, name, listener, flags) { if (typeof emitter.on === 'function') { if (flags.once) { emitter.once(name, listener); } else { emitter.on(name, listener); } } else if (typeof emitter.addeventlistener === 'function') { // eventtarget does not have `error` event semantics like node // eventemitters, we do not listen for `error` events here. emitter.addeventlistener(name, function wraplistener(arg) { // ie does not have builtin `{ once: true }` support so we // have to do it manually. if (flags.once) { emitter.removeeventlistener(name, wraplistener); } listener(arg); }); } else { throw new typeerror('the "emitter" argument must be of type eventemitter. received type ' + typeof emitter); } } /***/ }), /***/ "./node_modules/webworkify-webpack/index.js": /*!**************************************************!*\ !*** ./node_modules/webworkify-webpack/index.js ***! \**************************************************/ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { function webpackbootstrapfunc(modules) { /******/ // the module cache /******/ var installedmodules = {}; /******/ // the require function /******/ function __nested_webpack_require_164__(moduleid) { /******/ // check if module is in cache /******/ if (installedmodules[moduleid]) /******/ return installedmodules[moduleid].exports; /******/ // create a new module (and put it into the cache) /******/ var module = installedmodules[moduleid] = { /******/ i: moduleid, /******/ l: false, /******/ exports: {} /******/ }; /******/ // execute the module function /******/ modules[moduleid].call(module.exports, module, module.exports, __nested_webpack_require_164__); /******/ // flag the module as loaded /******/ module.l = true; /******/ // return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __nested_webpack_require_164__.m = modules; /******/ // expose the module cache /******/ __nested_webpack_require_164__.c = installedmodules; /******/ // identity function for calling harmony imports with the correct context /******/ __nested_webpack_require_164__.i = function (value) { return value; }; /******/ // define getter function for harmony exports /******/ __nested_webpack_require_164__.d = function (exports, name, getter) { /******/ if (!__nested_webpack_require_164__.o(exports, name)) { /******/ object.defineproperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ // define __esmodule on exports /******/ __nested_webpack_require_164__.r = function (exports) { /******/ object.defineproperty(exports, '__esmodule', { value: true }); /******/ }; /******/ // getdefaultexport function for compatibility with non-harmony modules /******/ __nested_webpack_require_164__.n = function (module) { /******/ var getter = module && module.__esmodule ? /******/ function getdefault() { return module['default']; } : /******/ function getmoduleexports() { return module; }; /******/ __nested_webpack_require_164__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ // object.prototype.hasownproperty.call /******/ __nested_webpack_require_164__.o = function (object, property) { return object.prototype.hasownproperty.call(object, property); }; /******/ // __webpack_public_path__ /******/ __nested_webpack_require_164__.p = "/"; /******/ // on error function for async loading /******/ __nested_webpack_require_164__.oe = function (err) { console.error(err); throw err; }; var f = __nested_webpack_require_164__(__nested_webpack_require_164__.s = entry_module); return f.default || f; // try to call default if defined to also support babel esmodule exports } var modulenamereqexp = '[\\.|\\-|\\+|\\w|\/|@]+'; var dependencyregexp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + modulenamereqexp + ').*?\\)'; // additional chars when output.pathinfo is true // http://stackoverflow.com/a/2593661/130442 function quoteregexp(str) { return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&'); } function isnumeric(n) { return !isnan(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to nan } function getmoduledependencies(sources, module, queuename) { var retval = {}; retval[queuename] = []; var fnstring = module.tostring(); var wrappersignature = fnstring.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/); if (!wrappersignature) return retval; var webpackrequirename = wrappersignature[1]; // main bundle deps var re = new regexp('(\\\\n|\\w)' + quoteregexp(webpackrequirename) + dependencyregexp, 'g'); var match; while ((match = re.exec(fnstring))) { if (match[3] === 'dll-reference') continue; retval[queuename].push(match[3]); } // dll deps re = new regexp('\\(' + quoteregexp(webpackrequirename) + '\\("(dll-reference\\s(' + modulenamereqexp + '))"\\)\\)' + dependencyregexp, 'g'); while ((match = re.exec(fnstring))) { if (!sources[match[2]]) { retval[queuename].push(match[1]); sources[match[2]] = __webpack_require__(match[1]).m; } retval[match[2]] = retval[match[2]] || []; retval[match[2]].push(match[4]); } // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3 var keys = object.keys(retval); for (var i = 0; i < keys.length; i++) { for (var j = 0; j < retval[keys[i]].length; j++) { if (isnumeric(retval[keys[i]][j])) { retval[keys[i]][j] = 1 * retval[keys[i]][j]; } } } return retval; } function hasvaluesinqueues(queues) { var keys = object.keys(queues); return keys.reduce(function (hasvalues, key) { return hasvalues || queues[key].length > 0; }, false); } function getrequiredmodules(sources, moduleid) { var modulesqueue = { main: [moduleid] }; var requiredmodules = { main: [] }; var seenmodules = { main: {} }; while (hasvaluesinqueues(modulesqueue)) { var queues = object.keys(modulesqueue); for (var i = 0; i < queues.length; i++) { var queuename = queues[i]; var queue = modulesqueue[queuename]; var moduletocheck = queue.pop(); seenmodules[queuename] = seenmodules[queuename] || {}; if (seenmodules[queuename][moduletocheck] || !sources[queuename][moduletocheck]) continue; seenmodules[queuename][moduletocheck] = true; requiredmodules[queuename] = requiredmodules[queuename] || []; requiredmodules[queuename].push(moduletocheck); var newmodules = getmoduledependencies(sources, sources[queuename][moduletocheck], queuename); var newmoduleskeys = object.keys(newmodules); for (var j = 0; j < newmoduleskeys.length; j++) { modulesqueue[newmoduleskeys[j]] = modulesqueue[newmoduleskeys[j]] || []; modulesqueue[newmoduleskeys[j]] = modulesqueue[newmoduleskeys[j]].concat(newmodules[newmoduleskeys[j]]); } } } return requiredmodules; } module.exports = function (moduleid, options) { options = options || {}; var sources = { main: __webpack_require__.m }; var requiredmodules = options.all ? { main: object.keys(sources.main) } : getrequiredmodules(sources, moduleid); var src = ''; object.keys(requiredmodules).filter(function (m) { return m !== 'main'; }).foreach(function (module) { var entrymodule = 0; while (requiredmodules[module][entrymodule]) { entrymodule++; } requiredmodules[module].push(entrymodule); sources[module][entrymodule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'; src = src + 'var ' + module + ' = (' + webpackbootstrapfunc.tostring().replace('entry_module', json.stringify(entrymodule)) + ')({' + requiredmodules[module].map(function (id) { return '' + json.stringify(id) + ': ' + sources[module][id].tostring(); }).join(',') + '});\n'; }); src = src + 'new ((' + webpackbootstrapfunc.tostring().replace('entry_module', json.stringify(moduleid)) + ')({' + requiredmodules.main.map(function (id) { return '' + json.stringify(id) + ': ' + sources.main[id].tostring(); }).join(',') + '}))(self);'; var blob = new window.blob([src], { type: 'text/javascript' }); if (options.bare) { return blob; } var url = window.url || window.webkiturl || window.mozurl || window.msurl; var workerurl = url.createobjecturl(blob); var worker = new window.worker(workerurl); worker.objecturl = workerurl; return worker; }; /***/ }), /***/ "./src/config.js": /*!***********************!*\ !*** ./src/config.js ***! \***********************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "defaultconfig": function() { return /* binding */ defaultconfig; }, /* harmony export */ "createdefaultconfig": function() { return /* binding */ createdefaultconfig; } /* harmony export */ }); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var defaultconfig = { enableworker: false, enablestashbuffer: true, stashinitialsize: undefined, islive: false, lazyload: true, lazyloadmaxduration: 3 * 60, lazyloadrecoverduration: 30, deferloadaftersourceopen: true, // autocleanupsourcebuffer: default as false, leave unspecified autocleanupmaxbackwardduration: 3 * 60, autocleanupminbackwardduration: 2 * 60, statisticsinforeportinterval: 600, fixaudiotimestampgap: true, accurateseek: false, seektype: 'range', seekparamstart: 'bstart', seekparamend: 'bend', rangeloadzerostart: false, customseekhandler: undefined, reuseredirectedurl: false, // referrerpolicy: leave as unspecified headers: undefined, customloader: undefined }; function createdefaultconfig() { return object.assign({}, defaultconfig); } /***/ }), /***/ "./src/core/features.js": /*!******************************!*\ !*** ./src/core/features.js ***! \******************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _io_io_controller_js__webpack_imported_module_0__ = __webpack_require__(/*! ../io/io-controller.js */ "./src/io/io-controller.js"); /* harmony import */ var _config_js__webpack_imported_module_1__ = __webpack_require__(/*! ../config.js */ "./src/config.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var features = /** @class */ (function () { function features() { } features.supportmseh264playback = function () { return window.mediasource && window.mediasource.istypesupported('video/mp4; codecs="avc1.42e01e,mp4a.40.2"'); }; features.supportnetworkstreamio = function () { var ioctl = new _io_io_controller_js__webpack_imported_module_0__.default({}, (0,_config_js__webpack_imported_module_1__.createdefaultconfig)()); var loadertype = ioctl.loadertype; ioctl.destroy(); return loadertype == 'fetch-stream-loader' || loadertype == 'xhr-moz-chunked-loader'; }; features.getnetworkloadertypename = function () { var ioctl = new _io_io_controller_js__webpack_imported_module_0__.default({}, (0,_config_js__webpack_imported_module_1__.createdefaultconfig)()); var loadertype = ioctl.loadertype; ioctl.destroy(); return loadertype; }; features.supportnativemediaplayback = function (mimetype) { if (features.videoelement == undefined) { features.videoelement = window.document.createelement('video'); } var canplay = features.videoelement.canplaytype(mimetype); return canplay === 'probably' || canplay == 'maybe'; }; features.getfeaturelist = function () { var features = { mseflvplayback: false, mseliveflvplayback: false, networkstreamio: false, networkloadername: '', nativemp4h264playback: false, nativewebmvp8playback: false, nativewebmvp9playback: false }; features.mseflvplayback = features.supportmseh264playback(); features.networkstreamio = features.supportnetworkstreamio(); features.networkloadername = features.getnetworkloadertypename(); features.mseliveflvplayback = features.mseflvplayback && features.networkstreamio; features.nativemp4h264playback = features.supportnativemediaplayback('video/mp4; codecs="avc1.42001e, mp4a.40.2"'); features.nativewebmvp8playback = features.supportnativemediaplayback('video/webm; codecs="vp8.0, vorbis"'); features.nativewebmvp9playback = features.supportnativemediaplayback('video/webm; codecs="vp9"'); return features; }; return features; }()); /* harmony default export */ __webpack_exports__["default"] = (features); /***/ }), /***/ "./src/core/media-info.js": /*!********************************!*\ !*** ./src/core/media-info.js ***! \********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var mediainfo = /** @class */ (function () { function mediainfo() { this.mimetype = null; this.duration = null; this.hasaudio = null; this.hasvideo = null; this.audiocodec = null; this.videocodec = null; this.audiodatarate = null; this.videodatarate = null; this.audiosamplerate = null; this.audiochannelcount = null; this.width = null; this.height = null; this.fps = null; this.profile = null; this.level = null; this.refframes = null; this.chromaformat = null; this.sarnum = null; this.sarden = null; this.metadata = null; this.segments = null; // mediainfo[] this.segmentcount = null; this.haskeyframesindex = null; this.keyframesindex = null; } mediainfo.prototype.iscomplete = function () { var audioinfocomplete = (this.hasaudio === false) || (this.hasaudio === true && this.audiocodec != null && this.audiosamplerate != null && this.audiochannelcount != null); var videoinfocomplete = (this.hasvideo === false) || (this.hasvideo === true && this.videocodec != null && this.width != null && this.height != null && this.fps != null && this.profile != null && this.level != null && this.refframes != null && this.chromaformat != null && this.sarnum != null && this.sarden != null); // keyframesindex may not be present return this.mimetype != null && this.duration != null && this.metadata != null && this.haskeyframesindex != null && audioinfocomplete && videoinfocomplete; }; mediainfo.prototype.isseekable = function () { return this.haskeyframesindex === true; }; mediainfo.prototype.getnearestkeyframe = function (milliseconds) { if (this.keyframesindex == null) { return null; } var table = this.keyframesindex; var keyframeidx = this._search(table.times, milliseconds); return { index: keyframeidx, milliseconds: table.times[keyframeidx], fileposition: table.filepositions[keyframeidx] }; }; mediainfo.prototype._search = function (list, value) { var idx = 0; var last = list.length - 1; var mid = 0; var lbound = 0; var ubound = last; if (value < list[0]) { idx = 0; lbound = ubound + 1; // skip search } while (lbound <= ubound) { mid = lbound + math.floor((ubound - lbound) / 2); if (mid === last || (value >= list[mid] && value < list[mid + 1])) { idx = mid; break; } else if (list[mid] < value) { lbound = mid + 1; } else { ubound = mid - 1; } } return idx; }; return mediainfo; }()); /* harmony default export */ __webpack_exports__["default"] = (mediainfo); /***/ }), /***/ "./src/core/media-segment-info.js": /*!****************************************!*\ !*** ./src/core/media-segment-info.js ***! \****************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "sampleinfo": function() { return /* binding */ sampleinfo; }, /* harmony export */ "mediasegmentinfo": function() { return /* binding */ mediasegmentinfo; }, /* harmony export */ "idrsamplelist": function() { return /* binding */ idrsamplelist; }, /* harmony export */ "mediasegmentinfolist": function() { return /* binding */ mediasegmentinfolist; } /* harmony export */ }); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ // represents an media sample (audio / video) var sampleinfo = /** @class */ (function () { function sampleinfo(dts, pts, duration, originaldts, issync) { this.dts = dts; this.pts = pts; this.duration = duration; this.originaldts = originaldts; this.issyncpoint = issync; this.fileposition = null; } return sampleinfo; }()); // media segment concept is defined in media source extensions spec. // particularly in iso bmff format, an media segment contains a moof box followed by a mdat box. var mediasegmentinfo = /** @class */ (function () { function mediasegmentinfo() { this.begindts = 0; this.enddts = 0; this.beginpts = 0; this.endpts = 0; this.originalbegindts = 0; this.originalenddts = 0; this.syncpoints = []; // sampleinfo[n], for video idr frames only this.firstsample = null; // sampleinfo this.lastsample = null; // sampleinfo } mediasegmentinfo.prototype.appendsyncpoint = function (sampleinfo) { sampleinfo.issyncpoint = true; this.syncpoints.push(sampleinfo); }; return mediasegmentinfo; }()); // ordered list for recording video idr frames, sorted by originaldts var idrsamplelist = /** @class */ (function () { function idrsamplelist() { this._list = []; } idrsamplelist.prototype.clear = function () { this._list = []; }; idrsamplelist.prototype.appendarray = function (syncpoints) { var list = this._list; if (syncpoints.length === 0) { return; } if (list.length > 0 && syncpoints[0].originaldts < list[list.length - 1].originaldts) { this.clear(); } array.prototype.push.apply(list, syncpoints); }; idrsamplelist.prototype.getlastsyncpointbeforedts = function (dts) { if (this._list.length == 0) { return null; } var list = this._list; var idx = 0; var last = list.length - 1; var mid = 0; var lbound = 0; var ubound = last; if (dts < list[0].dts) { idx = 0; lbound = ubound + 1; } while (lbound <= ubound) { mid = lbound + math.floor((ubound - lbound) / 2); if (mid === last || (dts >= list[mid].dts && dts < list[mid + 1].dts)) { idx = mid; break; } else if (list[mid].dts < dts) { lbound = mid + 1; } else { ubound = mid - 1; } } return this._list[idx]; }; return idrsamplelist; }()); // data structure for recording information of media segments in single track. var mediasegmentinfolist = /** @class */ (function () { function mediasegmentinfolist(type) { this._type = type; this._list = []; this._lastappendlocation = -1; // cached last insert location } object.defineproperty(mediasegmentinfolist.prototype, "type", { get: function () { return this._type; }, enumerable: false, configurable: true }); object.defineproperty(mediasegmentinfolist.prototype, "length", { get: function () { return this._list.length; }, enumerable: false, configurable: true }); mediasegmentinfolist.prototype.isempty = function () { return this._list.length === 0; }; mediasegmentinfolist.prototype.clear = function () { this._list = []; this._lastappendlocation = -1; }; mediasegmentinfolist.prototype._searchnearestsegmentbefore = function (originalbegindts) { var list = this._list; if (list.length === 0) { return -2; } var last = list.length - 1; var mid = 0; var lbound = 0; var ubound = last; var idx = 0; if (originalbegindts < list[0].originalbegindts) { idx = -1; return idx; } while (lbound <= ubound) { mid = lbound + math.floor((ubound - lbound) / 2); if (mid === last || (originalbegindts > list[mid].lastsample.originaldts && (originalbegindts < list[mid + 1].originalbegindts))) { idx = mid; break; } else if (list[mid].originalbegindts < originalbegindts) { lbound = mid + 1; } else { ubound = mid - 1; } } return idx; }; mediasegmentinfolist.prototype._searchnearestsegmentafter = function (originalbegindts) { return this._searchnearestsegmentbefore(originalbegindts) + 1; }; mediasegmentinfolist.prototype.append = function (mediasegmentinfo) { var list = this._list; var msi = mediasegmentinfo; var lastappendidx = this._lastappendlocation; var insertidx = 0; if (lastappendidx !== -1 && lastappendidx < list.length && msi.originalbegindts >= list[lastappendidx].lastsample.originaldts && ((lastappendidx === list.length - 1) || (lastappendidx < list.length - 1 && msi.originalbegindts < list[lastappendidx + 1].originalbegindts))) { insertidx = lastappendidx + 1; // use cached location idx } else { if (list.length > 0) { insertidx = this._searchnearestsegmentbefore(msi.originalbegindts) + 1; } } this._lastappendlocation = insertidx; this._list.splice(insertidx, 0, msi); }; mediasegmentinfolist.prototype.getlastsegmentbefore = function (originalbegindts) { var idx = this._searchnearestsegmentbefore(originalbegindts); if (idx >= 0) { return this._list[idx]; } else { // -1 return null; } }; mediasegmentinfolist.prototype.getlastsamplebefore = function (originalbegindts) { var segment = this.getlastsegmentbefore(originalbegindts); if (segment != null) { return segment.lastsample; } else { return null; } }; mediasegmentinfolist.prototype.getlastsyncpointbefore = function (originalbegindts) { var segmentidx = this._searchnearestsegmentbefore(originalbegindts); var syncpoints = this._list[segmentidx].syncpoints; while (syncpoints.length === 0 && segmentidx > 0) { segmentidx--; syncpoints = this._list[segmentidx].syncpoints; } if (syncpoints.length > 0) { return syncpoints[syncpoints.length - 1]; } else { return null; } }; return mediasegmentinfolist; }()); /***/ }), /***/ "./src/core/mse-controller.js": /*!************************************!*\ !*** ./src/core/mse-controller.js ***! \************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var events__webpack_imported_module_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js"); /* harmony import */ var events__webpack_imported_module_0___default = /*#__pure__*/__webpack_require__.n(events__webpack_imported_module_0__); /* harmony import */ var _utils_logger_js__webpack_imported_module_1__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _utils_browser_js__webpack_imported_module_2__ = __webpack_require__(/*! ../utils/browser.js */ "./src/utils/browser.js"); /* harmony import */ var _mse_events_js__webpack_imported_module_3__ = __webpack_require__(/*! ./mse-events.js */ "./src/core/mse-events.js"); /* harmony import */ var _media_segment_info_js__webpack_imported_module_4__ = __webpack_require__(/*! ./media-segment-info.js */ "./src/core/media-segment-info.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_5__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ // media source extensions controller var msecontroller = /** @class */ (function () { function msecontroller(config) { this.tag = 'msecontroller'; this._config = config; this._emitter = new (events__webpack_imported_module_0___default())(); if (this._config.islive && this._config.autocleanupsourcebuffer == undefined) { // for live stream, do auto cleanup by default this._config.autocleanupsourcebuffer = true; } this.e = { onsourceopen: this._onsourceopen.bind(this), onsourceended: this._onsourceended.bind(this), onsourceclose: this._onsourceclose.bind(this), onsourcebuffererror: this._onsourcebuffererror.bind(this), onsourcebufferupdateend: this._onsourcebufferupdateend.bind(this) }; this._mediasource = null; this._mediasourceobjecturl = null; this._mediaelement = null; this._isbufferfull = false; this._haspendingeos = false; this._requiresetmediaduration = false; this._pendingmediaduration = 0; this._pendingsourcebufferinit = []; this._mimetypes = { video: null, audio: null }; this._sourcebuffers = { video: null, audio: null }; this._lastinitsegments = { video: null, audio: null }; this._pendingsegments = { video: [], audio: [] }; this._pendingremoveranges = { video: [], audio: [] }; this._idrlist = new _media_segment_info_js__webpack_imported_module_4__.idrsamplelist(); } msecontroller.prototype.destroy = function () { if (this._mediaelement || this._mediasource) { this.detachmediaelement(); } this.e = null; this._emitter.removealllisteners(); this._emitter = null; }; msecontroller.prototype.on = function (event, listener) { this._emitter.addlistener(event, listener); }; msecontroller.prototype.off = function (event, listener) { this._emitter.removelistener(event, listener); }; msecontroller.prototype.attachmediaelement = function (mediaelement) { if (this._mediasource) { throw new _utils_exception_js__webpack_imported_module_5__.illegalstateexception('mediasource has been attached to an htmlmediaelement!'); } var ms = this._mediasource = new window.mediasource(); ms.addeventlistener('sourceopen', this.e.onsourceopen); ms.addeventlistener('sourceended', this.e.onsourceended); ms.addeventlistener('sourceclose', this.e.onsourceclose); this._mediaelement = mediaelement; this._mediasourceobjecturl = window.url.createobjecturl(this._mediasource); mediaelement.src = this._mediasourceobjecturl; }; msecontroller.prototype.detachmediaelement = function () { if (this._mediasource) { var ms = this._mediasource; for (var type in this._sourcebuffers) { // pending segments should be discard var ps = this._pendingsegments[type]; ps.splice(0, ps.length); this._pendingsegments[type] = null; this._pendingremoveranges[type] = null; this._lastinitsegments[type] = null; // remove all sourcebuffers var sb = this._sourcebuffers[type]; if (sb) { if (ms.readystate !== 'closed') { // ms edge can throw an error: unexpected call to method or property access try { ms.removesourcebuffer(sb); } catch (error) { _utils_logger_js__webpack_imported_module_1__.default.e(this.tag, error.message); } sb.removeeventlistener('error', this.e.onsourcebuffererror); sb.removeeventlistener('updateend', this.e.onsourcebufferupdateend); } this._mimetypes[type] = null; this._sourcebuffers[type] = null; } } if (ms.readystate === 'open') { try { ms.endofstream(); } catch (error) { _utils_logger_js__webpack_imported_module_1__.default.e(this.tag, error.message); } } ms.removeeventlistener('sourceopen', this.e.onsourceopen); ms.removeeventlistener('sourceended', this.e.onsourceended); ms.removeeventlistener('sourceclose', this.e.onsourceclose); this._pendingsourcebufferinit = []; this._isbufferfull = false; this._idrlist.clear(); this._mediasource = null; } if (this._mediaelement) { this._mediaelement.src = ''; this._mediaelement.removeattribute('src'); this._mediaelement = null; } if (this._mediasourceobjecturl) { window.url.revokeobjecturl(this._mediasourceobjecturl); this._mediasourceobjecturl = null; } }; msecontroller.prototype.appendinitsegment = function (initsegment, deferred) { if (!this._mediasource || this._mediasource.readystate !== 'open') { // sourcebuffer creation requires mediasource.readystate === 'open' // so we defer the sourcebuffer creation, until sourceopen event triggered this._pendingsourcebufferinit.push(initsegment); // make sure that this initsegment is in the front of pending segments queue this._pendingsegments[initsegment.type].push(initsegment); return; } var is = initsegment; var mimetype = "" + is.container; if (is.codec && is.codec.length > 0) { mimetype += ";codecs=" + is.codec; } var firstinitsegment = false; _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, 'received initialization segment, mimetype: ' + mimetype); this._lastinitsegments[is.type] = is; if (mimetype !== this._mimetypes[is.type]) { if (!this._mimetypes[is.type]) { // empty, first chance create sourcebuffer firstinitsegment = true; try { var sb = this._sourcebuffers[is.type] = this._mediasource.addsourcebuffer(mimetype); sb.addeventlistener('error', this.e.onsourcebuffererror); sb.addeventlistener('updateend', this.e.onsourcebufferupdateend); } catch (error) { _utils_logger_js__webpack_imported_module_1__.default.e(this.tag, error.message); this._emitter.emit(_mse_events_js__webpack_imported_module_3__.default.error, { code: error.code, msg: error.message }); return; } } else { _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, "notice: " + is.type + " mimetype changed, origin: " + this._mimetypes[is.type] + ", target: " + mimetype); } this._mimetypes[is.type] = mimetype; } if (!deferred) { // deferred means this initsegment has been pushed to pendingsegments queue this._pendingsegments[is.type].push(is); } if (!firstinitsegment) { // append immediately only if init segment in subsequence if (this._sourcebuffers[is.type] && !this._sourcebuffers[is.type].updating) { this._doappendsegments(); } } if (_utils_browser_js__webpack_imported_module_2__.default.safari && is.container === 'audio/mpeg' && is.mediaduration > 0) { // 'audio/mpeg' track under safari may cause mediaelement's duration to be nan // manually correct mediasource.duration to make progress bar seekable, and report right duration this._requiresetmediaduration = true; this._pendingmediaduration = is.mediaduration / 1000; // in seconds this._updatemediasourceduration(); } }; msecontroller.prototype.appendmediasegment = function (mediasegment) { var ms = mediasegment; this._pendingsegments[ms.type].push(ms); if (this._config.autocleanupsourcebuffer && this._needcleanupsourcebuffer()) { this._docleanupsourcebuffer(); } var sb = this._sourcebuffers[ms.type]; if (sb && !sb.updating && !this._haspendingremoveranges()) { this._doappendsegments(); } }; msecontroller.prototype.seek = function (seconds) { // remove all appended buffers for (var type in this._sourcebuffers) { if (!this._sourcebuffers[type]) { continue; } // abort current buffer append algorithm var sb = this._sourcebuffers[type]; if (this._mediasource.readystate === 'open') { try { // if range removal algorithm is running, invalidstateerror will be throwed // ignore it. sb.abort(); } catch (error) { _utils_logger_js__webpack_imported_module_1__.default.e(this.tag, error.message); } } // idrlist should be clear this._idrlist.clear(); // pending segments should be discard var ps = this._pendingsegments[type]; ps.splice(0, ps.length); if (this._mediasource.readystate === 'closed') { // parent mediasource object has been detached from htmlmediaelement continue; } // record ranges to be remove from sourcebuffer for (var i = 0; i < sb.buffered.length; i++) { var start = sb.buffered.start(i); var end = sb.buffered.end(i); this._pendingremoveranges[type].push({ start: start, end: end }); } // if sb is not updating, let's remove ranges now! if (!sb.updating) { this._doremoveranges(); } // safari 10 may get invalidstateerror in the later appendbuffer() after sourcebuffer.remove() call // internal parser's state may be invalid at this time. re-append last initsegment to workaround. // related issue: https://bugs.webkit.org/show_bug.cgi?id=159230 if (_utils_browser_js__webpack_imported_module_2__.default.safari) { var lastinitsegment = this._lastinitsegments[type]; if (lastinitsegment) { this._pendingsegments[type].push(lastinitsegment); if (!sb.updating) { this._doappendsegments(); } } } } }; msecontroller.prototype.endofstream = function () { var ms = this._mediasource; var sb = this._sourcebuffers; if (!ms || ms.readystate !== 'open') { if (ms && ms.readystate === 'closed' && this._haspendingsegments()) { // if mediasource hasn't turned into open state, and there're pending segments // mark pending endofstream, defer call until all pending segments appended complete this._haspendingeos = true; } return; } if (sb.video && sb.video.updating || sb.audio && sb.audio.updating) { // if any sourcebuffer is updating, defer endofstream operation // see _onsourcebufferupdateend() this._haspendingeos = true; } else { this._haspendingeos = false; // notify media data loading complete // this is helpful for correcting total duration to match last media segment // otherwise mediaelement's ended event may not be triggered ms.endofstream(); } }; msecontroller.prototype.getnearestkeyframe = function (dts) { return this._idrlist.getlastsyncpointbeforedts(dts); }; msecontroller.prototype._needcleanupsourcebuffer = function () { if (!this._config.autocleanupsourcebuffer) { return false; } var currenttime = this._mediaelement.currenttime; for (var type in this._sourcebuffers) { var sb = this._sourcebuffers[type]; if (sb) { var buffered = sb.buffered; if (buffered.length >= 1) { if (currenttime - buffered.start(0) >= this._config.autocleanupmaxbackwardduration) { return true; } } } } return false; }; msecontroller.prototype._docleanupsourcebuffer = function () { var currenttime = this._mediaelement.currenttime; for (var type in this._sourcebuffers) { var sb = this._sourcebuffers[type]; if (sb) { var buffered = sb.buffered; var doremove = false; for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); if (start <= currenttime && currenttime < end + 3) { // padding 3 seconds if (currenttime - start >= this._config.autocleanupmaxbackwardduration) { doremove = true; var removeend = currenttime - this._config.autocleanupminbackwardduration; this._pendingremoveranges[type].push({ start: start, end: removeend }); } } else if (end < currenttime) { doremove = true; this._pendingremoveranges[type].push({ start: start, end: end }); } } if (doremove && !sb.updating) { this._doremoveranges(); } } } }; msecontroller.prototype._updatemediasourceduration = function () { var sb = this._sourcebuffers; if (this._mediaelement.readystate === 0 || this._mediasource.readystate !== 'open') { return; } if ((sb.video && sb.video.updating) || (sb.audio && sb.audio.updating)) { return; } var current = this._mediasource.duration; var target = this._pendingmediaduration; if (target > 0 && (isnan(current) || target > current)) { _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, "update mediasource duration from " + current + " to " + target); this._mediasource.duration = target; } this._requiresetmediaduration = false; this._pendingmediaduration = 0; }; msecontroller.prototype._doremoveranges = function () { for (var type in this._pendingremoveranges) { if (!this._sourcebuffers[type] || this._sourcebuffers[type].updating) { continue; } var sb = this._sourcebuffers[type]; var ranges = this._pendingremoveranges[type]; while (ranges.length && !sb.updating) { var range = ranges.shift(); sb.remove(range.start, range.end); } } }; msecontroller.prototype._doappendsegments = function () { var pendingsegments = this._pendingsegments; for (var type in pendingsegments) { if (!this._sourcebuffers[type] || this._sourcebuffers[type].updating) { continue; } if (pendingsegments[type].length > 0) { var segment = pendingsegments[type].shift(); if (segment.timestampoffset) { // for mpeg audio stream in mse, if unbuffered-seeking occurred // we need explicitly set timestampoffset to the desired point in timeline for mpeg sourcebuffer. var currentoffset = this._sourcebuffers[type].timestampoffset; var targetoffset = segment.timestampoffset / 1000; // in seconds var delta = math.abs(currentoffset - targetoffset); if (delta > 0.1) { // if time delta > 100ms _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, "update mpeg audio timestampoffset from " + currentoffset + " to " + targetoffset); this._sourcebuffers[type].timestampoffset = targetoffset; } delete segment.timestampoffset; } if (!segment.data || segment.data.bytelength === 0) { // ignore empty buffer continue; } try { this._sourcebuffers[type].appendbuffer(segment.data); this._isbufferfull = false; if (type === 'video' && segment.hasownproperty('info')) { this._idrlist.appendarray(segment.info.syncpoints); } } catch (error) { this._pendingsegments[type].unshift(segment); if (error.code === 22) { // quotaexceedederror /* notice that firefox may not throw quotaexceedederror if sourcebuffer is full * currently we can only do lazy-load to avoid sourcebuffer become scattered. * sourcebuffer eviction policy may be changed in future version of firefox. * * related issues: * https://bugzilla.mozilla.org/show_bug.cgi?id=1279885 * https://bugzilla.mozilla.org/show_bug.cgi?id=1280023 */ // report buffer full, abort network io if (!this._isbufferfull) { this._emitter.emit(_mse_events_js__webpack_imported_module_3__.default.buffer_full); } this._isbufferfull = true; } else { _utils_logger_js__webpack_imported_module_1__.default.e(this.tag, error.message); this._emitter.emit(_mse_events_js__webpack_imported_module_3__.default.error, { code: error.code, msg: error.message }); } } } } }; msecontroller.prototype._onsourceopen = function () { _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, 'mediasource onsourceopen'); this._mediasource.removeeventlistener('sourceopen', this.e.onsourceopen); // deferred sourcebuffer creation / initialization if (this._pendingsourcebufferinit.length > 0) { var pendings = this._pendingsourcebufferinit; while (pendings.length) { var segment = pendings.shift(); this.appendinitsegment(segment, true); } } // there may be some pending media segments, append them if (this._haspendingsegments()) { this._doappendsegments(); } this._emitter.emit(_mse_events_js__webpack_imported_module_3__.default.source_open); }; msecontroller.prototype._onsourceended = function () { // fired on endofstream _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, 'mediasource onsourceended'); }; msecontroller.prototype._onsourceclose = function () { // fired on detaching from media element _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, 'mediasource onsourceclose'); if (this._mediasource && this.e != null) { this._mediasource.removeeventlistener('sourceopen', this.e.onsourceopen); this._mediasource.removeeventlistener('sourceended', this.e.onsourceended); this._mediasource.removeeventlistener('sourceclose', this.e.onsourceclose); } }; msecontroller.prototype._haspendingsegments = function () { var ps = this._pendingsegments; return ps.video.length > 0 || ps.audio.length > 0; }; msecontroller.prototype._haspendingremoveranges = function () { var prr = this._pendingremoveranges; return prr.video.length > 0 || prr.audio.length > 0; }; msecontroller.prototype._onsourcebufferupdateend = function () { if (this._requiresetmediaduration) { this._updatemediasourceduration(); } else if (this._haspendingremoveranges()) { this._doremoveranges(); } else if (this._haspendingsegments()) { this._doappendsegments(); } else if (this._haspendingeos) { this.endofstream(); } this._emitter.emit(_mse_events_js__webpack_imported_module_3__.default.update_end); }; msecontroller.prototype._onsourcebuffererror = function (e) { _utils_logger_js__webpack_imported_module_1__.default.e(this.tag, "sourcebuffer error: " + e); // this error might not always be fatal, just ignore it }; return msecontroller; }()); /* harmony default export */ __webpack_exports__["default"] = (msecontroller); /***/ }), /***/ "./src/core/mse-events.js": /*!********************************!*\ !*** ./src/core/mse-events.js ***! \********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var mseevents = { error: 'error', source_open: 'source_open', update_end: 'update_end', buffer_full: 'buffer_full' }; /* harmony default export */ __webpack_exports__["default"] = (mseevents); /***/ }), /***/ "./src/core/transmuxer.js": /*!********************************!*\ !*** ./src/core/transmuxer.js ***! \********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var events__webpack_imported_module_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js"); /* harmony import */ var events__webpack_imported_module_0___default = /*#__pure__*/__webpack_require__.n(events__webpack_imported_module_0__); /* harmony import */ var webworkify_webpack__webpack_imported_module_1__ = __webpack_require__(/*! webworkify-webpack */ "./node_modules/webworkify-webpack/index.js"); /* harmony import */ var webworkify_webpack__webpack_imported_module_1___default = /*#__pure__*/__webpack_require__.n(webworkify_webpack__webpack_imported_module_1__); /* harmony import */ var _utils_logger_js__webpack_imported_module_2__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _utils_logging_control_js__webpack_imported_module_3__ = __webpack_require__(/*! ../utils/logging-control.js */ "./src/utils/logging-control.js"); /* harmony import */ var _transmuxing_controller_js__webpack_imported_module_4__ = __webpack_require__(/*! ./transmuxing-controller.js */ "./src/core/transmuxing-controller.js"); /* harmony import */ var _transmuxing_events_js__webpack_imported_module_5__ = __webpack_require__(/*! ./transmuxing-events.js */ "./src/core/transmuxing-events.js"); /* harmony import */ var _media_info_js__webpack_imported_module_6__ = __webpack_require__(/*! ./media-info.js */ "./src/core/media-info.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var transmuxer = /** @class */ (function () { function transmuxer(mediadatasource, config) { this.tag = 'transmuxer'; this._emitter = new (events__webpack_imported_module_0___default())(); if (config.enableworker && typeof (worker) !== 'undefined') { try { this._worker = webworkify_webpack__webpack_imported_module_1___default()(/*require.resolve*/(/*! ./transmuxing-worker */ "./src/core/transmuxing-worker.js")); this._workerdestroying = false; this._worker.addeventlistener('message', this._onworkermessage.bind(this)); this._worker.postmessage({ cmd: 'init', param: [mediadatasource, config] }); this.e = { onloggingconfigchanged: this._onloggingconfigchanged.bind(this) }; _utils_logging_control_js__webpack_imported_module_3__.default.registerlistener(this.e.onloggingconfigchanged); this._worker.postmessage({ cmd: 'logging_config', param: _utils_logging_control_js__webpack_imported_module_3__.default.getconfig() }); } catch (error) { _utils_logger_js__webpack_imported_module_2__.default.e(this.tag, 'error while initialize transmuxing worker, fallback to inline transmuxing'); this._worker = null; this._controller = new _transmuxing_controller_js__webpack_imported_module_4__.default(mediadatasource, config); } } else { this._controller = new _transmuxing_controller_js__webpack_imported_module_4__.default(mediadatasource, config); } if (this._controller) { var ctl = this._controller; ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.io_error, this._onioerror.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.demux_error, this._ondemuxerror.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.init_segment, this._oninitsegment.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.media_segment, this._onmediasegment.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.loading_complete, this._onloadingcomplete.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.recovered_early_eof, this._onrecoveredearlyeof.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.media_info, this._onmediainfo.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.metadata_arrived, this._onmetadataarrived.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.scriptdata_arrived, this._onscriptdataarrived.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.statistics_info, this._onstatisticsinfo.bind(this)); ctl.on(_transmuxing_events_js__webpack_imported_module_5__.default.recommend_seekpoint, this._onrecommendseekpoint.bind(this)); } } transmuxer.prototype.destroy = function () { if (this._worker) { if (!this._workerdestroying) { this._workerdestroying = true; this._worker.postmessage({ cmd: 'destroy' }); _utils_logging_control_js__webpack_imported_module_3__.default.removelistener(this.e.onloggingconfigchanged); this.e = null; } } else { this._controller.destroy(); this._controller = null; } this._emitter.removealllisteners(); this._emitter = null; }; transmuxer.prototype.on = function (event, listener) { this._emitter.addlistener(event, listener); }; transmuxer.prototype.off = function (event, listener) { this._emitter.removelistener(event, listener); }; transmuxer.prototype.hasworker = function () { return this._worker != null; }; transmuxer.prototype.open = function () { if (this._worker) { this._worker.postmessage({ cmd: 'start' }); } else { this._controller.start(); } }; transmuxer.prototype.close = function () { if (this._worker) { this._worker.postmessage({ cmd: 'stop' }); } else { this._controller.stop(); } }; transmuxer.prototype.seek = function (milliseconds) { if (this._worker) { this._worker.postmessage({ cmd: 'seek', param: milliseconds }); } else { this._controller.seek(milliseconds); } }; transmuxer.prototype.pause = function () { if (this._worker) { this._worker.postmessage({ cmd: 'pause' }); } else { this._controller.pause(); } }; transmuxer.prototype.resume = function () { if (this._worker) { this._worker.postmessage({ cmd: 'resume' }); } else { this._controller.resume(); } }; transmuxer.prototype._oninitsegment = function (type, initsegment) { var _this = this; // do async invoke promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.init_segment, type, initsegment); }); }; transmuxer.prototype._onmediasegment = function (type, mediasegment) { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.media_segment, type, mediasegment); }); }; transmuxer.prototype._onloadingcomplete = function () { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.loading_complete); }); }; transmuxer.prototype._onrecoveredearlyeof = function () { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.recovered_early_eof); }); }; transmuxer.prototype._onmediainfo = function (mediainfo) { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.media_info, mediainfo); }); }; transmuxer.prototype._onmetadataarrived = function (metadata) { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.metadata_arrived, metadata); }); }; transmuxer.prototype._onscriptdataarrived = function (data) { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.scriptdata_arrived, data); }); }; transmuxer.prototype._onstatisticsinfo = function (statisticsinfo) { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.statistics_info, statisticsinfo); }); }; transmuxer.prototype._onioerror = function (type, info) { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.io_error, type, info); }); }; transmuxer.prototype._ondemuxerror = function (type, info) { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.demux_error, type, info); }); }; transmuxer.prototype._onrecommendseekpoint = function (milliseconds) { var _this = this; promise.resolve().then(function () { _this._emitter.emit(_transmuxing_events_js__webpack_imported_module_5__.default.recommend_seekpoint, milliseconds); }); }; transmuxer.prototype._onloggingconfigchanged = function (config) { if (this._worker) { this._worker.postmessage({ cmd: 'logging_config', param: config }); } }; transmuxer.prototype._onworkermessage = function (e) { var message = e.data; var data = message.data; if (message.msg === 'destroyed' || this._workerdestroying) { this._workerdestroying = false; this._worker.terminate(); this._worker = null; return; } switch (message.msg) { case _transmuxing_events_js__webpack_imported_module_5__.default.init_segment: case _transmuxing_events_js__webpack_imported_module_5__.default.media_segment: this._emitter.emit(message.msg, data.type, data.data); break; case _transmuxing_events_js__webpack_imported_module_5__.default.loading_complete: case _transmuxing_events_js__webpack_imported_module_5__.default.recovered_early_eof: this._emitter.emit(message.msg); break; case _transmuxing_events_js__webpack_imported_module_5__.default.media_info: object.setprototypeof(data, _media_info_js__webpack_imported_module_6__.default.prototype); this._emitter.emit(message.msg, data); break; case _transmuxing_events_js__webpack_imported_module_5__.default.metadata_arrived: case _transmuxing_events_js__webpack_imported_module_5__.default.scriptdata_arrived: case _transmuxing_events_js__webpack_imported_module_5__.default.statistics_info: this._emitter.emit(message.msg, data); break; case _transmuxing_events_js__webpack_imported_module_5__.default.io_error: case _transmuxing_events_js__webpack_imported_module_5__.default.demux_error: this._emitter.emit(message.msg, data.type, data.info); break; case _transmuxing_events_js__webpack_imported_module_5__.default.recommend_seekpoint: this._emitter.emit(message.msg, data); break; case 'logcat_callback': _utils_logger_js__webpack_imported_module_2__.default.emitter.emit('log', data.type, data.logcat); break; default: break; } }; return transmuxer; }()); /* harmony default export */ __webpack_exports__["default"] = (transmuxer); /***/ }), /***/ "./src/core/transmuxing-controller.js": /*!********************************************!*\ !*** ./src/core/transmuxing-controller.js ***! \********************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var events__webpack_imported_module_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js"); /* harmony import */ var events__webpack_imported_module_0___default = /*#__pure__*/__webpack_require__.n(events__webpack_imported_module_0__); /* harmony import */ var _utils_logger_js__webpack_imported_module_1__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _utils_browser_js__webpack_imported_module_2__ = __webpack_require__(/*! ../utils/browser.js */ "./src/utils/browser.js"); /* harmony import */ var _media_info_js__webpack_imported_module_3__ = __webpack_require__(/*! ./media-info.js */ "./src/core/media-info.js"); /* harmony import */ var _demux_flv_demuxer_js__webpack_imported_module_4__ = __webpack_require__(/*! ../demux/flv-demuxer.js */ "./src/demux/flv-demuxer.js"); /* harmony import */ var _remux_mp4_remuxer_js__webpack_imported_module_5__ = __webpack_require__(/*! ../remux/mp4-remuxer.js */ "./src/remux/mp4-remuxer.js"); /* harmony import */ var _demux_demux_errors_js__webpack_imported_module_6__ = __webpack_require__(/*! ../demux/demux-errors.js */ "./src/demux/demux-errors.js"); /* harmony import */ var _io_io_controller_js__webpack_imported_module_7__ = __webpack_require__(/*! ../io/io-controller.js */ "./src/io/io-controller.js"); /* harmony import */ var _transmuxing_events_js__webpack_imported_module_8__ = __webpack_require__(/*! ./transmuxing-events.js */ "./src/core/transmuxing-events.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ // transmuxing (io, demuxing, remuxing) controller, with multipart support var transmuxingcontroller = /** @class */ (function () { function transmuxingcontroller(mediadatasource, config) { this.tag = 'transmuxingcontroller'; this._emitter = new (events__webpack_imported_module_0___default())(); this._config = config; // treat single part media as multipart media, which has only one segment if (!mediadatasource.segments) { mediadatasource.segments = [{ duration: mediadatasource.duration, filesize: mediadatasource.filesize, url: mediadatasource.url }]; } // fill in default io params if not exists if (typeof mediadatasource.cors !== 'boolean') { mediadatasource.cors = true; } if (typeof mediadatasource.withcredentials !== 'boolean') { mediadatasource.withcredentials = false; } this._mediadatasource = mediadatasource; this._currentsegmentindex = 0; var totalduration = 0; this._mediadatasource.segments.foreach(function (segment) { // timestampbase for each segment, and calculate total duration segment.timestampbase = totalduration; totalduration += segment.duration; // params needed by iocontroller segment.cors = mediadatasource.cors; segment.withcredentials = mediadatasource.withcredentials; // referrer policy control, if exist if (config.referrerpolicy) { segment.referrerpolicy = config.referrerpolicy; } }); if (!isnan(totalduration) && this._mediadatasource.duration !== totalduration) { this._mediadatasource.duration = totalduration; } this._mediainfo = null; this._demuxer = null; this._remuxer = null; this._ioctl = null; this._pendingseektime = null; this._pendingresolveseekpoint = null; this._statisticsreporter = null; } transmuxingcontroller.prototype.destroy = function () { this._mediainfo = null; this._mediadatasource = null; if (this._statisticsreporter) { this._disablestatisticsreporter(); } if (this._ioctl) { this._ioctl.destroy(); this._ioctl = null; } if (this._demuxer) { this._demuxer.destroy(); this._demuxer = null; } if (this._remuxer) { this._remuxer.destroy(); this._remuxer = null; } this._emitter.removealllisteners(); this._emitter = null; }; transmuxingcontroller.prototype.on = function (event, listener) { this._emitter.addlistener(event, listener); }; transmuxingcontroller.prototype.off = function (event, listener) { this._emitter.removelistener(event, listener); }; transmuxingcontroller.prototype.start = function () { this._loadsegment(0); this._enablestatisticsreporter(); }; transmuxingcontroller.prototype._loadsegment = function (segmentindex, optionalfrom) { this._currentsegmentindex = segmentindex; var datasource = this._mediadatasource.segments[segmentindex]; var ioctl = this._ioctl = new _io_io_controller_js__webpack_imported_module_7__.default(datasource, this._config, segmentindex); ioctl.onerror = this._onioexception.bind(this); ioctl.onseeked = this._onioseeked.bind(this); ioctl.oncomplete = this._oniocomplete.bind(this); ioctl.onredirect = this._onioredirect.bind(this); ioctl.onrecoveredearlyeof = this._oniorecoveredearlyeof.bind(this); if (optionalfrom) { this._demuxer.binddatasource(this._ioctl); } else { ioctl.ondataarrival = this._oninitchunkarrival.bind(this); } ioctl.open(optionalfrom); }; transmuxingcontroller.prototype.stop = function () { this._internalabort(); this._disablestatisticsreporter(); }; transmuxingcontroller.prototype._internalabort = function () { if (this._ioctl) { this._ioctl.destroy(); this._ioctl = null; } }; transmuxingcontroller.prototype.pause = function () { if (this._ioctl && this._ioctl.isworking()) { this._ioctl.pause(); this._disablestatisticsreporter(); } }; transmuxingcontroller.prototype.resume = function () { if (this._ioctl && this._ioctl.ispaused()) { this._ioctl.resume(); this._enablestatisticsreporter(); } }; transmuxingcontroller.prototype.seek = function (milliseconds) { if (this._mediainfo == null || !this._mediainfo.isseekable()) { return; } var targetsegmentindex = this._searchsegmentindexcontains(milliseconds); if (targetsegmentindex === this._currentsegmentindex) { // intra-segment seeking var segmentinfo = this._mediainfo.segments[targetsegmentindex]; if (segmentinfo == undefined) { // current segment loading started, but mediainfo hasn't received yet // wait for the metadata loaded, then seek to expected position this._pendingseektime = milliseconds; } else { var keyframe = segmentinfo.getnearestkeyframe(milliseconds); this._remuxer.seek(keyframe.milliseconds); this._ioctl.seek(keyframe.fileposition); // will be resolved in _onremuxermediasegmentarrival() this._pendingresolveseekpoint = keyframe.milliseconds; } } else { // cross-segment seeking var targetsegmentinfo = this._mediainfo.segments[targetsegmentindex]; if (targetsegmentinfo == undefined) { // target segment hasn't been loaded. we need metadata then seek to expected time this._pendingseektime = milliseconds; this._internalabort(); this._remuxer.seek(); this._remuxer.insertdiscontinuity(); this._loadsegment(targetsegmentindex); // here we wait for the metadata loaded, then seek to expected position } else { // we have target segment's metadata, direct seek to target position var keyframe = targetsegmentinfo.getnearestkeyframe(milliseconds); this._internalabort(); this._remuxer.seek(milliseconds); this._remuxer.insertdiscontinuity(); this._demuxer.resetmediainfo(); this._demuxer.timestampbase = this._mediadatasource.segments[targetsegmentindex].timestampbase; this._loadsegment(targetsegmentindex, keyframe.fileposition); this._pendingresolveseekpoint = keyframe.milliseconds; this._reportsegmentmediainfo(targetsegmentindex); } } this._enablestatisticsreporter(); }; transmuxingcontroller.prototype._searchsegmentindexcontains = function (milliseconds) { var segments = this._mediadatasource.segments; var idx = segments.length - 1; for (var i = 0; i < segments.length; i++) { if (milliseconds < segments[i].timestampbase) { idx = i - 1; break; } } return idx; }; transmuxingcontroller.prototype._oninitchunkarrival = function (data, bytestart) { var _this = this; var probedata = null; var consumed = 0; if (bytestart > 0) { // iocontroller seeked immediately after opened, bytestart > 0 callback may received this._demuxer.binddatasource(this._ioctl); this._demuxer.timestampbase = this._mediadatasource.segments[this._currentsegmentindex].timestampbase; consumed = this._demuxer.parsechunks(data, bytestart); } else if ((probedata = _demux_flv_demuxer_js__webpack_imported_module_4__.default.probe(data)).match) { // always create new flvdemuxer this._demuxer = new _demux_flv_demuxer_js__webpack_imported_module_4__.default(probedata, this._config); if (!this._remuxer) { this._remuxer = new _remux_mp4_remuxer_js__webpack_imported_module_5__.default(this._config); } var mds = this._mediadatasource; if (mds.duration != undefined && !isnan(mds.duration)) { this._demuxer.overridedduration = mds.duration; } if (typeof mds.hasaudio === 'boolean') { this._demuxer.overridedhasaudio = mds.hasaudio; } if (typeof mds.hasvideo === 'boolean') { this._demuxer.overridedhasvideo = mds.hasvideo; } this._demuxer.timestampbase = mds.segments[this._currentsegmentindex].timestampbase; this._demuxer.onerror = this._ondemuxexception.bind(this); this._demuxer.onmediainfo = this._onmediainfo.bind(this); this._demuxer.onmetadataarrived = this._onmetadataarrived.bind(this); this._demuxer.onscriptdataarrived = this._onscriptdataarrived.bind(this); this._remuxer.binddatasource(this._demuxer .binddatasource(this._ioctl)); this._remuxer.oninitsegment = this._onremuxerinitsegmentarrival.bind(this); this._remuxer.onmediasegment = this._onremuxermediasegmentarrival.bind(this); consumed = this._demuxer.parsechunks(data, bytestart); } else { probedata = null; _utils_logger_js__webpack_imported_module_1__.default.e(this.tag, 'non-flv, unsupported media type!'); promise.resolve().then(function () { _this._internalabort(); }); this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.demux_error, _demux_demux_errors_js__webpack_imported_module_6__.default.format_unsupported, 'non-flv, unsupported media type'); consumed = 0; } return consumed; }; transmuxingcontroller.prototype._onmediainfo = function (mediainfo) { var _this = this; if (this._mediainfo == null) { // store first segment's mediainfo as global mediainfo this._mediainfo = object.assign({}, mediainfo); this._mediainfo.keyframesindex = null; this._mediainfo.segments = []; this._mediainfo.segmentcount = this._mediadatasource.segments.length; object.setprototypeof(this._mediainfo, _media_info_js__webpack_imported_module_3__.default.prototype); } var segmentinfo = object.assign({}, mediainfo); object.setprototypeof(segmentinfo, _media_info_js__webpack_imported_module_3__.default.prototype); this._mediainfo.segments[this._currentsegmentindex] = segmentinfo; // notify mediainfo update this._reportsegmentmediainfo(this._currentsegmentindex); if (this._pendingseektime != null) { promise.resolve().then(function () { var target = _this._pendingseektime; _this._pendingseektime = null; _this.seek(target); }); } }; transmuxingcontroller.prototype._onmetadataarrived = function (metadata) { this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.metadata_arrived, metadata); }; transmuxingcontroller.prototype._onscriptdataarrived = function (data) { this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.scriptdata_arrived, data); }; transmuxingcontroller.prototype._onioseeked = function () { this._remuxer.insertdiscontinuity(); }; transmuxingcontroller.prototype._oniocomplete = function (extradata) { var segmentindex = extradata; var nextsegmentindex = segmentindex + 1; if (nextsegmentindex < this._mediadatasource.segments.length) { this._internalabort(); this._remuxer.flushstashedsamples(); this._loadsegment(nextsegmentindex); } else { this._remuxer.flushstashedsamples(); this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.loading_complete); this._disablestatisticsreporter(); } }; transmuxingcontroller.prototype._onioredirect = function (redirectedurl) { var segmentindex = this._ioctl.extradata; this._mediadatasource.segments[segmentindex].redirectedurl = redirectedurl; }; transmuxingcontroller.prototype._oniorecoveredearlyeof = function () { this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.recovered_early_eof); }; transmuxingcontroller.prototype._onioexception = function (type, info) { _utils_logger_js__webpack_imported_module_1__.default.e(this.tag, "ioexception: type = " + type + ", code = " + info.code + ", msg = " + info.msg); this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.io_error, type, info); this._disablestatisticsreporter(); }; transmuxingcontroller.prototype._ondemuxexception = function (type, info) { _utils_logger_js__webpack_imported_module_1__.default.e(this.tag, "demuxexception: type = " + type + ", info = " + info); this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.demux_error, type, info); }; transmuxingcontroller.prototype._onremuxerinitsegmentarrival = function (type, initsegment) { this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.init_segment, type, initsegment); }; transmuxingcontroller.prototype._onremuxermediasegmentarrival = function (type, mediasegment) { if (this._pendingseektime != null) { // media segments after new-segment cross-seeking should be dropped. return; } this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.media_segment, type, mediasegment); // resolve pending seekpoint if (this._pendingresolveseekpoint != null && type === 'video') { var syncpoints = mediasegment.info.syncpoints; var seekpoint = this._pendingresolveseekpoint; this._pendingresolveseekpoint = null; // safari: pass pts for recommend_seekpoint if (_utils_browser_js__webpack_imported_module_2__.default.safari && syncpoints.length > 0 && syncpoints[0].originaldts === seekpoint) { seekpoint = syncpoints[0].pts; } // else: use original dts (keyframe.milliseconds) this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.recommend_seekpoint, seekpoint); } }; transmuxingcontroller.prototype._enablestatisticsreporter = function () { if (this._statisticsreporter == null) { this._statisticsreporter = self.setinterval(this._reportstatisticsinfo.bind(this), this._config.statisticsinforeportinterval); } }; transmuxingcontroller.prototype._disablestatisticsreporter = function () { if (this._statisticsreporter) { self.clearinterval(this._statisticsreporter); this._statisticsreporter = null; } }; transmuxingcontroller.prototype._reportsegmentmediainfo = function (segmentindex) { var segmentinfo = this._mediainfo.segments[segmentindex]; var exportinfo = object.assign({}, segmentinfo); exportinfo.duration = this._mediainfo.duration; exportinfo.segmentcount = this._mediainfo.segmentcount; delete exportinfo.segments; delete exportinfo.keyframesindex; this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.media_info, exportinfo); }; transmuxingcontroller.prototype._reportstatisticsinfo = function () { var info = {}; info.url = this._ioctl.currenturl; info.hasredirect = this._ioctl.hasredirect; if (info.hasredirect) { info.redirectedurl = this._ioctl.currentredirectedurl; } info.speed = this._ioctl.currentspeed; info.loadertype = this._ioctl.loadertype; info.currentsegmentindex = this._currentsegmentindex; info.totalsegmentcount = this._mediadatasource.segments.length; this._emitter.emit(_transmuxing_events_js__webpack_imported_module_8__.default.statistics_info, info); }; return transmuxingcontroller; }()); /* harmony default export */ __webpack_exports__["default"] = (transmuxingcontroller); /***/ }), /***/ "./src/core/transmuxing-events.js": /*!****************************************!*\ !*** ./src/core/transmuxing-events.js ***! \****************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var transmuxingevents = { io_error: 'io_error', demux_error: 'demux_error', init_segment: 'init_segment', media_segment: 'media_segment', loading_complete: 'loading_complete', recovered_early_eof: 'recovered_early_eof', media_info: 'media_info', metadata_arrived: 'metadata_arrived', scriptdata_arrived: 'scriptdata_arrived', statistics_info: 'statistics_info', recommend_seekpoint: 'recommend_seekpoint' }; /* harmony default export */ __webpack_exports__["default"] = (transmuxingevents); /***/ }), /***/ "./src/core/transmuxing-worker.js": /*!****************************************!*\ !*** ./src/core/transmuxing-worker.js ***! \****************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logging_control_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/logging-control.js */ "./src/utils/logging-control.js"); /* harmony import */ var _utils_polyfill_js__webpack_imported_module_1__ = __webpack_require__(/*! ../utils/polyfill.js */ "./src/utils/polyfill.js"); /* harmony import */ var _transmuxing_controller_js__webpack_imported_module_2__ = __webpack_require__(/*! ./transmuxing-controller.js */ "./src/core/transmuxing-controller.js"); /* harmony import */ var _transmuxing_events_js__webpack_imported_module_3__ = __webpack_require__(/*! ./transmuxing-events.js */ "./src/core/transmuxing-events.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ /* post message to worker: data: { cmd: string param: any } receive message from worker: data: { msg: string, data: any } */ var transmuxingworker = function (self) { var tag = 'transmuxingworker'; var controller = null; var logcatlistener = onlogcatcallback.bind(this); _utils_polyfill_js__webpack_imported_module_1__.default.install(); self.addeventlistener('message', function (e) { switch (e.data.cmd) { case 'init': controller = new _transmuxing_controller_js__webpack_imported_module_2__.default(e.data.param[0], e.data.param[1]); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.io_error, onioerror.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.demux_error, ondemuxerror.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.init_segment, oninitsegment.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.media_segment, onmediasegment.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.loading_complete, onloadingcomplete.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.recovered_early_eof, onrecoveredearlyeof.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.media_info, onmediainfo.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.metadata_arrived, onmetadataarrived.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.scriptdata_arrived, onscriptdataarrived.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.statistics_info, onstatisticsinfo.bind(this)); controller.on(_transmuxing_events_js__webpack_imported_module_3__.default.recommend_seekpoint, onrecommendseekpoint.bind(this)); break; case 'destroy': if (controller) { controller.destroy(); controller = null; } self.postmessage({ msg: 'destroyed' }); break; case 'start': controller.start(); break; case 'stop': controller.stop(); break; case 'seek': controller.seek(e.data.param); break; case 'pause': controller.pause(); break; case 'resume': controller.resume(); break; case 'logging_config': { var config = e.data.param; _utils_logging_control_js__webpack_imported_module_0__.default.applyconfig(config); if (config.enablecallback === true) { _utils_logging_control_js__webpack_imported_module_0__.default.addloglistener(logcatlistener); } else { _utils_logging_control_js__webpack_imported_module_0__.default.removeloglistener(logcatlistener); } break; } } }); function oninitsegment(type, initsegment) { var obj = { msg: _transmuxing_events_js__webpack_imported_module_3__.default.init_segment, data: { type: type, data: initsegment } }; self.postmessage(obj, [initsegment.data]); // data: arraybuffer } function onmediasegment(type, mediasegment) { var obj = { msg: _transmuxing_events_js__webpack_imported_module_3__.default.media_segment, data: { type: type, data: mediasegment } }; self.postmessage(obj, [mediasegment.data]); // data: arraybuffer } function onloadingcomplete() { var obj = { msg: _transmuxing_events_js__webpack_imported_module_3__.default.loading_complete }; self.postmessage(obj); } function onrecoveredearlyeof() { var obj = { msg: _transmuxing_events_js__webpack_imported_module_3__.default.recovered_early_eof }; self.postmessage(obj); } function onmediainfo(mediainfo) { var obj = { msg: _transmuxing_events_js__webpack_imported_module_3__.default.media_info, data: mediainfo }; self.postmessage(obj); } function onmetadataarrived(metadata) { var obj = { msg: _transmuxing_events_js__webpack_imported_module_3__.default.metadata_arrived, data: metadata }; self.postmessage(obj); } function onscriptdataarrived(data) { var obj = { msg: _transmuxing_events_js__webpack_imported_module_3__.default.scriptdata_arrived, data: data }; self.postmessage(obj); } function onstatisticsinfo(statinfo) { var obj = { msg: _transmuxing_events_js__webpack_imported_module_3__.default.statistics_info, data: statinfo }; self.postmessage(obj); } function onioerror(type, info) { self.postmessage({ msg: _transmuxing_events_js__webpack_imported_module_3__.default.io_error, data: { type: type, info: info } }); } function ondemuxerror(type, info) { self.postmessage({ msg: _transmuxing_events_js__webpack_imported_module_3__.default.demux_error, data: { type: type, info: info } }); } function onrecommendseekpoint(milliseconds) { self.postmessage({ msg: _transmuxing_events_js__webpack_imported_module_3__.default.recommend_seekpoint, data: milliseconds }); } function onlogcatcallback(type, str) { self.postmessage({ msg: 'logcat_callback', data: { type: type, logcat: str } }); } }; /* harmony default export */ __webpack_exports__["default"] = (transmuxingworker); /***/ }), /***/ "./src/demux/amf-parser.js": /*!*********************************!*\ !*** ./src/demux/amf-parser.js ***! \*********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _utils_utf8_conv_js__webpack_imported_module_1__ = __webpack_require__(/*! ../utils/utf8-conv.js */ "./src/utils/utf8-conv.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_2__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var le = (function () { var buf = new arraybuffer(2); (new dataview(buf)).setint16(0, 256, true); // little-endian write return (new int16array(buf))[0] === 256; // platform-spec read, if equal then le })(); var amf = /** @class */ (function () { function amf() { } amf.parsescriptdata = function (arraybuffer, dataoffset, datasize) { var data = {}; try { var name_1 = amf.parsevalue(arraybuffer, dataoffset, datasize); var value = amf.parsevalue(arraybuffer, dataoffset + name_1.size, datasize - name_1.size); data[name_1.data] = value.data; } catch (e) { _utils_logger_js__webpack_imported_module_0__.default.e('amf', e.tostring()); } return data; }; amf.parseobject = function (arraybuffer, dataoffset, datasize) { if (datasize < 3) { throw new _utils_exception_js__webpack_imported_module_2__.illegalstateexception('data not enough when parse scriptdataobject'); } var name = amf.parsestring(arraybuffer, dataoffset, datasize); var value = amf.parsevalue(arraybuffer, dataoffset + name.size, datasize - name.size); var isobjectend = value.objectend; return { data: { name: name.data, value: value.data }, size: name.size + value.size, objectend: isobjectend }; }; amf.parsevariable = function (arraybuffer, dataoffset, datasize) { return amf.parseobject(arraybuffer, dataoffset, datasize); }; amf.parsestring = function (arraybuffer, dataoffset, datasize) { if (datasize < 2) { throw new _utils_exception_js__webpack_imported_module_2__.illegalstateexception('data not enough when parse string'); } var v = new dataview(arraybuffer, dataoffset, datasize); var length = v.getuint16(0, !le); var str; if (length > 0) { str = (0,_utils_utf8_conv_js__webpack_imported_module_1__.default)(new uint8array(arraybuffer, dataoffset + 2, length)); } else { str = ''; } return { data: str, size: 2 + length }; }; amf.parselongstring = function (arraybuffer, dataoffset, datasize) { if (datasize < 4) { throw new _utils_exception_js__webpack_imported_module_2__.illegalstateexception('data not enough when parse longstring'); } var v = new dataview(arraybuffer, dataoffset, datasize); var length = v.getuint32(0, !le); var str; if (length > 0) { str = (0,_utils_utf8_conv_js__webpack_imported_module_1__.default)(new uint8array(arraybuffer, dataoffset + 4, length)); } else { str = ''; } return { data: str, size: 4 + length }; }; amf.parsedate = function (arraybuffer, dataoffset, datasize) { if (datasize < 10) { throw new _utils_exception_js__webpack_imported_module_2__.illegalstateexception('data size invalid when parse date'); } var v = new dataview(arraybuffer, dataoffset, datasize); var timestamp = v.getfloat64(0, !le); var localtimeoffset = v.getint16(8, !le); timestamp += localtimeoffset * 60 * 1000; // get utc time return { data: new date(timestamp), size: 8 + 2 }; }; amf.parsevalue = function (arraybuffer, dataoffset, datasize) { if (datasize < 1) { throw new _utils_exception_js__webpack_imported_module_2__.illegalstateexception('data not enough when parse value'); } var v = new dataview(arraybuffer, dataoffset, datasize); var offset = 1; var type = v.getuint8(0); var value; var objectend = false; try { switch (type) { case 0: // number(double) type value = v.getfloat64(1, !le); offset += 8; break; case 1: { // boolean type var b = v.getuint8(1); value = b ? true : false; offset += 1; break; } case 2: { // string type var amfstr = amf.parsestring(arraybuffer, dataoffset + 1, datasize - 1); value = amfstr.data; offset += amfstr.size; break; } case 3: { // object(s) type value = {}; var terminal = 0; // workaround for malformed objects which has missing scriptdataobjectend if ((v.getuint32(datasize - 4, !le) & 0x00ffffff) === 9) { terminal = 3; } while (offset < datasize - 4) { // 4 === type(ui8) + scriptdataobjectend(ui24) var amfobj = amf.parseobject(arraybuffer, dataoffset + offset, datasize - offset - terminal); if (amfobj.objectend) break; value[amfobj.data.name] = amfobj.data.value; offset += amfobj.size; } if (offset <= datasize - 3) { var marker = v.getuint32(offset - 1, !le) & 0x00ffffff; if (marker === 9) { offset += 3; } } break; } case 8: { // ecma array type (mixed array) value = {}; offset += 4; // ecmaarraylength(ui32) var terminal = 0; // workaround for malformed mixedarrays which has missing scriptdataobjectend if ((v.getuint32(datasize - 4, !le) & 0x00ffffff) === 9) { terminal = 3; } while (offset < datasize - 8) { // 8 === type(ui8) + ecmaarraylength(ui32) + scriptdatavariableend(ui24) var amfvar = amf.parsevariable(arraybuffer, dataoffset + offset, datasize - offset - terminal); if (amfvar.objectend) break; value[amfvar.data.name] = amfvar.data.value; offset += amfvar.size; } if (offset <= datasize - 3) { var marker = v.getuint32(offset - 1, !le) & 0x00ffffff; if (marker === 9) { offset += 3; } } break; } case 9: // scriptdataobjectend value = undefined; offset = 1; objectend = true; break; case 10: { // strict array type // scriptdatavalue[n]. note: according to video_file_format_spec_v10_1.pdf value = []; var strictarraylength = v.getuint32(1, !le); offset += 4; for (var i = 0; i < strictarraylength; i++) { var val = amf.parsevalue(arraybuffer, dataoffset + offset, datasize - offset); value.push(val.data); offset += val.size; } break; } case 11: { // date type var date = amf.parsedate(arraybuffer, dataoffset + 1, datasize - 1); value = date.data; offset += date.size; break; } case 12: { // long string type var amflongstr = amf.parsestring(arraybuffer, dataoffset + 1, datasize - 1); value = amflongstr.data; offset += amflongstr.size; break; } default: // ignore and skip offset = datasize; _utils_logger_js__webpack_imported_module_0__.default.w('amf', 'unsupported amf value type ' + type); } } catch (e) { _utils_logger_js__webpack_imported_module_0__.default.e('amf', e.tostring()); } return { data: value, size: offset, objectend: objectend }; }; return amf; }()); /* harmony default export */ __webpack_exports__["default"] = (amf); /***/ }), /***/ "./src/demux/demux-errors.js": /*!***********************************!*\ !*** ./src/demux/demux-errors.js ***! \***********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var demuxerrors = { ok: 'ok', format_error: 'formaterror', format_unsupported: 'formatunsupported', codec_unsupported: 'codecunsupported' }; /* harmony default export */ __webpack_exports__["default"] = (demuxerrors); /***/ }), /***/ "./src/demux/exp-golomb.js": /*!*********************************!*\ !*** ./src/demux/exp-golomb.js ***! \*********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_exception_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ // exponential-golomb buffer decoder var expgolomb = /** @class */ (function () { function expgolomb(uint8array) { this.tag = 'expgolomb'; this._buffer = uint8array; this._buffer_index = 0; this._total_bytes = uint8array.bytelength; this._total_bits = uint8array.bytelength * 8; this._current_word = 0; this._current_word_bits_left = 0; } expgolomb.prototype.destroy = function () { this._buffer = null; }; expgolomb.prototype._fillcurrentword = function () { var buffer_bytes_left = this._total_bytes - this._buffer_index; if (buffer_bytes_left <= 0) throw new _utils_exception_js__webpack_imported_module_0__.illegalstateexception('expgolomb: _fillcurrentword() but no bytes available'); var bytes_read = math.min(4, buffer_bytes_left); var word = new uint8array(4); word.set(this._buffer.subarray(this._buffer_index, this._buffer_index + bytes_read)); this._current_word = new dataview(word.buffer).getuint32(0, false); this._buffer_index += bytes_read; this._current_word_bits_left = bytes_read * 8; }; expgolomb.prototype.readbits = function (bits) { if (bits > 32) throw new _utils_exception_js__webpack_imported_module_0__.invalidargumentexception('expgolomb: readbits() bits exceeded max 32bits!'); if (bits <= this._current_word_bits_left) { var result_1 = this._current_word >>> (32 - bits); this._current_word <<= bits; this._current_word_bits_left -= bits; return result_1; } var result = this._current_word_bits_left ? this._current_word : 0; result = result >>> (32 - this._current_word_bits_left); var bits_need_left = bits - this._current_word_bits_left; this._fillcurrentword(); var bits_read_next = math.min(bits_need_left, this._current_word_bits_left); var result2 = this._current_word >>> (32 - bits_read_next); this._current_word <<= bits_read_next; this._current_word_bits_left -= bits_read_next; result = (result << bits_read_next) | result2; return result; }; expgolomb.prototype.readbool = function () { return this.readbits(1) === 1; }; expgolomb.prototype.readbyte = function () { return this.readbits(8); }; expgolomb.prototype._skipleadingzero = function () { var zero_count; for (zero_count = 0; zero_count < this._current_word_bits_left; zero_count++) { if (0 !== (this._current_word & (0x80000000 >>> zero_count))) { this._current_word <<= zero_count; this._current_word_bits_left -= zero_count; return zero_count; } } this._fillcurrentword(); return zero_count + this._skipleadingzero(); }; expgolomb.prototype.readueg = function () { var leading_zeros = this._skipleadingzero(); return this.readbits(leading_zeros + 1) - 1; }; expgolomb.prototype.readseg = function () { var value = this.readueg(); if (value & 0x01) { return (value + 1) >>> 1; } else { return -1 * (value >>> 1); } }; return expgolomb; }()); /* harmony default export */ __webpack_exports__["default"] = (expgolomb); /***/ }), /***/ "./src/demux/flv-demuxer.js": /*!**********************************!*\ !*** ./src/demux/flv-demuxer.js ***! \**********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _amf_parser_js__webpack_imported_module_1__ = __webpack_require__(/*! ./amf-parser.js */ "./src/demux/amf-parser.js"); /* harmony import */ var _sps_parser_js__webpack_imported_module_2__ = __webpack_require__(/*! ./sps-parser.js */ "./src/demux/sps-parser.js"); /* harmony import */ var _demux_errors_js__webpack_imported_module_3__ = __webpack_require__(/*! ./demux-errors.js */ "./src/demux/demux-errors.js"); /* harmony import */ var _core_media_info_js__webpack_imported_module_4__ = __webpack_require__(/*! ../core/media-info.js */ "./src/core/media-info.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_5__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ function swap16(src) { return (((src >>> 8) & 0xff) | ((src & 0xff) << 8)); } function swap32(src) { return (((src & 0xff000000) >>> 24) | ((src & 0x00ff0000) >>> 8) | ((src & 0x0000ff00) << 8) | ((src & 0x000000ff) << 24)); } function readbig32(array, index) { return ((array[index] << 24) | (array[index + 1] << 16) | (array[index + 2] << 8) | (array[index + 3])); } var flvdemuxer = /** @class */ (function () { function flvdemuxer(probedata, config) { this.tag = 'flvdemuxer'; this._config = config; this._onerror = null; this._onmediainfo = null; this._onmetadataarrived = null; this._onscriptdataarrived = null; this._ontrackmetadata = null; this._ondataavailable = null; this._dataoffset = probedata.dataoffset; this._firstparse = true; this._dispatch = false; this._hasaudio = probedata.hasaudiotrack; this._hasvideo = probedata.hasvideotrack; this._hasaudioflagoverrided = false; this._hasvideoflagoverrided = false; this._audioinitialmetadatadispatched = false; this._videoinitialmetadatadispatched = false; this._mediainfo = new _core_media_info_js__webpack_imported_module_4__.default(); this._mediainfo.hasaudio = this._hasaudio; this._mediainfo.hasvideo = this._hasvideo; this._metadata = null; this._audiometadata = null; this._videometadata = null; this._nalulengthsize = 4; this._timestampbase = 0; // int32, in milliseconds this._timescale = 1000; this._duration = 0; // int32, in milliseconds this._durationoverrided = false; this._referenceframerate = { fixed: true, fps: 23.976, fps_num: 23976, fps_den: 1000 }; this._flvsoundratetable = [5500, 11025, 22050, 44100, 48000]; this._mpegsamplingrates = [ 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 ]; this._mpegaudiov10sampleratetable = [44100, 48000, 32000, 0]; this._mpegaudiov20sampleratetable = [22050, 24000, 16000, 0]; this._mpegaudiov25sampleratetable = [11025, 12000, 8000, 0]; this._mpegaudiol1bitratetable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1]; this._mpegaudiol2bitratetable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1]; this._mpegaudiol3bitratetable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1]; this._videotrack = { type: 'video', id: 1, sequencenumber: 0, samples: [], length: 0 }; this._audiotrack = { type: 'audio', id: 2, sequencenumber: 0, samples: [], length: 0 }; this._littleendian = (function () { var buf = new arraybuffer(2); (new dataview(buf)).setint16(0, 256, true); // little-endian write return (new int16array(buf))[0] === 256; // platform-spec read, if equal then le })(); } flvdemuxer.prototype.destroy = function () { this._mediainfo = null; this._metadata = null; this._audiometadata = null; this._videometadata = null; this._videotrack = null; this._audiotrack = null; this._onerror = null; this._onmediainfo = null; this._onmetadataarrived = null; this._onscriptdataarrived = null; this._ontrackmetadata = null; this._ondataavailable = null; }; flvdemuxer.probe = function (buffer) { var data = new uint8array(buffer); var mismatch = { match: false }; if (data[0] !== 0x46 || data[1] !== 0x4c || data[2] !== 0x56 || data[3] !== 0x01) { return mismatch; } var hasaudio = ((data[4] & 4) >>> 2) !== 0; var hasvideo = (data[4] & 1) !== 0; var offset = readbig32(data, 5); if (offset < 9) { return mismatch; } return { match: true, consumed: offset, dataoffset: offset, hasaudiotrack: hasaudio, hasvideotrack: hasvideo }; }; flvdemuxer.prototype.binddatasource = function (loader) { loader.ondataarrival = this.parsechunks.bind(this); return this; }; object.defineproperty(flvdemuxer.prototype, "ontrackmetadata", { // prototype: function(type: string, metadata: any): void get: function () { return this._ontrackmetadata; }, set: function (callback) { this._ontrackmetadata = callback; }, enumerable: false, configurable: true }); object.defineproperty(flvdemuxer.prototype, "onmediainfo", { // prototype: function(mediainfo: mediainfo): void get: function () { return this._onmediainfo; }, set: function (callback) { this._onmediainfo = callback; }, enumerable: false, configurable: true }); object.defineproperty(flvdemuxer.prototype, "onmetadataarrived", { get: function () { return this._onmetadataarrived; }, set: function (callback) { this._onmetadataarrived = callback; }, enumerable: false, configurable: true }); object.defineproperty(flvdemuxer.prototype, "onscriptdataarrived", { get: function () { return this._onscriptdataarrived; }, set: function (callback) { this._onscriptdataarrived = callback; }, enumerable: false, configurable: true }); object.defineproperty(flvdemuxer.prototype, "onerror", { // prototype: function(type: number, info: string): void get: function () { return this._onerror; }, set: function (callback) { this._onerror = callback; }, enumerable: false, configurable: true }); object.defineproperty(flvdemuxer.prototype, "ondataavailable", { // prototype: function(videotrack: any, audiotrack: any): void get: function () { return this._ondataavailable; }, set: function (callback) { this._ondataavailable = callback; }, enumerable: false, configurable: true }); object.defineproperty(flvdemuxer.prototype, "timestampbase", { // timestamp base for output samples, must be in milliseconds get: function () { return this._timestampbase; }, set: function (base) { this._timestampbase = base; }, enumerable: false, configurable: true }); object.defineproperty(flvdemuxer.prototype, "overridedduration", { get: function () { return this._duration; }, // force-override media duration. must be in milliseconds, int32 set: function (duration) { this._durationoverrided = true; this._duration = duration; this._mediainfo.duration = duration; }, enumerable: false, configurable: true }); object.defineproperty(flvdemuxer.prototype, "overridedhasaudio", { // force-override audio track present flag, boolean set: function (hasaudio) { this._hasaudioflagoverrided = true; this._hasaudio = hasaudio; this._mediainfo.hasaudio = hasaudio; }, enumerable: false, configurable: true }); object.defineproperty(flvdemuxer.prototype, "overridedhasvideo", { // force-override video track present flag, boolean set: function (hasvideo) { this._hasvideoflagoverrided = true; this._hasvideo = hasvideo; this._mediainfo.hasvideo = hasvideo; }, enumerable: false, configurable: true }); flvdemuxer.prototype.resetmediainfo = function () { this._mediainfo = new _core_media_info_js__webpack_imported_module_4__.default(); }; flvdemuxer.prototype._isinitialmetadatadispatched = function () { if (this._hasaudio && this._hasvideo) { // both audio & video return this._audioinitialmetadatadispatched && this._videoinitialmetadatadispatched; } if (this._hasaudio && !this._hasvideo) { // audio only return this._audioinitialmetadatadispatched; } if (!this._hasaudio && this._hasvideo) { // video only return this._videoinitialmetadatadispatched; } return false; }; // function parsechunks(chunk: arraybuffer, bytestart: number): number; flvdemuxer.prototype.parsechunks = function (chunk, bytestart) { if (!this._onerror || !this._onmediainfo || !this._ontrackmetadata || !this._ondataavailable) { throw new _utils_exception_js__webpack_imported_module_5__.illegalstateexception('flv: onerror & onmediainfo & ontrackmetadata & ondataavailable callback must be specified'); } var offset = 0; var le = this._littleendian; if (bytestart === 0) { // buffer with flv header if (chunk.bytelength > 13) { var probedata = flvdemuxer.probe(chunk); offset = probedata.dataoffset; } else { return 0; } } if (this._firstparse) { // handle previoustagsize0 before tag1 this._firstparse = false; if (bytestart + offset !== this._dataoffset) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'first time parsing but chunk bytestart invalid!'); } var v = new dataview(chunk, offset); var prevtagsize0 = v.getuint32(0, !le); if (prevtagsize0 !== 0) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'prevtagsize0 !== 0 !!!'); } offset += 4; } while (offset < chunk.bytelength) { this._dispatch = true; var v = new dataview(chunk, offset); if (offset + 11 + 4 > chunk.bytelength) { // data not enough for parsing an flv tag break; } var tagtype = v.getuint8(0); var datasize = v.getuint32(0, !le) & 0x00ffffff; if (offset + 11 + datasize + 4 > chunk.bytelength) { // data not enough for parsing actual data body break; } if (tagtype !== 8 && tagtype !== 9 && tagtype !== 18) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, "unsupported tag type " + tagtype + ", skipped"); // consume the whole tag (skip it) offset += 11 + datasize + 4; continue; } var ts2 = v.getuint8(4); var ts1 = v.getuint8(5); var ts0 = v.getuint8(6); var ts3 = v.getuint8(7); var timestamp = ts0 | (ts1 << 8) | (ts2 << 16) | (ts3 << 24); var streamid = v.getuint32(7, !le) & 0x00ffffff; if (streamid !== 0) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'meet tag which has streamid != 0!'); } var dataoffset = offset + 11; switch (tagtype) { case 8: // audio this._parseaudiodata(chunk, dataoffset, datasize, timestamp); break; case 9: // video this._parsevideodata(chunk, dataoffset, datasize, timestamp, bytestart + offset); break; case 18: // scriptdataobject this._parsescriptdata(chunk, dataoffset, datasize); break; } var prevtagsize = v.getuint32(11 + datasize, !le); if (prevtagsize !== 11 + datasize) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, "invalid prevtagsize " + prevtagsize); } offset += 11 + datasize + 4; // tagbody + datasize + prevtagsize } // dispatch parsed frames to consumer (typically, the remuxer) if (this._isinitialmetadatadispatched()) { if (this._dispatch && (this._audiotrack.length || this._videotrack.length)) { this._ondataavailable(this._audiotrack, this._videotrack); } } return offset; // consumed bytes, just equals latest offset index }; flvdemuxer.prototype._parsescriptdata = function (arraybuffer, dataoffset, datasize) { var scriptdata = _amf_parser_js__webpack_imported_module_1__.default.parsescriptdata(arraybuffer, dataoffset, datasize); if (scriptdata.hasownproperty('onmetadata')) { if (scriptdata.onmetadata == null || typeof scriptdata.onmetadata !== 'object') { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'invalid onmetadata structure!'); return; } if (this._metadata) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'found another onmetadata tag!'); } this._metadata = scriptdata; var onmetadata = this._metadata.onmetadata; if (this._onmetadataarrived) { this._onmetadataarrived(object.assign({}, onmetadata)); } if (typeof onmetadata.hasaudio === 'boolean') { // hasaudio if (this._hasaudioflagoverrided === false) { this._hasaudio = onmetadata.hasaudio; this._mediainfo.hasaudio = this._hasaudio; } } if (typeof onmetadata.hasvideo === 'boolean') { // hasvideo if (this._hasvideoflagoverrided === false) { this._hasvideo = onmetadata.hasvideo; this._mediainfo.hasvideo = this._hasvideo; } } if (typeof onmetadata.audiodatarate === 'number') { // audiodatarate this._mediainfo.audiodatarate = onmetadata.audiodatarate; } if (typeof onmetadata.videodatarate === 'number') { // videodatarate this._mediainfo.videodatarate = onmetadata.videodatarate; } if (typeof onmetadata.width === 'number') { // width this._mediainfo.width = onmetadata.width; } if (typeof onmetadata.height === 'number') { // height this._mediainfo.height = onmetadata.height; } if (typeof onmetadata.duration === 'number') { // duration if (!this._durationoverrided) { var duration = math.floor(onmetadata.duration * this._timescale); this._duration = duration; this._mediainfo.duration = duration; } } else { this._mediainfo.duration = 0; } if (typeof onmetadata.framerate === 'number') { // framerate var fps_num = math.floor(onmetadata.framerate * 1000); if (fps_num > 0) { var fps = fps_num / 1000; this._referenceframerate.fixed = true; this._referenceframerate.fps = fps; this._referenceframerate.fps_num = fps_num; this._referenceframerate.fps_den = 1000; this._mediainfo.fps = fps; } } if (typeof onmetadata.keyframes === 'object') { // keyframes this._mediainfo.haskeyframesindex = true; var keyframes = onmetadata.keyframes; this._mediainfo.keyframesindex = this._parsekeyframesindex(keyframes); onmetadata.keyframes = null; // keyframes has been extracted, remove it } else { this._mediainfo.haskeyframesindex = false; } this._dispatch = false; this._mediainfo.metadata = onmetadata; _utils_logger_js__webpack_imported_module_0__.default.v(this.tag, 'parsed onmetadata'); if (this._mediainfo.iscomplete()) { this._onmediainfo(this._mediainfo); } } if (object.keys(scriptdata).length > 0) { if (this._onscriptdataarrived) { this._onscriptdataarrived(object.assign({}, scriptdata)); } } }; flvdemuxer.prototype._parsekeyframesindex = function (keyframes) { var times = []; var filepositions = []; // ignore first keyframe which is actually avc sequence header (avcdecoderconfigurationrecord) for (var i = 1; i < keyframes.times.length; i++) { var time = this._timestampbase + math.floor(keyframes.times[i] * 1000); times.push(time); filepositions.push(keyframes.filepositions[i]); } return { times: times, filepositions: filepositions }; }; flvdemuxer.prototype._parseaudiodata = function (arraybuffer, dataoffset, datasize, tagtimestamp) { if (datasize <= 1) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'flv: invalid audio packet, missing sounddata payload!'); return; } if (this._hasaudioflagoverrided === true && this._hasaudio === false) { // if hasaudio: false indicated explicitly in mediadatasource, // ignore all the audio packets return; } var le = this._littleendian; var v = new dataview(arraybuffer, dataoffset, datasize); var soundspec = v.getuint8(0); var soundformat = soundspec >>> 4; if (soundformat !== 2 && soundformat !== 10) { // mp3 or aac this._onerror(_demux_errors_js__webpack_imported_module_3__.default.codec_unsupported, 'flv: unsupported audio codec idx: ' + soundformat); return; } var soundrate = 0; var soundrateindex = (soundspec & 12) >>> 2; if (soundrateindex >= 0 && soundrateindex <= 4) { soundrate = this._flvsoundratetable[soundrateindex]; } else { this._onerror(_demux_errors_js__webpack_imported_module_3__.default.format_error, 'flv: invalid audio sample rate idx: ' + soundrateindex); return; } var soundsize = (soundspec & 2) >>> 1; // unused var soundtype = (soundspec & 1); var meta = this._audiometadata; var track = this._audiotrack; if (!meta) { if (this._hasaudio === false && this._hasaudioflagoverrided === false) { this._hasaudio = true; this._mediainfo.hasaudio = true; } // initial metadata meta = this._audiometadata = {}; meta.type = 'audio'; meta.id = track.id; meta.timescale = this._timescale; meta.duration = this._duration; meta.audiosamplerate = soundrate; meta.channelcount = (soundtype === 0 ? 1 : 2); } if (soundformat === 10) { // aac var aacdata = this._parseaacaudiodata(arraybuffer, dataoffset + 1, datasize - 1); if (aacdata == undefined) { return; } if (aacdata.packettype === 0) { // aac sequence header (audiospecificconfig) if (meta.config) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'found another audiospecificconfig!'); } var misc = aacdata.data; meta.audiosamplerate = misc.samplingrate; meta.channelcount = misc.channelcount; meta.codec = misc.codec; meta.originalcodec = misc.originalcodec; meta.config = misc.config; // the decode result of an aac sample is 1024 pcm samples meta.refsampleduration = 1024 / meta.audiosamplerate * meta.timescale; _utils_logger_js__webpack_imported_module_0__.default.v(this.tag, 'parsed audiospecificconfig'); if (this._isinitialmetadatadispatched()) { // non-initial metadata, force dispatch (or flush) parsed frames to remuxer if (this._dispatch && (this._audiotrack.length || this._videotrack.length)) { this._ondataavailable(this._audiotrack, this._videotrack); } } else { this._audioinitialmetadatadispatched = true; } // then notify new metadata this._dispatch = false; this._ontrackmetadata('audio', meta); var mi = this._mediainfo; mi.audiocodec = meta.originalcodec; mi.audiosamplerate = meta.audiosamplerate; mi.audiochannelcount = meta.channelcount; if (mi.hasvideo) { if (mi.videocodec != null) { mi.mimetype = 'video/x-flv; codecs="' + mi.videocodec + ',' + mi.audiocodec + '"'; } } else { mi.mimetype = 'video/x-flv; codecs="' + mi.audiocodec + '"'; } if (mi.iscomplete()) { this._onmediainfo(mi); } } else if (aacdata.packettype === 1) { // aac raw frame data var dts = this._timestampbase + tagtimestamp; var aacsample = { unit: aacdata.data, length: aacdata.data.bytelength, dts: dts, pts: dts }; track.samples.push(aacsample); track.length += aacdata.data.length; } else { _utils_logger_js__webpack_imported_module_0__.default.e(this.tag, "flv: unsupported aac data type " + aacdata.packettype); } } else if (soundformat === 2) { // mp3 if (!meta.codec) { // we need metadata for mp3 audio track, extract info from frame header var misc = this._parsemp3audiodata(arraybuffer, dataoffset + 1, datasize - 1, true); if (misc == undefined) { return; } meta.audiosamplerate = misc.samplingrate; meta.channelcount = misc.channelcount; meta.codec = misc.codec; meta.originalcodec = misc.originalcodec; // the decode result of an mp3 sample is 1152 pcm samples meta.refsampleduration = 1152 / meta.audiosamplerate * meta.timescale; _utils_logger_js__webpack_imported_module_0__.default.v(this.tag, 'parsed mpeg audio frame header'); this._audioinitialmetadatadispatched = true; this._ontrackmetadata('audio', meta); var mi = this._mediainfo; mi.audiocodec = meta.codec; mi.audiosamplerate = meta.audiosamplerate; mi.audiochannelcount = meta.channelcount; mi.audiodatarate = misc.bitrate; if (mi.hasvideo) { if (mi.videocodec != null) { mi.mimetype = 'video/x-flv; codecs="' + mi.videocodec + ',' + mi.audiocodec + '"'; } } else { mi.mimetype = 'video/x-flv; codecs="' + mi.audiocodec + '"'; } if (mi.iscomplete()) { this._onmediainfo(mi); } } // this packet is always a valid audio packet, extract it var data = this._parsemp3audiodata(arraybuffer, dataoffset + 1, datasize - 1, false); if (data == undefined) { return; } var dts = this._timestampbase + tagtimestamp; var mp3sample = { unit: data, length: data.bytelength, dts: dts, pts: dts }; track.samples.push(mp3sample); track.length += data.length; } }; flvdemuxer.prototype._parseaacaudiodata = function (arraybuffer, dataoffset, datasize) { if (datasize <= 1) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'flv: invalid aac packet, missing aacpackettype or/and data!'); return; } var result = {}; var array = new uint8array(arraybuffer, dataoffset, datasize); result.packettype = array[0]; if (array[0] === 0) { result.data = this._parseaacaudiospecificconfig(arraybuffer, dataoffset + 1, datasize - 1); } else { result.data = array.subarray(1); } return result; }; flvdemuxer.prototype._parseaacaudiospecificconfig = function (arraybuffer, dataoffset, datasize) { var array = new uint8array(arraybuffer, dataoffset, datasize); var config = null; /* audio object type: 0: null 1: aac main 2: aac lc 3: aac ssr (scalable sample rate) 4: aac ltp (long term prediction) 5: he-aac / sbr (spectral band replication) 6: aac scalable */ var audioobjecttype = 0; var originalaudioobjecttype = 0; var audioextensionobjecttype = null; var samplingindex = 0; var extensionsamplingindex = null; // 5 bits audioobjecttype = originalaudioobjecttype = array[0] >>> 3; // 4 bits samplingindex = ((array[0] & 0x07) << 1) | (array[1] >>> 7); if (samplingindex < 0 || samplingindex >= this._mpegsamplingrates.length) { this._onerror(_demux_errors_js__webpack_imported_module_3__.default.format_error, 'flv: aac invalid sampling frequency index!'); return; } var samplingfrequence = this._mpegsamplingrates[samplingindex]; // 4 bits var channelconfig = (array[1] & 0x78) >>> 3; if (channelconfig < 0 || channelconfig >= 8) { this._onerror(_demux_errors_js__webpack_imported_module_3__.default.format_error, 'flv: aac invalid channel configuration'); return; } if (audioobjecttype === 5) { // he-aac? // 4 bits extensionsamplingindex = ((array[1] & 0x07) << 1) | (array[2] >>> 7); // 5 bits audioextensionobjecttype = (array[2] & 0x7c) >>> 2; } // workarounds for various browsers var useragent = self.navigator.useragent.tolowercase(); if (useragent.indexof('firefox') !== -1) { // firefox: use sbr (he-aac) if freq less than 24khz if (samplingindex >= 6) { audioobjecttype = 5; config = new array(4); extensionsamplingindex = samplingindex - 3; } else { // use lc-aac audioobjecttype = 2; config = new array(2); extensionsamplingindex = samplingindex; } } else if (useragent.indexof('android') !== -1) { // android: always use lc-aac audioobjecttype = 2; config = new array(2); extensionsamplingindex = samplingindex; } else { // for other browsers, e.g. chrome... // always use he-aac to make it easier to switch aac codec profile audioobjecttype = 5; extensionsamplingindex = samplingindex; config = new array(4); if (samplingindex >= 6) { extensionsamplingindex = samplingindex - 3; } else if (channelconfig === 1) { // mono channel audioobjecttype = 2; config = new array(2); extensionsamplingindex = samplingindex; } } config[0] = audioobjecttype << 3; config[0] |= (samplingindex & 0x0f) >>> 1; config[1] = (samplingindex & 0x0f) << 7; config[1] |= (channelconfig & 0x0f) << 3; if (audioobjecttype === 5) { config[1] |= ((extensionsamplingindex & 0x0f) >>> 1); config[2] = (extensionsamplingindex & 0x01) << 7; // extended audio object type: force to 2 (lc-aac) config[2] |= (2 << 2); config[3] = 0; } return { config: config, samplingrate: samplingfrequence, channelcount: channelconfig, codec: 'mp4a.40.' + audioobjecttype, originalcodec: 'mp4a.40.' + originalaudioobjecttype }; }; flvdemuxer.prototype._parsemp3audiodata = function (arraybuffer, dataoffset, datasize, requestheader) { if (datasize < 4) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'flv: invalid mp3 packet, header missing!'); return; } var le = this._littleendian; var array = new uint8array(arraybuffer, dataoffset, datasize); var result = null; if (requestheader) { if (array[0] !== 0xff) { return; } var ver = (array[1] >>> 3) & 0x03; var layer = (array[1] & 0x06) >> 1; var bitrate_index = (array[2] & 0xf0) >>> 4; var sampling_freq_index = (array[2] & 0x0c) >>> 2; var channel_mode = (array[3] >>> 6) & 0x03; var channel_count = channel_mode !== 3 ? 2 : 1; var sample_rate = 0; var bit_rate = 0; var object_type = 34; // layer-3, listed in mpeg-4 audio object types var codec = 'mp3'; switch (ver) { case 0: // mpeg 2.5 sample_rate = this._mpegaudiov25sampleratetable[sampling_freq_index]; break; case 2: // mpeg 2 sample_rate = this._mpegaudiov20sampleratetable[sampling_freq_index]; break; case 3: // mpeg 1 sample_rate = this._mpegaudiov10sampleratetable[sampling_freq_index]; break; } switch (layer) { case 1: // layer 3 object_type = 34; if (bitrate_index < this._mpegaudiol3bitratetable.length) { bit_rate = this._mpegaudiol3bitratetable[bitrate_index]; } break; case 2: // layer 2 object_type = 33; if (bitrate_index < this._mpegaudiol2bitratetable.length) { bit_rate = this._mpegaudiol2bitratetable[bitrate_index]; } break; case 3: // layer 1 object_type = 32; if (bitrate_index < this._mpegaudiol1bitratetable.length) { bit_rate = this._mpegaudiol1bitratetable[bitrate_index]; } break; } result = { bitrate: bit_rate, samplingrate: sample_rate, channelcount: channel_count, codec: codec, originalcodec: codec }; } else { result = array; } return result; }; flvdemuxer.prototype._parsevideodata = function (arraybuffer, dataoffset, datasize, tagtimestamp, tagposition) { if (datasize <= 1) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'flv: invalid video packet, missing videodata payload!'); return; } if (this._hasvideoflagoverrided === true && this._hasvideo === false) { // if hasvideo: false indicated explicitly in mediadatasource, // ignore all the video packets return; } var spec = (new uint8array(arraybuffer, dataoffset, datasize))[0]; var frametype = (spec & 240) >>> 4; var codecid = spec & 15; if (codecid !== 7) { this._onerror(_demux_errors_js__webpack_imported_module_3__.default.codec_unsupported, "flv: unsupported codec in video frame: " + codecid); return; } this._parseavcvideopacket(arraybuffer, dataoffset + 1, datasize - 1, tagtimestamp, tagposition, frametype); }; flvdemuxer.prototype._parseavcvideopacket = function (arraybuffer, dataoffset, datasize, tagtimestamp, tagposition, frametype) { if (datasize < 4) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'flv: invalid avc packet, missing avcpackettype or/and compositiontime'); return; } var le = this._littleendian; var v = new dataview(arraybuffer, dataoffset, datasize); var packettype = v.getuint8(0); var cts_unsigned = v.getuint32(0, !le) & 0x00ffffff; var cts = (cts_unsigned << 8) >> 8; // convert to 24-bit signed int if (packettype === 0) { // avcdecoderconfigurationrecord this._parseavcdecoderconfigurationrecord(arraybuffer, dataoffset + 4, datasize - 4); } else if (packettype === 1) { // one or more nalus this._parseavcvideodata(arraybuffer, dataoffset + 4, datasize - 4, tagtimestamp, tagposition, frametype, cts); } else if (packettype === 2) { // empty, avc end of sequence } else { this._onerror(_demux_errors_js__webpack_imported_module_3__.default.format_error, "flv: invalid video packet type " + packettype); return; } }; flvdemuxer.prototype._parseavcdecoderconfigurationrecord = function (arraybuffer, dataoffset, datasize) { if (datasize < 7) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'flv: invalid avcdecoderconfigurationrecord, lack of data!'); return; } var meta = this._videometadata; var track = this._videotrack; var le = this._littleendian; var v = new dataview(arraybuffer, dataoffset, datasize); if (!meta) { if (this._hasvideo === false && this._hasvideoflagoverrided === false) { this._hasvideo = true; this._mediainfo.hasvideo = true; } meta = this._videometadata = {}; meta.type = 'video'; meta.id = track.id; meta.timescale = this._timescale; meta.duration = this._duration; } else { if (typeof meta.avcc !== 'undefined') { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'found another avcdecoderconfigurationrecord!'); } } var version = v.getuint8(0); // configurationversion var avcprofile = v.getuint8(1); // avcprofileindication var profilecompatibility = v.getuint8(2); // profile_compatibility var avclevel = v.getuint8(3); // avclevelindication if (version !== 1 || avcprofile === 0) { this._onerror(_demux_errors_js__webpack_imported_module_3__.default.format_error, 'flv: invalid avcdecoderconfigurationrecord'); return; } this._nalulengthsize = (v.getuint8(4) & 3) + 1; // lengthsizeminusone if (this._nalulengthsize !== 3 && this._nalulengthsize !== 4) { // holy shit!!! this._onerror(_demux_errors_js__webpack_imported_module_3__.default.format_error, "flv: strange nalulengthsizeminusone: " + (this._nalulengthsize - 1)); return; } var spscount = v.getuint8(5) & 31; // numofsequenceparametersets if (spscount === 0) { this._onerror(_demux_errors_js__webpack_imported_module_3__.default.format_error, 'flv: invalid avcdecoderconfigurationrecord: no sps'); return; } else if (spscount > 1) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, "flv: strange avcdecoderconfigurationrecord: sps count = " + spscount); } var offset = 6; for (var i = 0; i < spscount; i++) { var len = v.getuint16(offset, !le); // sequenceparametersetlength offset += 2; if (len === 0) { continue; } // notice: nalu without startcode header (00 00 00 01) var sps = new uint8array(arraybuffer, dataoffset + offset, len); offset += len; var config = _sps_parser_js__webpack_imported_module_2__.default.parsesps(sps); if (i !== 0) { // ignore other sps's config continue; } meta.codecwidth = config.codec_size.width; meta.codecheight = config.codec_size.height; meta.presentwidth = config.present_size.width; meta.presentheight = config.present_size.height; meta.profile = config.profile_string; meta.level = config.level_string; meta.bitdepth = config.bit_depth; meta.chromaformat = config.chroma_format; meta.sarratio = config.sar_ratio; meta.framerate = config.frame_rate; if (config.frame_rate.fixed === false || config.frame_rate.fps_num === 0 || config.frame_rate.fps_den === 0) { meta.framerate = this._referenceframerate; } var fps_den = meta.framerate.fps_den; var fps_num = meta.framerate.fps_num; meta.refsampleduration = meta.timescale * (fps_den / fps_num); var codecarray = sps.subarray(1, 4); var codecstring = 'avc1.'; for (var j = 0; j < 3; j++) { var h = codecarray[j].tostring(16); if (h.length < 2) { h = '0' + h; } codecstring += h; } meta.codec = codecstring; var mi = this._mediainfo; mi.width = meta.codecwidth; mi.height = meta.codecheight; mi.fps = meta.framerate.fps; mi.profile = meta.profile; mi.level = meta.level; mi.refframes = config.ref_frames; mi.chromaformat = config.chroma_format_string; mi.sarnum = meta.sarratio.width; mi.sarden = meta.sarratio.height; mi.videocodec = codecstring; if (mi.hasaudio) { if (mi.audiocodec != null) { mi.mimetype = 'video/x-flv; codecs="' + mi.videocodec + ',' + mi.audiocodec + '"'; } } else { mi.mimetype = 'video/x-flv; codecs="' + mi.videocodec + '"'; } if (mi.iscomplete()) { this._onmediainfo(mi); } } var ppscount = v.getuint8(offset); // numofpictureparametersets if (ppscount === 0) { this._onerror(_demux_errors_js__webpack_imported_module_3__.default.format_error, 'flv: invalid avcdecoderconfigurationrecord: no pps'); return; } else if (ppscount > 1) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, "flv: strange avcdecoderconfigurationrecord: pps count = " + ppscount); } offset++; for (var i = 0; i < ppscount; i++) { var len = v.getuint16(offset, !le); // pictureparametersetlength offset += 2; if (len === 0) { continue; } // pps is useless for extracting video information offset += len; } meta.avcc = new uint8array(datasize); meta.avcc.set(new uint8array(arraybuffer, dataoffset, datasize), 0); _utils_logger_js__webpack_imported_module_0__.default.v(this.tag, 'parsed avcdecoderconfigurationrecord'); if (this._isinitialmetadatadispatched()) { // flush parsed frames if (this._dispatch && (this._audiotrack.length || this._videotrack.length)) { this._ondataavailable(this._audiotrack, this._videotrack); } } else { this._videoinitialmetadatadispatched = true; } // notify new metadata this._dispatch = false; this._ontrackmetadata('video', meta); }; flvdemuxer.prototype._parseavcvideodata = function (arraybuffer, dataoffset, datasize, tagtimestamp, tagposition, frametype, cts) { var le = this._littleendian; var v = new dataview(arraybuffer, dataoffset, datasize); var units = [], length = 0; var offset = 0; var lengthsize = this._nalulengthsize; var dts = this._timestampbase + tagtimestamp; var keyframe = (frametype === 1); // from flv frame type constants while (offset < datasize) { if (offset + 4 >= datasize) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, "malformed nalu near timestamp " + dts + ", offset = " + offset + ", datasize = " + datasize); break; // data not enough for next nalu } // nalu with length-header (avc1) var nalusize = v.getuint32(offset, !le); // big-endian read if (lengthsize === 3) { nalusize >>>= 8; } if (nalusize > datasize - lengthsize) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, "malformed nalus near timestamp " + dts + ", nalusize > datasize!"); return; } var unittype = v.getuint8(offset + lengthsize) & 0x1f; if (unittype === 5) { // idr keyframe = true; } var data = new uint8array(arraybuffer, dataoffset + offset, lengthsize + nalusize); var unit = { type: unittype, data: data }; units.push(unit); length += data.bytelength; offset += lengthsize + nalusize; } if (units.length) { var track = this._videotrack; var avcsample = { units: units, length: length, iskeyframe: keyframe, dts: dts, cts: cts, pts: (dts + cts) }; if (keyframe) { avcsample.fileposition = tagposition; } track.samples.push(avcsample); track.length += length; } }; return flvdemuxer; }()); /* harmony default export */ __webpack_exports__["default"] = (flvdemuxer); /***/ }), /***/ "./src/demux/sps-parser.js": /*!*********************************!*\ !*** ./src/demux/sps-parser.js ***! \*********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _exp_golomb_js__webpack_imported_module_0__ = __webpack_require__(/*! ./exp-golomb.js */ "./src/demux/exp-golomb.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var spsparser = /** @class */ (function () { function spsparser() { } spsparser._ebsp2rbsp = function (uint8array) { var src = uint8array; var src_length = src.bytelength; var dst = new uint8array(src_length); var dst_idx = 0; for (var i = 0; i < src_length; i++) { if (i >= 2) { // unescape: skip 0x03 after 00 00 if (src[i] === 0x03 && src[i - 1] === 0x00 && src[i - 2] === 0x00) { continue; } } dst[dst_idx] = src[i]; dst_idx++; } return new uint8array(dst.buffer, 0, dst_idx); }; spsparser.parsesps = function (uint8array) { var rbsp = spsparser._ebsp2rbsp(uint8array); var gb = new _exp_golomb_js__webpack_imported_module_0__.default(rbsp); gb.readbyte(); var profile_idc = gb.readbyte(); // profile_idc gb.readbyte(); // constraint_set_flags[5] + reserved_zero[3] var level_idc = gb.readbyte(); // level_idc gb.readueg(); // seq_parameter_set_id var profile_string = spsparser.getprofilestring(profile_idc); var level_string = spsparser.getlevelstring(level_idc); var chroma_format_idc = 1; var chroma_format = 420; var chroma_format_table = [0, 420, 422, 444]; var bit_depth = 8; if (profile_idc === 100 || profile_idc === 110 || profile_idc === 122 || profile_idc === 244 || profile_idc === 44 || profile_idc === 83 || profile_idc === 86 || profile_idc === 118 || profile_idc === 128 || profile_idc === 138 || profile_idc === 144) { chroma_format_idc = gb.readueg(); if (chroma_format_idc === 3) { gb.readbits(1); // separate_colour_plane_flag } if (chroma_format_idc <= 3) { chroma_format = chroma_format_table[chroma_format_idc]; } bit_depth = gb.readueg() + 8; // bit_depth_luma_minus8 gb.readueg(); // bit_depth_chroma_minus8 gb.readbits(1); // qpprime_y_zero_transform_bypass_flag if (gb.readbool()) { // seq_scaling_matrix_present_flag var scaling_list_count = (chroma_format_idc !== 3) ? 8 : 12; for (var i = 0; i < scaling_list_count; i++) { if (gb.readbool()) { // seq_scaling_list_present_flag if (i < 6) { spsparser._skipscalinglist(gb, 16); } else { spsparser._skipscalinglist(gb, 64); } } } } } gb.readueg(); // log2_max_frame_num_minus4 var pic_order_cnt_type = gb.readueg(); if (pic_order_cnt_type === 0) { gb.readueg(); // log2_max_pic_order_cnt_lsb_minus_4 } else if (pic_order_cnt_type === 1) { gb.readbits(1); // delta_pic_order_always_zero_flag gb.readseg(); // offset_for_non_ref_pic gb.readseg(); // offset_for_top_to_bottom_field var num_ref_frames_in_pic_order_cnt_cycle = gb.readueg(); for (var i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++) { gb.readseg(); // offset_for_ref_frame } } var ref_frames = gb.readueg(); // max_num_ref_frames gb.readbits(1); // gaps_in_frame_num_value_allowed_flag var pic_width_in_mbs_minus1 = gb.readueg(); var pic_height_in_map_units_minus1 = gb.readueg(); var frame_mbs_only_flag = gb.readbits(1); if (frame_mbs_only_flag === 0) { gb.readbits(1); // mb_adaptive_frame_field_flag } gb.readbits(1); // direct_8x8_inference_flag var frame_crop_left_offset = 0; var frame_crop_right_offset = 0; var frame_crop_top_offset = 0; var frame_crop_bottom_offset = 0; var frame_cropping_flag = gb.readbool(); if (frame_cropping_flag) { frame_crop_left_offset = gb.readueg(); frame_crop_right_offset = gb.readueg(); frame_crop_top_offset = gb.readueg(); frame_crop_bottom_offset = gb.readueg(); } var sar_width = 1, sar_height = 1; var fps = 0, fps_fixed = true, fps_num = 0, fps_den = 0; var vui_parameters_present_flag = gb.readbool(); if (vui_parameters_present_flag) { if (gb.readbool()) { // aspect_ratio_info_present_flag var aspect_ratio_idc = gb.readbyte(); var sar_w_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2]; var sar_h_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1]; if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) { sar_width = sar_w_table[aspect_ratio_idc - 1]; sar_height = sar_h_table[aspect_ratio_idc - 1]; } else if (aspect_ratio_idc === 255) { sar_width = gb.readbyte() << 8 | gb.readbyte(); sar_height = gb.readbyte() << 8 | gb.readbyte(); } } if (gb.readbool()) { // overscan_info_present_flag gb.readbool(); // overscan_appropriate_flag } if (gb.readbool()) { // video_signal_type_present_flag gb.readbits(4); // video_format & video_full_range_flag if (gb.readbool()) { // colour_description_present_flag gb.readbits(24); // colour_primaries & transfer_characteristics & matrix_coefficients } } if (gb.readbool()) { // chroma_loc_info_present_flag gb.readueg(); // chroma_sample_loc_type_top_field gb.readueg(); // chroma_sample_loc_type_bottom_field } if (gb.readbool()) { // timing_info_present_flag var num_units_in_tick = gb.readbits(32); var time_scale = gb.readbits(32); fps_fixed = gb.readbool(); // fixed_frame_rate_flag fps_num = time_scale; fps_den = num_units_in_tick * 2; fps = fps_num / fps_den; } } var sarscale = 1; if (sar_width !== 1 || sar_height !== 1) { sarscale = sar_width / sar_height; } var crop_unit_x = 0, crop_unit_y = 0; if (chroma_format_idc === 0) { crop_unit_x = 1; crop_unit_y = 2 - frame_mbs_only_flag; } else { var sub_wc = (chroma_format_idc === 3) ? 1 : 2; var sub_hc = (chroma_format_idc === 1) ? 2 : 1; crop_unit_x = sub_wc; crop_unit_y = sub_hc * (2 - frame_mbs_only_flag); } var codec_width = (pic_width_in_mbs_minus1 + 1) * 16; var codec_height = (2 - frame_mbs_only_flag) * ((pic_height_in_map_units_minus1 + 1) * 16); codec_width -= (frame_crop_left_offset + frame_crop_right_offset) * crop_unit_x; codec_height -= (frame_crop_top_offset + frame_crop_bottom_offset) * crop_unit_y; var present_width = math.ceil(codec_width * sarscale); gb.destroy(); gb = null; return { profile_string: profile_string, level_string: level_string, bit_depth: bit_depth, ref_frames: ref_frames, chroma_format: chroma_format, chroma_format_string: spsparser.getchromaformatstring(chroma_format), frame_rate: { fixed: fps_fixed, fps: fps, fps_den: fps_den, fps_num: fps_num }, sar_ratio: { width: sar_width, height: sar_height }, codec_size: { width: codec_width, height: codec_height }, present_size: { width: present_width, height: codec_height } }; }; spsparser._skipscalinglist = function (gb, count) { var last_scale = 8, next_scale = 8; var delta_scale = 0; for (var i = 0; i < count; i++) { if (next_scale !== 0) { delta_scale = gb.readseg(); next_scale = (last_scale + delta_scale + 256) % 256; } last_scale = (next_scale === 0) ? last_scale : next_scale; } }; spsparser.getprofilestring = function (profile_idc) { switch (profile_idc) { case 66: return 'baseline'; case 77: return 'main'; case 88: return 'extended'; case 100: return 'high'; case 110: return 'high10'; case 122: return 'high422'; case 244: return 'high444'; default: return 'unknown'; } }; spsparser.getlevelstring = function (level_idc) { return (level_idc / 10).tofixed(1); }; spsparser.getchromaformatstring = function (chroma) { switch (chroma) { case 420: return '4:2:0'; case 422: return '4:2:2'; case 444: return '4:4:4'; default: return 'unknown'; } }; return spsparser; }()); /* harmony default export */ __webpack_exports__["default"] = (spsparser); /***/ }), /***/ "./src/flv.js": /*!********************!*\ !*** ./src/flv.js ***! \********************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_polyfill_js__webpack_imported_module_0__ = __webpack_require__(/*! ./utils/polyfill.js */ "./src/utils/polyfill.js"); /* harmony import */ var _core_features_js__webpack_imported_module_1__ = __webpack_require__(/*! ./core/features.js */ "./src/core/features.js"); /* harmony import */ var _io_loader_js__webpack_imported_module_2__ = __webpack_require__(/*! ./io/loader.js */ "./src/io/loader.js"); /* harmony import */ var _player_flv_player_js__webpack_imported_module_3__ = __webpack_require__(/*! ./player/flv-player.js */ "./src/player/flv-player.js"); /* harmony import */ var _player_native_player_js__webpack_imported_module_4__ = __webpack_require__(/*! ./player/native-player.js */ "./src/player/native-player.js"); /* harmony import */ var _player_player_events_js__webpack_imported_module_5__ = __webpack_require__(/*! ./player/player-events.js */ "./src/player/player-events.js"); /* harmony import */ var _player_player_errors_js__webpack_imported_module_6__ = __webpack_require__(/*! ./player/player-errors.js */ "./src/player/player-errors.js"); /* harmony import */ var _utils_logging_control_js__webpack_imported_module_7__ = __webpack_require__(/*! ./utils/logging-control.js */ "./src/utils/logging-control.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_8__ = __webpack_require__(/*! ./utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ // here are all the interfaces // install polyfills _utils_polyfill_js__webpack_imported_module_0__.default.install(); // factory method function createplayer(mediadatasource, optionalconfig) { var mds = mediadatasource; if (mds == null || typeof mds !== 'object') { throw new _utils_exception_js__webpack_imported_module_8__.invalidargumentexception('mediadatasource must be an javascript object!'); } if (!mds.hasownproperty('type')) { throw new _utils_exception_js__webpack_imported_module_8__.invalidargumentexception('mediadatasource must has type field to indicate video file type!'); } switch (mds.type) { case 'flv': return new _player_flv_player_js__webpack_imported_module_3__.default(mds, optionalconfig); default: return new _player_native_player_js__webpack_imported_module_4__.default(mds, optionalconfig); } } // feature detection function issupported() { return _core_features_js__webpack_imported_module_1__.default.supportmseh264playback(); } function getfeaturelist() { return _core_features_js__webpack_imported_module_1__.default.getfeaturelist(); } // interfaces var flvjs = {}; flvjs.createplayer = createplayer; flvjs.issupported = issupported; flvjs.getfeaturelist = getfeaturelist; flvjs.baseloader = _io_loader_js__webpack_imported_module_2__.baseloader; flvjs.loaderstatus = _io_loader_js__webpack_imported_module_2__.loaderstatus; flvjs.loadererrors = _io_loader_js__webpack_imported_module_2__.loadererrors; flvjs.events = _player_player_events_js__webpack_imported_module_5__.default; flvjs.errortypes = _player_player_errors_js__webpack_imported_module_6__.errortypes; flvjs.errordetails = _player_player_errors_js__webpack_imported_module_6__.errordetails; flvjs.flvplayer = _player_flv_player_js__webpack_imported_module_3__.default; flvjs.nativeplayer = _player_native_player_js__webpack_imported_module_4__.default; flvjs.loggingcontrol = _utils_logging_control_js__webpack_imported_module_7__.default; object.defineproperty(flvjs, 'version', { enumerable: true, get: function () { // replace by webpack.defineplugin return "1.6.2"; } }); /* harmony default export */ __webpack_exports__["default"] = (flvjs); /***/ }), /***/ "./src/index.js": /*!**********************!*\ !*** ./src/index.js ***! \**********************/ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { // entry/index file // make it compatible with browserify's umd wrapper module.exports = __webpack_require__(/*! ./flv.js */ "./src/flv.js").default; /***/ }), /***/ "./src/io/fetch-stream-loader.js": /*!***************************************!*\ !*** ./src/io/fetch-stream-loader.js ***! \***************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_browser_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/browser.js */ "./src/utils/browser.js"); /* harmony import */ var _loader_js__webpack_imported_module_1__ = __webpack_require__(/*! ./loader.js */ "./src/io/loader.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_2__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var __extends = (undefined && undefined.__extends) || (function () { var extendstatics = function (d, b) { extendstatics = object.setprototypeof || ({ __proto__: [] } instanceof array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (object.prototype.hasownproperty.call(b, p)) d[p] = b[p]; }; return extendstatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new typeerror("class extends value " + string(b) + " is not a constructor or null"); extendstatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /* fetch + stream io loader. currently working on chrome 43+. * fetch provides a better alternative http api to xmlhttprequest * * fetch spec https://fetch.spec.whatwg.org/ * stream spec https://streams.spec.whatwg.org/ */ var fetchstreamloader = /** @class */ (function (_super) { __extends(fetchstreamloader, _super); function fetchstreamloader(seekhandler, config) { var _this = _super.call(this, 'fetch-stream-loader') || this; _this.tag = 'fetchstreamloader'; _this._seekhandler = seekhandler; _this._config = config; _this._needstash = true; _this._requestabort = false; _this._contentlength = null; _this._receivedlength = 0; return _this; } fetchstreamloader.issupported = function () { try { // fetch + stream is broken on microsoft edge. disable before build 15048. // see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8196907/ // fixed in jan 10, 2017. build 15048+ removed from blacklist. var isworkwelledge = _utils_browser_js__webpack_imported_module_0__.default.msedge && _utils_browser_js__webpack_imported_module_0__.default.version.minor >= 15048; var browsernotblacklisted = _utils_browser_js__webpack_imported_module_0__.default.msedge ? isworkwelledge : true; return (self.fetch && self.readablestream && browsernotblacklisted); } catch (e) { return false; } }; fetchstreamloader.prototype.destroy = function () { if (this.isworking()) { this.abort(); } _super.prototype.destroy.call(this); }; fetchstreamloader.prototype.open = function (datasource, range) { var _this = this; this._datasource = datasource; this._range = range; var sourceurl = datasource.url; if (this._config.reuseredirectedurl && datasource.redirectedurl != undefined) { sourceurl = datasource.redirectedurl; } var seekconfig = this._seekhandler.getconfig(sourceurl, range); var headers = new self.headers(); if (typeof seekconfig.headers === 'object') { var configheaders = seekconfig.headers; for (var key in configheaders) { if (configheaders.hasownproperty(key)) { headers.append(key, configheaders[key]); } } } var params = { method: 'get', headers: headers, mode: 'cors', cache: 'default', // the default policy of fetch api in the whatwg standard // safari incorrectly indicates 'no-referrer' as default policy, fuck it referrerpolicy: 'no-referrer-when-downgrade' }; // add additional headers if (typeof this._config.headers === 'object') { for (var key in this._config.headers) { headers.append(key, this._config.headers[key]); } } // cors is enabled by default if (datasource.cors === false) { // no-cors means 'disregard cors policy', which can only be used in serviceworker params.mode = 'same-origin'; } // withcredentials is disabled by default if (datasource.withcredentials) { params.credentials = 'include'; } // referrerpolicy from config if (datasource.referrerpolicy) { params.referrerpolicy = datasource.referrerpolicy; } // add abort controller, by wmlgl 2019-5-10 12:21:27 if (self.abortcontroller) { this._abortcontroller = new self.abortcontroller(); params.signal = this._abortcontroller.signal; } this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kconnecting; self.fetch(seekconfig.url, params).then(function (res) { if (_this._requestabort) { _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kidle; res.body.cancel(); return; } if (res.ok && (res.status >= 200 && res.status <= 299)) { if (res.url !== seekconfig.url) { if (_this._onurlredirect) { var redirectedurl = _this._seekhandler.removeurlparameters(res.url); _this._onurlredirect(redirectedurl); } } var lengthheader = res.headers.get('content-length'); if (lengthheader != null) { _this._contentlength = parseint(lengthheader); if (_this._contentlength !== 0) { if (_this._oncontentlengthknown) { _this._oncontentlengthknown(_this._contentlength); } } } return _this._pump.call(_this, res.body.getreader()); } else { _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kerror; if (_this._onerror) { _this._onerror(_loader_js__webpack_imported_module_1__.loadererrors.http_status_code_invalid, { code: res.status, msg: res.statustext }); } else { throw new _utils_exception_js__webpack_imported_module_2__.runtimeexception('fetchstreamloader: http code invalid, ' + res.status + ' ' + res.statustext); } } }).catch(function (e) { if (_this._abortcontroller && _this._abortcontroller.signal.aborted) { return; } _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kerror; if (_this._onerror) { _this._onerror(_loader_js__webpack_imported_module_1__.loadererrors.exception, { code: -1, msg: e.message }); } else { throw e; } }); }; fetchstreamloader.prototype.abort = function () { this._requestabort = true; if (this._status !== _loader_js__webpack_imported_module_1__.loaderstatus.kbuffering || !_utils_browser_js__webpack_imported_module_0__.default.chrome) { // chrome may throw exception-like things here, avoid using if is buffering if (this._abortcontroller) { try { this._abortcontroller.abort(); } catch (e) { } } } }; fetchstreamloader.prototype._pump = function (reader) { var _this = this; return reader.read().then(function (result) { if (result.done) { // first check received length if (_this._contentlength !== null && _this._receivedlength < _this._contentlength) { // report early-eof _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kerror; var type = _loader_js__webpack_imported_module_1__.loadererrors.early_eof; var info = { code: -1, msg: 'fetch stream meet early-eof' }; if (_this._onerror) { _this._onerror(type, info); } else { throw new _utils_exception_js__webpack_imported_module_2__.runtimeexception(info.msg); } } else { // ok. download complete _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kcomplete; if (_this._oncomplete) { _this._oncomplete(_this._range.from, _this._range.from + _this._receivedlength - 1); } } } else { if (_this._abortcontroller && _this._abortcontroller.signal.aborted) { _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kcomplete; return; } else if (_this._requestabort === true) { _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kcomplete; return reader.cancel(); } _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kbuffering; var chunk = result.value.buffer; var bytestart = _this._range.from + _this._receivedlength; _this._receivedlength += chunk.bytelength; if (_this._ondataarrival) { _this._ondataarrival(chunk, bytestart, _this._receivedlength); } _this._pump(reader); } }).catch(function (e) { if (_this._abortcontroller && _this._abortcontroller.signal.aborted) { _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kcomplete; return; } if (e.code === 11 && _utils_browser_js__webpack_imported_module_0__.default.msedge) { // invalidstateerror on microsoft edge // workaround: edge may throw invalidstateerror after readablestreamreader.cancel() call // ignore the unknown exception. // related issue: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11265202/ return; } _this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kerror; var type = 0; var info = null; if ((e.code === 19 || e.message === 'network error') && // network_err (_this._contentlength === null || (_this._contentlength !== null && _this._receivedlength < _this._contentlength))) { type = _loader_js__webpack_imported_module_1__.loadererrors.early_eof; info = { code: e.code, msg: 'fetch stream meet early-eof' }; } else { type = _loader_js__webpack_imported_module_1__.loadererrors.exception; info = { code: e.code, msg: e.message }; } if (_this._onerror) { _this._onerror(type, info); } else { throw new _utils_exception_js__webpack_imported_module_2__.runtimeexception(info.msg); } }); }; return fetchstreamloader; }(_loader_js__webpack_imported_module_1__.baseloader)); /* harmony default export */ __webpack_exports__["default"] = (fetchstreamloader); /***/ }), /***/ "./src/io/io-controller.js": /*!*********************************!*\ !*** ./src/io/io-controller.js ***! \*********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _speed_sampler_js__webpack_imported_module_1__ = __webpack_require__(/*! ./speed-sampler.js */ "./src/io/speed-sampler.js"); /* harmony import */ var _loader_js__webpack_imported_module_2__ = __webpack_require__(/*! ./loader.js */ "./src/io/loader.js"); /* harmony import */ var _fetch_stream_loader_js__webpack_imported_module_3__ = __webpack_require__(/*! ./fetch-stream-loader.js */ "./src/io/fetch-stream-loader.js"); /* harmony import */ var _xhr_moz_chunked_loader_js__webpack_imported_module_4__ = __webpack_require__(/*! ./xhr-moz-chunked-loader.js */ "./src/io/xhr-moz-chunked-loader.js"); /* harmony import */ var _xhr_range_loader_js__webpack_imported_module_5__ = __webpack_require__(/*! ./xhr-range-loader.js */ "./src/io/xhr-range-loader.js"); /* harmony import */ var _websocket_loader_js__webpack_imported_module_6__ = __webpack_require__(/*! ./websocket-loader.js */ "./src/io/websocket-loader.js"); /* harmony import */ var _range_seek_handler_js__webpack_imported_module_7__ = __webpack_require__(/*! ./range-seek-handler.js */ "./src/io/range-seek-handler.js"); /* harmony import */ var _param_seek_handler_js__webpack_imported_module_8__ = __webpack_require__(/*! ./param-seek-handler.js */ "./src/io/param-seek-handler.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_9__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ /** * datasource: { * url: string, * filesize: number, * cors: boolean, * withcredentials: boolean * } * */ // manage io loaders var iocontroller = /** @class */ (function () { function iocontroller(datasource, config, extradata) { this.tag = 'iocontroller'; this._config = config; this._extradata = extradata; this._stashinitialsize = 1024 * 384; // default initial size: 384kb if (config.stashinitialsize != undefined && config.stashinitialsize > 0) { // apply from config this._stashinitialsize = config.stashinitialsize; } this._stashused = 0; this._stashsize = this._stashinitialsize; this._buffersize = 1024 * 1024 * 3; // initial size: 3mb this._stashbuffer = new arraybuffer(this._buffersize); this._stashbytestart = 0; this._enablestash = true; if (config.enablestashbuffer === false) { this._enablestash = false; } this._loader = null; this._loaderclass = null; this._seekhandler = null; this._datasource = datasource; this._iswebsocketurl = /wss?:\/\/(.+?)/.test(datasource.url); this._reftotallength = datasource.filesize ? datasource.filesize : null; this._totallength = this._reftotallength; this._fullrequestflag = false; this._currentrange = null; this._redirectedurl = null; this._speednormalized = 0; this._speedsampler = new _speed_sampler_js__webpack_imported_module_1__.default(); this._speednormalizelist = [64, 128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096]; this._isearlyeofreconnecting = false; this._paused = false; this._resumefrom = 0; this._ondataarrival = null; this._onseeked = null; this._onerror = null; this._oncomplete = null; this._onredirect = null; this._onrecoveredearlyeof = null; this._selectseekhandler(); this._selectloader(); this._createloader(); } iocontroller.prototype.destroy = function () { if (this._loader.isworking()) { this._loader.abort(); } this._loader.destroy(); this._loader = null; this._loaderclass = null; this._datasource = null; this._stashbuffer = null; this._stashused = this._stashsize = this._buffersize = this._stashbytestart = 0; this._currentrange = null; this._speedsampler = null; this._isearlyeofreconnecting = false; this._ondataarrival = null; this._onseeked = null; this._onerror = null; this._oncomplete = null; this._onredirect = null; this._onrecoveredearlyeof = null; this._extradata = null; }; iocontroller.prototype.isworking = function () { return this._loader && this._loader.isworking() && !this._paused; }; iocontroller.prototype.ispaused = function () { return this._paused; }; object.defineproperty(iocontroller.prototype, "status", { get: function () { return this._loader.status; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "extradata", { get: function () { return this._extradata; }, set: function (data) { this._extradata = data; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "ondataarrival", { // prototype: function ondataarrival(chunks: arraybuffer, bytestart: number): number get: function () { return this._ondataarrival; }, set: function (callback) { this._ondataarrival = callback; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "onseeked", { get: function () { return this._onseeked; }, set: function (callback) { this._onseeked = callback; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "onerror", { // prototype: function onerror(type: number, info: {code: number, msg: string}): void get: function () { return this._onerror; }, set: function (callback) { this._onerror = callback; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "oncomplete", { get: function () { return this._oncomplete; }, set: function (callback) { this._oncomplete = callback; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "onredirect", { get: function () { return this._onredirect; }, set: function (callback) { this._onredirect = callback; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "onrecoveredearlyeof", { get: function () { return this._onrecoveredearlyeof; }, set: function (callback) { this._onrecoveredearlyeof = callback; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "currenturl", { get: function () { return this._datasource.url; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "hasredirect", { get: function () { return (this._redirectedurl != null || this._datasource.redirectedurl != undefined); }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "currentredirectedurl", { get: function () { return this._redirectedurl || this._datasource.redirectedurl; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "currentspeed", { // in kb/s get: function () { if (this._loaderclass === _xhr_range_loader_js__webpack_imported_module_5__.default) { // speedsampler is inaccuracy if loader is rangeloader return this._loader.currentspeed; } return this._speedsampler.lastsecondkbps; }, enumerable: false, configurable: true }); object.defineproperty(iocontroller.prototype, "loadertype", { get: function () { return this._loader.type; }, enumerable: false, configurable: true }); iocontroller.prototype._selectseekhandler = function () { var config = this._config; if (config.seektype === 'range') { this._seekhandler = new _range_seek_handler_js__webpack_imported_module_7__.default(this._config.rangeloadzerostart); } else if (config.seektype === 'param') { var paramstart = config.seekparamstart || 'bstart'; var paramend = config.seekparamend || 'bend'; this._seekhandler = new _param_seek_handler_js__webpack_imported_module_8__.default(paramstart, paramend); } else if (config.seektype === 'custom') { if (typeof config.customseekhandler !== 'function') { throw new _utils_exception_js__webpack_imported_module_9__.invalidargumentexception('custom seektype specified in config but invalid customseekhandler!'); } this._seekhandler = new config.customseekhandler(); } else { throw new _utils_exception_js__webpack_imported_module_9__.invalidargumentexception("invalid seektype in config: " + config.seektype); } }; iocontroller.prototype._selectloader = function () { if (this._config.customloader != null) { this._loaderclass = this._config.customloader; } else if (this._iswebsocketurl) { this._loaderclass = _websocket_loader_js__webpack_imported_module_6__.default; } else if (_fetch_stream_loader_js__webpack_imported_module_3__.default.issupported()) { this._loaderclass = _fetch_stream_loader_js__webpack_imported_module_3__.default; } else if (_xhr_moz_chunked_loader_js__webpack_imported_module_4__.default.issupported()) { this._loaderclass = _xhr_moz_chunked_loader_js__webpack_imported_module_4__.default; } else if (_xhr_range_loader_js__webpack_imported_module_5__.default.issupported()) { this._loaderclass = _xhr_range_loader_js__webpack_imported_module_5__.default; } else { throw new _utils_exception_js__webpack_imported_module_9__.runtimeexception('your browser doesn\'t support xhr with arraybuffer responsetype!'); } }; iocontroller.prototype._createloader = function () { this._loader = new this._loaderclass(this._seekhandler, this._config); if (this._loader.needstashbuffer === false) { this._enablestash = false; } this._loader.oncontentlengthknown = this._oncontentlengthknown.bind(this); this._loader.onurlredirect = this._onurlredirect.bind(this); this._loader.ondataarrival = this._onloaderchunkarrival.bind(this); this._loader.oncomplete = this._onloadercomplete.bind(this); this._loader.onerror = this._onloadererror.bind(this); }; iocontroller.prototype.open = function (optionalfrom) { this._currentrange = { from: 0, to: -1 }; if (optionalfrom) { this._currentrange.from = optionalfrom; } this._speedsampler.reset(); if (!optionalfrom) { this._fullrequestflag = true; } this._loader.open(this._datasource, object.assign({}, this._currentrange)); }; iocontroller.prototype.abort = function () { this._loader.abort(); if (this._paused) { this._paused = false; this._resumefrom = 0; } }; iocontroller.prototype.pause = function () { if (this.isworking()) { this._loader.abort(); if (this._stashused !== 0) { this._resumefrom = this._stashbytestart; this._currentrange.to = this._stashbytestart - 1; } else { this._resumefrom = this._currentrange.to + 1; } this._stashused = 0; this._stashbytestart = 0; this._paused = true; } }; iocontroller.prototype.resume = function () { if (this._paused) { this._paused = false; var bytes = this._resumefrom; this._resumefrom = 0; this._internalseek(bytes, true); } }; iocontroller.prototype.seek = function (bytes) { this._paused = false; this._stashused = 0; this._stashbytestart = 0; this._internalseek(bytes, true); }; /** * when seeking request is from media seeking, unconsumed stash data should be dropped * however, stash data shouldn't be dropped if seeking requested from http reconnection * * @dropunconsumed: ignore and discard all unconsumed data in stash buffer */ iocontroller.prototype._internalseek = function (bytes, dropunconsumed) { if (this._loader.isworking()) { this._loader.abort(); } // dispatch & flush stash buffer before seek this._flushstashbuffer(dropunconsumed); this._loader.destroy(); this._loader = null; var requestrange = { from: bytes, to: -1 }; this._currentrange = { from: requestrange.from, to: -1 }; this._speedsampler.reset(); this._stashsize = this._stashinitialsize; this._createloader(); this._loader.open(this._datasource, requestrange); if (this._onseeked) { this._onseeked(); } }; iocontroller.prototype.updateurl = function (url) { if (!url || typeof url !== 'string' || url.length === 0) { throw new _utils_exception_js__webpack_imported_module_9__.invalidargumentexception('url must be a non-empty string!'); } this._datasource.url = url; // todo: replace with new url }; iocontroller.prototype._expandbuffer = function (expectedbytes) { var buffernewsize = this._stashsize; while (buffernewsize + 1024 * 1024 * 1 < expectedbytes) { buffernewsize *= 2; } buffernewsize += 1024 * 1024 * 1; // buffersize = stashsize + 1mb if (buffernewsize === this._buffersize) { return; } var newbuffer = new arraybuffer(buffernewsize); if (this._stashused > 0) { // copy existing data into new buffer var stasholdarray = new uint8array(this._stashbuffer, 0, this._stashused); var stashnewarray = new uint8array(newbuffer, 0, buffernewsize); stashnewarray.set(stasholdarray, 0); } this._stashbuffer = newbuffer; this._buffersize = buffernewsize; }; iocontroller.prototype._normalizespeed = function (input) { var list = this._speednormalizelist; var last = list.length - 1; var mid = 0; var lbound = 0; var ubound = last; if (input < list[0]) { return list[0]; } // binary search while (lbound <= ubound) { mid = lbound + math.floor((ubound - lbound) / 2); if (mid === last || (input >= list[mid] && input < list[mid + 1])) { return list[mid]; } else if (list[mid] < input) { lbound = mid + 1; } else { ubound = mid - 1; } } }; iocontroller.prototype._adjuststashsize = function (normalized) { var stashsizekb = 0; if (this._config.islive) { // live stream: always use single normalized speed for size of stashsizekb stashsizekb = normalized; } else { if (normalized < 512) { stashsizekb = normalized; } else if (normalized >= 512 && normalized <= 1024) { stashsizekb = math.floor(normalized * 1.5); } else { stashsizekb = normalized * 2; } } if (stashsizekb > 8192) { stashsizekb = 8192; } var buffersize = stashsizekb * 1024 + 1024 * 1024 * 1; // stashsize + 1mb if (this._buffersize < buffersize) { this._expandbuffer(buffersize); } this._stashsize = stashsizekb * 1024; }; iocontroller.prototype._dispatchchunks = function (chunks, bytestart) { this._currentrange.to = bytestart + chunks.bytelength - 1; return this._ondataarrival(chunks, bytestart); }; iocontroller.prototype._onurlredirect = function (redirectedurl) { this._redirectedurl = redirectedurl; if (this._onredirect) { this._onredirect(redirectedurl); } }; iocontroller.prototype._oncontentlengthknown = function (contentlength) { if (contentlength && this._fullrequestflag) { this._totallength = contentlength; this._fullrequestflag = false; } }; iocontroller.prototype._onloaderchunkarrival = function (chunk, bytestart, receivedlength) { if (!this._ondataarrival) { throw new _utils_exception_js__webpack_imported_module_9__.illegalstateexception('iocontroller: no existing consumer (ondataarrival) callback!'); } if (this._paused) { return; } if (this._isearlyeofreconnecting) { // auto-reconnect for earlyeof succeed, notify to upper-layer by callback this._isearlyeofreconnecting = false; if (this._onrecoveredearlyeof) { this._onrecoveredearlyeof(); } } this._speedsampler.addbytes(chunk.bytelength); // adjust stash buffer size according to network speed dynamically var kbps = this._speedsampler.lastsecondkbps; if (kbps !== 0) { var normalized = this._normalizespeed(kbps); if (this._speednormalized !== normalized) { this._speednormalized = normalized; this._adjuststashsize(normalized); } } if (!this._enablestash) { // disable stash if (this._stashused === 0) { // dispatch chunk directly to consumer; // check ret value (consumed bytes) and stash unconsumed to stashbuffer var consumed = this._dispatchchunks(chunk, bytestart); if (consumed < chunk.bytelength) { // unconsumed data remain. var remain = chunk.bytelength - consumed; if (remain > this._buffersize) { this._expandbuffer(remain); } var stasharray = new uint8array(this._stashbuffer, 0, this._buffersize); stasharray.set(new uint8array(chunk, consumed), 0); this._stashused += remain; this._stashbytestart = bytestart + consumed; } } else { // else: merge chunk into stashbuffer, and dispatch stashbuffer to consumer. if (this._stashused + chunk.bytelength > this._buffersize) { this._expandbuffer(this._stashused + chunk.bytelength); } var stasharray = new uint8array(this._stashbuffer, 0, this._buffersize); stasharray.set(new uint8array(chunk), this._stashused); this._stashused += chunk.bytelength; var consumed = this._dispatchchunks(this._stashbuffer.slice(0, this._stashused), this._stashbytestart); if (consumed < this._stashused && consumed > 0) { // unconsumed data remain var remainarray = new uint8array(this._stashbuffer, consumed); stasharray.set(remainarray, 0); } this._stashused -= consumed; this._stashbytestart += consumed; } } else { // enable stash if (this._stashused === 0 && this._stashbytestart === 0) { // seeked? or init chunk? // this is the first chunk after seek action this._stashbytestart = bytestart; } if (this._stashused + chunk.bytelength <= this._stashsize) { // just stash var stasharray = new uint8array(this._stashbuffer, 0, this._stashsize); stasharray.set(new uint8array(chunk), this._stashused); this._stashused += chunk.bytelength; } else { // stashused + chunksize > stashsize, size limit exceeded var stasharray = new uint8array(this._stashbuffer, 0, this._buffersize); if (this._stashused > 0) { // there're stash datas in buffer // dispatch the whole stashbuffer, and stash remain data // then append chunk to stashbuffer (stash) var buffer = this._stashbuffer.slice(0, this._stashused); var consumed = this._dispatchchunks(buffer, this._stashbytestart); if (consumed < buffer.bytelength) { if (consumed > 0) { var remainarray = new uint8array(buffer, consumed); stasharray.set(remainarray, 0); this._stashused = remainarray.bytelength; this._stashbytestart += consumed; } } else { this._stashused = 0; this._stashbytestart += consumed; } if (this._stashused + chunk.bytelength > this._buffersize) { this._expandbuffer(this._stashused + chunk.bytelength); stasharray = new uint8array(this._stashbuffer, 0, this._buffersize); } stasharray.set(new uint8array(chunk), this._stashused); this._stashused += chunk.bytelength; } else { // stash buffer empty, but chunksize > stashsize (oh, holy shit) // dispatch chunk directly and stash remain data var consumed = this._dispatchchunks(chunk, bytestart); if (consumed < chunk.bytelength) { var remain = chunk.bytelength - consumed; if (remain > this._buffersize) { this._expandbuffer(remain); stasharray = new uint8array(this._stashbuffer, 0, this._buffersize); } stasharray.set(new uint8array(chunk, consumed), 0); this._stashused += remain; this._stashbytestart = bytestart + consumed; } } } } }; iocontroller.prototype._flushstashbuffer = function (dropunconsumed) { if (this._stashused > 0) { var buffer = this._stashbuffer.slice(0, this._stashused); var consumed = this._dispatchchunks(buffer, this._stashbytestart); var remain = buffer.bytelength - consumed; if (consumed < buffer.bytelength) { if (dropunconsumed) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, remain + " bytes unconsumed data remain when flush buffer, dropped"); } else { if (consumed > 0) { var stasharray = new uint8array(this._stashbuffer, 0, this._buffersize); var remainarray = new uint8array(buffer, consumed); stasharray.set(remainarray, 0); this._stashused = remainarray.bytelength; this._stashbytestart += consumed; } return 0; } } this._stashused = 0; this._stashbytestart = 0; return remain; } return 0; }; iocontroller.prototype._onloadercomplete = function (from, to) { // force-flush stash buffer, and drop unconsumed data this._flushstashbuffer(true); if (this._oncomplete) { this._oncomplete(this._extradata); } }; iocontroller.prototype._onloadererror = function (type, data) { _utils_logger_js__webpack_imported_module_0__.default.e(this.tag, "loader error, code = " + data.code + ", msg = " + data.msg); this._flushstashbuffer(false); if (this._isearlyeofreconnecting) { // auto-reconnect for earlyeof failed, throw unrecoverableearlyeof error to upper-layer this._isearlyeofreconnecting = false; type = _loader_js__webpack_imported_module_2__.loadererrors.unrecoverable_early_eof; } switch (type) { case _loader_js__webpack_imported_module_2__.loadererrors.early_eof: { if (!this._config.islive) { // do internal http reconnect if not live stream if (this._totallength) { var nextfrom = this._currentrange.to + 1; if (nextfrom < this._totallength) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'connection lost, trying reconnect...'); this._isearlyeofreconnecting = true; this._internalseek(nextfrom, false); } return; } // else: we don't know totallength, throw unrecoverableearlyeof } // live stream: throw unrecoverableearlyeof error to upper-layer type = _loader_js__webpack_imported_module_2__.loadererrors.unrecoverable_early_eof; break; } case _loader_js__webpack_imported_module_2__.loadererrors.unrecoverable_early_eof: case _loader_js__webpack_imported_module_2__.loadererrors.connecting_timeout: case _loader_js__webpack_imported_module_2__.loadererrors.http_status_code_invalid: case _loader_js__webpack_imported_module_2__.loadererrors.exception: break; } if (this._onerror) { this._onerror(type, data); } else { throw new _utils_exception_js__webpack_imported_module_9__.runtimeexception('ioexception: ' + data.msg); } }; return iocontroller; }()); /* harmony default export */ __webpack_exports__["default"] = (iocontroller); /***/ }), /***/ "./src/io/loader.js": /*!**************************!*\ !*** ./src/io/loader.js ***! \**************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "loaderstatus": function() { return /* binding */ loaderstatus; }, /* harmony export */ "loadererrors": function() { return /* binding */ loadererrors; }, /* harmony export */ "baseloader": function() { return /* binding */ baseloader; } /* harmony export */ }); /* harmony import */ var _utils_exception_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var loaderstatus = { kidle: 0, kconnecting: 1, kbuffering: 2, kerror: 3, kcomplete: 4 }; var loadererrors = { ok: 'ok', exception: 'exception', http_status_code_invalid: 'httpstatuscodeinvalid', connecting_timeout: 'connectingtimeout', early_eof: 'earlyeof', unrecoverable_early_eof: 'unrecoverableearlyeof' }; /* loader has callbacks which have following prototypes: * function oncontentlengthknown(contentlength: number): void * function onurlredirect(url: string): void * function ondataarrival(chunk: arraybuffer, bytestart: number, receivedlength: number): void * function onerror(errortype: number, errorinfo: {code: number, msg: string}): void * function oncomplete(rangefrom: number, rangeto: number): void */ var baseloader = /** @class */ (function () { function baseloader(typename) { this._type = typename || 'undefined'; this._status = loaderstatus.kidle; this._needstash = false; // callbacks this._oncontentlengthknown = null; this._onurlredirect = null; this._ondataarrival = null; this._onerror = null; this._oncomplete = null; } baseloader.prototype.destroy = function () { this._status = loaderstatus.kidle; this._oncontentlengthknown = null; this._onurlredirect = null; this._ondataarrival = null; this._onerror = null; this._oncomplete = null; }; baseloader.prototype.isworking = function () { return this._status === loaderstatus.kconnecting || this._status === loaderstatus.kbuffering; }; object.defineproperty(baseloader.prototype, "type", { get: function () { return this._type; }, enumerable: false, configurable: true }); object.defineproperty(baseloader.prototype, "status", { get: function () { return this._status; }, enumerable: false, configurable: true }); object.defineproperty(baseloader.prototype, "needstashbuffer", { get: function () { return this._needstash; }, enumerable: false, configurable: true }); object.defineproperty(baseloader.prototype, "oncontentlengthknown", { get: function () { return this._oncontentlengthknown; }, set: function (callback) { this._oncontentlengthknown = callback; }, enumerable: false, configurable: true }); object.defineproperty(baseloader.prototype, "onurlredirect", { get: function () { return this._onurlredirect; }, set: function (callback) { this._onurlredirect = callback; }, enumerable: false, configurable: true }); object.defineproperty(baseloader.prototype, "ondataarrival", { get: function () { return this._ondataarrival; }, set: function (callback) { this._ondataarrival = callback; }, enumerable: false, configurable: true }); object.defineproperty(baseloader.prototype, "onerror", { get: function () { return this._onerror; }, set: function (callback) { this._onerror = callback; }, enumerable: false, configurable: true }); object.defineproperty(baseloader.prototype, "oncomplete", { get: function () { return this._oncomplete; }, set: function (callback) { this._oncomplete = callback; }, enumerable: false, configurable: true }); // pure virtual baseloader.prototype.open = function (datasource, range) { throw new _utils_exception_js__webpack_imported_module_0__.notimplementedexception('unimplemented abstract function!'); }; baseloader.prototype.abort = function () { throw new _utils_exception_js__webpack_imported_module_0__.notimplementedexception('unimplemented abstract function!'); }; return baseloader; }()); /***/ }), /***/ "./src/io/param-seek-handler.js": /*!**************************************!*\ !*** ./src/io/param-seek-handler.js ***! \**************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var paramseekhandler = /** @class */ (function () { function paramseekhandler(paramstart, paramend) { this._startname = paramstart; this._endname = paramend; } paramseekhandler.prototype.getconfig = function (baseurl, range) { var url = baseurl; if (range.from !== 0 || range.to !== -1) { var needand = true; if (url.indexof('?') === -1) { url += '?'; needand = false; } if (needand) { url += '&'; } url += this._startname + "=" + range.from.tostring(); if (range.to !== -1) { url += "&" + this._endname + "=" + range.to.tostring(); } } return { url: url, headers: {} }; }; paramseekhandler.prototype.removeurlparameters = function (seekedurl) { var baseurl = seekedurl.split('?')[0]; var params = undefined; var queryindex = seekedurl.indexof('?'); if (queryindex !== -1) { params = seekedurl.substring(queryindex + 1); } var resultparams = ''; if (params != undefined && params.length > 0) { var pairs = params.split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); var requireand = (i > 0); if (pair[0] !== this._startname && pair[0] !== this._endname) { if (requireand) { resultparams += '&'; } resultparams += pairs[i]; } } } return (resultparams.length === 0) ? baseurl : baseurl + '?' + resultparams; }; return paramseekhandler; }()); /* harmony default export */ __webpack_exports__["default"] = (paramseekhandler); /***/ }), /***/ "./src/io/range-seek-handler.js": /*!**************************************!*\ !*** ./src/io/range-seek-handler.js ***! \**************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var rangeseekhandler = /** @class */ (function () { function rangeseekhandler(zerostart) { this._zerostart = zerostart || false; } rangeseekhandler.prototype.getconfig = function (url, range) { var headers = {}; if (range.from !== 0 || range.to !== -1) { var param = void 0; if (range.to !== -1) { param = "bytes=" + range.from.tostring() + "-" + range.to.tostring(); } else { param = "bytes=" + range.from.tostring() + "-"; } headers['range'] = param; } else if (this._zerostart) { headers['range'] = 'bytes=0-'; } return { url: url, headers: headers }; }; rangeseekhandler.prototype.removeurlparameters = function (seekedurl) { return seekedurl; }; return rangeseekhandler; }()); /* harmony default export */ __webpack_exports__["default"] = (rangeseekhandler); /***/ }), /***/ "./src/io/speed-sampler.js": /*!*********************************!*\ !*** ./src/io/speed-sampler.js ***! \*********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ // utility class to calculate realtime network i/o speed var speedsampler = /** @class */ (function () { function speedsampler() { // milliseconds this._firstcheckpoint = 0; this._lastcheckpoint = 0; this._intervalbytes = 0; this._totalbytes = 0; this._lastsecondbytes = 0; // compatibility detection if (self.performance && self.performance.now) { this._now = self.performance.now.bind(self.performance); } else { this._now = date.now; } } speedsampler.prototype.reset = function () { this._firstcheckpoint = this._lastcheckpoint = 0; this._totalbytes = this._intervalbytes = 0; this._lastsecondbytes = 0; }; speedsampler.prototype.addbytes = function (bytes) { if (this._firstcheckpoint === 0) { this._firstcheckpoint = this._now(); this._lastcheckpoint = this._firstcheckpoint; this._intervalbytes += bytes; this._totalbytes += bytes; } else if (this._now() - this._lastcheckpoint < 1000) { this._intervalbytes += bytes; this._totalbytes += bytes; } else { // duration >= 1000 this._lastsecondbytes = this._intervalbytes; this._intervalbytes = bytes; this._totalbytes += bytes; this._lastcheckpoint = this._now(); } }; object.defineproperty(speedsampler.prototype, "currentkbps", { get: function () { this.addbytes(0); var durationseconds = (this._now() - this._lastcheckpoint) / 1000; if (durationseconds == 0) durationseconds = 1; return (this._intervalbytes / durationseconds) / 1024; }, enumerable: false, configurable: true }); object.defineproperty(speedsampler.prototype, "lastsecondkbps", { get: function () { this.addbytes(0); if (this._lastsecondbytes !== 0) { return this._lastsecondbytes / 1024; } else { // lastsecondbytes === 0 if (this._now() - this._lastcheckpoint >= 500) { // if time interval since last checkpoint has exceeded 500ms // the speed is nearly accurate return this.currentkbps; } else { // we don't know return 0; } } }, enumerable: false, configurable: true }); object.defineproperty(speedsampler.prototype, "averagekbps", { get: function () { var durationseconds = (this._now() - this._firstcheckpoint) / 1000; return (this._totalbytes / durationseconds) / 1024; }, enumerable: false, configurable: true }); return speedsampler; }()); /* harmony default export */ __webpack_exports__["default"] = (speedsampler); /***/ }), /***/ "./src/io/websocket-loader.js": /*!************************************!*\ !*** ./src/io/websocket-loader.js ***! \************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _loader_js__webpack_imported_module_0__ = __webpack_require__(/*! ./loader.js */ "./src/io/loader.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_1__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var __extends = (undefined && undefined.__extends) || (function () { var extendstatics = function (d, b) { extendstatics = object.setprototypeof || ({ __proto__: [] } instanceof array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (object.prototype.hasownproperty.call(b, p)) d[p] = b[p]; }; return extendstatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new typeerror("class extends value " + string(b) + " is not a constructor or null"); extendstatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // for flv over websocket live stream var websocketloader = /** @class */ (function (_super) { __extends(websocketloader, _super); function websocketloader() { var _this = _super.call(this, 'websocket-loader') || this; _this.tag = 'websocketloader'; _this._needstash = true; _this._ws = null; _this._requestabort = false; _this._receivedlength = 0; return _this; } websocketloader.issupported = function () { try { return (typeof self.websocket !== 'undefined'); } catch (e) { return false; } }; websocketloader.prototype.destroy = function () { if (this._ws) { this.abort(); } _super.prototype.destroy.call(this); }; websocketloader.prototype.open = function (datasource) { try { var ws = this._ws = new self.websocket(datasource.url); ws.binarytype = 'arraybuffer'; ws.onopen = this._onwebsocketopen.bind(this); ws.onclose = this._onwebsocketclose.bind(this); ws.onmessage = this._onwebsocketmessage.bind(this); ws.onerror = this._onwebsocketerror.bind(this); this._status = _loader_js__webpack_imported_module_0__.loaderstatus.kconnecting; } catch (e) { this._status = _loader_js__webpack_imported_module_0__.loaderstatus.kerror; var info = { code: e.code, msg: e.message }; if (this._onerror) { this._onerror(_loader_js__webpack_imported_module_0__.loadererrors.exception, info); } else { throw new _utils_exception_js__webpack_imported_module_1__.runtimeexception(info.msg); } } }; websocketloader.prototype.abort = function () { var ws = this._ws; if (ws && (ws.readystate === 0 || ws.readystate === 1)) { // connecting || open this._requestabort = true; ws.close(); } this._ws = null; this._status = _loader_js__webpack_imported_module_0__.loaderstatus.kcomplete; }; websocketloader.prototype._onwebsocketopen = function (e) { this._status = _loader_js__webpack_imported_module_0__.loaderstatus.kbuffering; }; websocketloader.prototype._onwebsocketclose = function (e) { if (this._requestabort === true) { this._requestabort = false; return; } this._status = _loader_js__webpack_imported_module_0__.loaderstatus.kcomplete; if (this._oncomplete) { this._oncomplete(0, this._receivedlength - 1); } }; websocketloader.prototype._onwebsocketmessage = function (e) { var _this = this; if (e.data instanceof arraybuffer) { this._dispatcharraybuffer(e.data); } else if (e.data instanceof blob) { var reader_1 = new filereader(); reader_1.onload = function () { _this._dispatcharraybuffer(reader_1.result); }; reader_1.readasarraybuffer(e.data); } else { this._status = _loader_js__webpack_imported_module_0__.loaderstatus.kerror; var info = { code: -1, msg: 'unsupported websocket message type: ' + e.data.constructor.name }; if (this._onerror) { this._onerror(_loader_js__webpack_imported_module_0__.loadererrors.exception, info); } else { throw new _utils_exception_js__webpack_imported_module_1__.runtimeexception(info.msg); } } }; websocketloader.prototype._dispatcharraybuffer = function (arraybuffer) { var chunk = arraybuffer; var bytestart = this._receivedlength; this._receivedlength += chunk.bytelength; if (this._ondataarrival) { this._ondataarrival(chunk, bytestart, this._receivedlength); } }; websocketloader.prototype._onwebsocketerror = function (e) { this._status = _loader_js__webpack_imported_module_0__.loaderstatus.kerror; var info = { code: e.code, msg: e.message }; if (this._onerror) { this._onerror(_loader_js__webpack_imported_module_0__.loadererrors.exception, info); } else { throw new _utils_exception_js__webpack_imported_module_1__.runtimeexception(info.msg); } }; return websocketloader; }(_loader_js__webpack_imported_module_0__.baseloader)); /* harmony default export */ __webpack_exports__["default"] = (websocketloader); /***/ }), /***/ "./src/io/xhr-moz-chunked-loader.js": /*!******************************************!*\ !*** ./src/io/xhr-moz-chunked-loader.js ***! \******************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _loader_js__webpack_imported_module_1__ = __webpack_require__(/*! ./loader.js */ "./src/io/loader.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_2__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var __extends = (undefined && undefined.__extends) || (function () { var extendstatics = function (d, b) { extendstatics = object.setprototypeof || ({ __proto__: [] } instanceof array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (object.prototype.hasownproperty.call(b, p)) d[p] = b[p]; }; return extendstatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new typeerror("class extends value " + string(b) + " is not a constructor or null"); extendstatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // for firefox browser which supports `xhr.responsetype = 'moz-chunked-arraybuffer'` var mozchunkedloader = /** @class */ (function (_super) { __extends(mozchunkedloader, _super); function mozchunkedloader(seekhandler, config) { var _this = _super.call(this, 'xhr-moz-chunked-loader') || this; _this.tag = 'mozchunkedloader'; _this._seekhandler = seekhandler; _this._config = config; _this._needstash = true; _this._xhr = null; _this._requestabort = false; _this._contentlength = null; _this._receivedlength = 0; return _this; } mozchunkedloader.issupported = function () { try { var xhr = new xmlhttprequest(); // firefox 37- requires .open() to be called before setting responsetype xhr.open('get', 'https://example.com', true); xhr.responsetype = 'moz-chunked-arraybuffer'; return (xhr.responsetype === 'moz-chunked-arraybuffer'); } catch (e) { _utils_logger_js__webpack_imported_module_0__.default.w('mozchunkedloader', e.message); return false; } }; mozchunkedloader.prototype.destroy = function () { if (this.isworking()) { this.abort(); } if (this._xhr) { this._xhr.onreadystatechange = null; this._xhr.onprogress = null; this._xhr.onloadend = null; this._xhr.onerror = null; this._xhr = null; } _super.prototype.destroy.call(this); }; mozchunkedloader.prototype.open = function (datasource, range) { this._datasource = datasource; this._range = range; var sourceurl = datasource.url; if (this._config.reuseredirectedurl && datasource.redirectedurl != undefined) { sourceurl = datasource.redirectedurl; } var seekconfig = this._seekhandler.getconfig(sourceurl, range); this._requesturl = seekconfig.url; var xhr = this._xhr = new xmlhttprequest(); xhr.open('get', seekconfig.url, true); xhr.responsetype = 'moz-chunked-arraybuffer'; xhr.onreadystatechange = this._onreadystatechange.bind(this); xhr.onprogress = this._onprogress.bind(this); xhr.onloadend = this._onloadend.bind(this); xhr.onerror = this._onxhrerror.bind(this); // cors is auto detected and enabled by xhr // withcredentials is disabled by default if (datasource.withcredentials) { xhr.withcredentials = true; } if (typeof seekconfig.headers === 'object') { var headers = seekconfig.headers; for (var key in headers) { if (headers.hasownproperty(key)) { xhr.setrequestheader(key, headers[key]); } } } // add additional headers if (typeof this._config.headers === 'object') { var headers = this._config.headers; for (var key in headers) { if (headers.hasownproperty(key)) { xhr.setrequestheader(key, headers[key]); } } } this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kconnecting; xhr.send(); }; mozchunkedloader.prototype.abort = function () { this._requestabort = true; if (this._xhr) { this._xhr.abort(); } this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kcomplete; }; mozchunkedloader.prototype._onreadystatechange = function (e) { var xhr = e.target; if (xhr.readystate === 2) { // headers_received if (xhr.responseurl != undefined && xhr.responseurl !== this._requesturl) { if (this._onurlredirect) { var redirectedurl = this._seekhandler.removeurlparameters(xhr.responseurl); this._onurlredirect(redirectedurl); } } if (xhr.status !== 0 && (xhr.status < 200 || xhr.status > 299)) { this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kerror; if (this._onerror) { this._onerror(_loader_js__webpack_imported_module_1__.loadererrors.http_status_code_invalid, { code: xhr.status, msg: xhr.statustext }); } else { throw new _utils_exception_js__webpack_imported_module_2__.runtimeexception('mozchunkedloader: http code invalid, ' + xhr.status + ' ' + xhr.statustext); } } else { this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kbuffering; } } }; mozchunkedloader.prototype._onprogress = function (e) { if (this._status === _loader_js__webpack_imported_module_1__.loaderstatus.kerror) { // ignore error response return; } if (this._contentlength === null) { if (e.total !== null && e.total !== 0) { this._contentlength = e.total; if (this._oncontentlengthknown) { this._oncontentlengthknown(this._contentlength); } } } var chunk = e.target.response; var bytestart = this._range.from + this._receivedlength; this._receivedlength += chunk.bytelength; if (this._ondataarrival) { this._ondataarrival(chunk, bytestart, this._receivedlength); } }; mozchunkedloader.prototype._onloadend = function (e) { if (this._requestabort === true) { this._requestabort = false; return; } else if (this._status === _loader_js__webpack_imported_module_1__.loaderstatus.kerror) { return; } this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kcomplete; if (this._oncomplete) { this._oncomplete(this._range.from, this._range.from + this._receivedlength - 1); } }; mozchunkedloader.prototype._onxhrerror = function (e) { this._status = _loader_js__webpack_imported_module_1__.loaderstatus.kerror; var type = 0; var info = null; if (this._contentlength && e.loaded < this._contentlength) { type = _loader_js__webpack_imported_module_1__.loadererrors.early_eof; info = { code: -1, msg: 'moz-chunked stream meet early-eof' }; } else { type = _loader_js__webpack_imported_module_1__.loadererrors.exception; info = { code: -1, msg: e.constructor.name + ' ' + e.type }; } if (this._onerror) { this._onerror(type, info); } else { throw new _utils_exception_js__webpack_imported_module_2__.runtimeexception(info.msg); } }; return mozchunkedloader; }(_loader_js__webpack_imported_module_1__.baseloader)); /* harmony default export */ __webpack_exports__["default"] = (mozchunkedloader); /***/ }), /***/ "./src/io/xhr-range-loader.js": /*!************************************!*\ !*** ./src/io/xhr-range-loader.js ***! \************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _speed_sampler_js__webpack_imported_module_1__ = __webpack_require__(/*! ./speed-sampler.js */ "./src/io/speed-sampler.js"); /* harmony import */ var _loader_js__webpack_imported_module_2__ = __webpack_require__(/*! ./loader.js */ "./src/io/loader.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_3__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var __extends = (undefined && undefined.__extends) || (function () { var extendstatics = function (d, b) { extendstatics = object.setprototypeof || ({ __proto__: [] } instanceof array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (object.prototype.hasownproperty.call(b, p)) d[p] = b[p]; }; return extendstatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new typeerror("class extends value " + string(b) + " is not a constructor or null"); extendstatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // universal io loader, implemented by adding range header in xhr's request header var rangeloader = /** @class */ (function (_super) { __extends(rangeloader, _super); function rangeloader(seekhandler, config) { var _this = _super.call(this, 'xhr-range-loader') || this; _this.tag = 'rangeloader'; _this._seekhandler = seekhandler; _this._config = config; _this._needstash = false; _this._chunksizekblist = [ 128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 7168, 8192 ]; _this._currentchunksizekb = 384; _this._currentspeednormalized = 0; _this._zerospeedchunkcount = 0; _this._xhr = null; _this._speedsampler = new _speed_sampler_js__webpack_imported_module_1__.default(); _this._requestabort = false; _this._waitfortotallength = false; _this._totallengthreceived = false; _this._currentrequesturl = null; _this._currentredirectedurl = null; _this._currentrequestrange = null; _this._totallength = null; // size of the entire file _this._contentlength = null; // content-length of entire request range _this._receivedlength = 0; // total received bytes _this._lasttimeloaded = 0; // received bytes of current request sub-range return _this; } rangeloader.issupported = function () { try { var xhr = new xmlhttprequest(); xhr.open('get', 'https://example.com', true); xhr.responsetype = 'arraybuffer'; return (xhr.responsetype === 'arraybuffer'); } catch (e) { _utils_logger_js__webpack_imported_module_0__.default.w('rangeloader', e.message); return false; } }; rangeloader.prototype.destroy = function () { if (this.isworking()) { this.abort(); } if (this._xhr) { this._xhr.onreadystatechange = null; this._xhr.onprogress = null; this._xhr.onload = null; this._xhr.onerror = null; this._xhr = null; } _super.prototype.destroy.call(this); }; object.defineproperty(rangeloader.prototype, "currentspeed", { get: function () { return this._speedsampler.lastsecondkbps; }, enumerable: false, configurable: true }); rangeloader.prototype.open = function (datasource, range) { this._datasource = datasource; this._range = range; this._status = _loader_js__webpack_imported_module_2__.loaderstatus.kconnecting; var usereftotallength = false; if (this._datasource.filesize != undefined && this._datasource.filesize !== 0) { usereftotallength = true; this._totallength = this._datasource.filesize; } if (!this._totallengthreceived && !usereftotallength) { // we need total filesize this._waitfortotallength = true; this._internalopen(this._datasource, { from: 0, to: -1 }); } else { // we have filesize, start loading this._opensubrange(); } }; rangeloader.prototype._opensubrange = function () { var chunksize = this._currentchunksizekb * 1024; var from = this._range.from + this._receivedlength; var to = from + chunksize; if (this._contentlength != null) { if (to - this._range.from >= this._contentlength) { to = this._range.from + this._contentlength - 1; } } this._currentrequestrange = { from: from, to: to }; this._internalopen(this._datasource, this._currentrequestrange); }; rangeloader.prototype._internalopen = function (datasource, range) { this._lasttimeloaded = 0; var sourceurl = datasource.url; if (this._config.reuseredirectedurl) { if (this._currentredirectedurl != undefined) { sourceurl = this._currentredirectedurl; } else if (datasource.redirectedurl != undefined) { sourceurl = datasource.redirectedurl; } } var seekconfig = this._seekhandler.getconfig(sourceurl, range); this._currentrequesturl = seekconfig.url; var xhr = this._xhr = new xmlhttprequest(); xhr.open('get', seekconfig.url, true); xhr.responsetype = 'arraybuffer'; xhr.onreadystatechange = this._onreadystatechange.bind(this); xhr.onprogress = this._onprogress.bind(this); xhr.onload = this._onload.bind(this); xhr.onerror = this._onxhrerror.bind(this); if (datasource.withcredentials) { xhr.withcredentials = true; } if (typeof seekconfig.headers === 'object') { var headers = seekconfig.headers; for (var key in headers) { if (headers.hasownproperty(key)) { xhr.setrequestheader(key, headers[key]); } } } // add additional headers if (typeof this._config.headers === 'object') { var headers = this._config.headers; for (var key in headers) { if (headers.hasownproperty(key)) { xhr.setrequestheader(key, headers[key]); } } } xhr.send(); }; rangeloader.prototype.abort = function () { this._requestabort = true; this._internalabort(); this._status = _loader_js__webpack_imported_module_2__.loaderstatus.kcomplete; }; rangeloader.prototype._internalabort = function () { if (this._xhr) { this._xhr.onreadystatechange = null; this._xhr.onprogress = null; this._xhr.onload = null; this._xhr.onerror = null; this._xhr.abort(); this._xhr = null; } }; rangeloader.prototype._onreadystatechange = function (e) { var xhr = e.target; if (xhr.readystate === 2) { // headers_received if (xhr.responseurl != undefined) { // if the browser support this property var redirectedurl = this._seekhandler.removeurlparameters(xhr.responseurl); if (xhr.responseurl !== this._currentrequesturl && redirectedurl !== this._currentredirectedurl) { this._currentredirectedurl = redirectedurl; if (this._onurlredirect) { this._onurlredirect(redirectedurl); } } } if ((xhr.status >= 200 && xhr.status <= 299)) { if (this._waitfortotallength) { return; } this._status = _loader_js__webpack_imported_module_2__.loaderstatus.kbuffering; } else { this._status = _loader_js__webpack_imported_module_2__.loaderstatus.kerror; if (this._onerror) { this._onerror(_loader_js__webpack_imported_module_2__.loadererrors.http_status_code_invalid, { code: xhr.status, msg: xhr.statustext }); } else { throw new _utils_exception_js__webpack_imported_module_3__.runtimeexception('rangeloader: http code invalid, ' + xhr.status + ' ' + xhr.statustext); } } } }; rangeloader.prototype._onprogress = function (e) { if (this._status === _loader_js__webpack_imported_module_2__.loaderstatus.kerror) { // ignore error response return; } if (this._contentlength === null) { var opennextrange = false; if (this._waitfortotallength) { this._waitfortotallength = false; this._totallengthreceived = true; opennextrange = true; var total = e.total; this._internalabort(); if (total != null & total !== 0) { this._totallength = total; } } // calculate currrent request range's contentlength if (this._range.to === -1) { this._contentlength = this._totallength - this._range.from; } else { // to !== -1 this._contentlength = this._range.to - this._range.from + 1; } if (opennextrange) { this._opensubrange(); return; } if (this._oncontentlengthknown) { this._oncontentlengthknown(this._contentlength); } } var delta = e.loaded - this._lasttimeloaded; this._lasttimeloaded = e.loaded; this._speedsampler.addbytes(delta); }; rangeloader.prototype._normalizespeed = function (input) { var list = this._chunksizekblist; var last = list.length - 1; var mid = 0; var lbound = 0; var ubound = last; if (input < list[0]) { return list[0]; } while (lbound <= ubound) { mid = lbound + math.floor((ubound - lbound) / 2); if (mid === last || (input >= list[mid] && input < list[mid + 1])) { return list[mid]; } else if (list[mid] < input) { lbound = mid + 1; } else { ubound = mid - 1; } } }; rangeloader.prototype._onload = function (e) { if (this._status === _loader_js__webpack_imported_module_2__.loaderstatus.kerror) { // ignore error response return; } if (this._waitfortotallength) { this._waitfortotallength = false; return; } this._lasttimeloaded = 0; var kbps = this._speedsampler.lastsecondkbps; if (kbps === 0) { this._zerospeedchunkcount++; if (this._zerospeedchunkcount >= 3) { // try get currentkbps after 3 chunks kbps = this._speedsampler.currentkbps; } } if (kbps !== 0) { var normalized = this._normalizespeed(kbps); if (this._currentspeednormalized !== normalized) { this._currentspeednormalized = normalized; this._currentchunksizekb = normalized; } } var chunk = e.target.response; var bytestart = this._range.from + this._receivedlength; this._receivedlength += chunk.bytelength; var reportcomplete = false; if (this._contentlength != null && this._receivedlength < this._contentlength) { // continue load next chunk this._opensubrange(); } else { reportcomplete = true; } // dispatch received chunk if (this._ondataarrival) { this._ondataarrival(chunk, bytestart, this._receivedlength); } if (reportcomplete) { this._status = _loader_js__webpack_imported_module_2__.loaderstatus.kcomplete; if (this._oncomplete) { this._oncomplete(this._range.from, this._range.from + this._receivedlength - 1); } } }; rangeloader.prototype._onxhrerror = function (e) { this._status = _loader_js__webpack_imported_module_2__.loaderstatus.kerror; var type = 0; var info = null; if (this._contentlength && this._receivedlength > 0 && this._receivedlength < this._contentlength) { type = _loader_js__webpack_imported_module_2__.loadererrors.early_eof; info = { code: -1, msg: 'rangeloader meet early-eof' }; } else { type = _loader_js__webpack_imported_module_2__.loadererrors.exception; info = { code: -1, msg: e.constructor.name + ' ' + e.type }; } if (this._onerror) { this._onerror(type, info); } else { throw new _utils_exception_js__webpack_imported_module_3__.runtimeexception(info.msg); } }; return rangeloader; }(_loader_js__webpack_imported_module_2__.baseloader)); /* harmony default export */ __webpack_exports__["default"] = (rangeloader); /***/ }), /***/ "./src/player/flv-player.js": /*!**********************************!*\ !*** ./src/player/flv-player.js ***! \**********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var events__webpack_imported_module_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js"); /* harmony import */ var events__webpack_imported_module_0___default = /*#__pure__*/__webpack_require__.n(events__webpack_imported_module_0__); /* harmony import */ var _utils_logger_js__webpack_imported_module_1__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _utils_browser_js__webpack_imported_module_2__ = __webpack_require__(/*! ../utils/browser.js */ "./src/utils/browser.js"); /* harmony import */ var _player_events_js__webpack_imported_module_3__ = __webpack_require__(/*! ./player-events.js */ "./src/player/player-events.js"); /* harmony import */ var _core_transmuxer_js__webpack_imported_module_4__ = __webpack_require__(/*! ../core/transmuxer.js */ "./src/core/transmuxer.js"); /* harmony import */ var _core_transmuxing_events_js__webpack_imported_module_5__ = __webpack_require__(/*! ../core/transmuxing-events.js */ "./src/core/transmuxing-events.js"); /* harmony import */ var _core_mse_controller_js__webpack_imported_module_6__ = __webpack_require__(/*! ../core/mse-controller.js */ "./src/core/mse-controller.js"); /* harmony import */ var _core_mse_events_js__webpack_imported_module_7__ = __webpack_require__(/*! ../core/mse-events.js */ "./src/core/mse-events.js"); /* harmony import */ var _player_errors_js__webpack_imported_module_8__ = __webpack_require__(/*! ./player-errors.js */ "./src/player/player-errors.js"); /* harmony import */ var _config_js__webpack_imported_module_9__ = __webpack_require__(/*! ../config.js */ "./src/config.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_10__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var flvplayer = /** @class */ (function () { function flvplayer(mediadatasource, config) { this.tag = 'flvplayer'; this._type = 'flvplayer'; this._emitter = new (events__webpack_imported_module_0___default())(); this._config = (0,_config_js__webpack_imported_module_9__.createdefaultconfig)(); if (typeof config === 'object') { object.assign(this._config, config); } if (mediadatasource.type.tolowercase() !== 'flv') { throw new _utils_exception_js__webpack_imported_module_10__.invalidargumentexception('flvplayer requires an flv mediadatasource input!'); } if (mediadatasource.islive === true) { this._config.islive = true; } this.e = { onvloadedmetadata: this._onvloadedmetadata.bind(this), onvseeking: this._onvseeking.bind(this), onvcanplay: this._onvcanplay.bind(this), onvstalled: this._onvstalled.bind(this), onvprogress: this._onvprogress.bind(this) }; if (self.performance && self.performance.now) { this._now = self.performance.now.bind(self.performance); } else { this._now = date.now; } this._pendingseektime = null; // in seconds this._requestsettime = false; this._seekpointrecord = null; this._progresschecker = null; this._mediadatasource = mediadatasource; this._mediaelement = null; this._msectl = null; this._transmuxer = null; this._msesourceopened = false; this._haspendingload = false; this._receivedcanplay = false; this._mediainfo = null; this._statisticsinfo = null; var chromeneedidrfix = (_utils_browser_js__webpack_imported_module_2__.default.chrome && (_utils_browser_js__webpack_imported_module_2__.default.version.major < 50 || (_utils_browser_js__webpack_imported_module_2__.default.version.major === 50 && _utils_browser_js__webpack_imported_module_2__.default.version.build < 2661))); this._alwaysseekkeyframe = (chromeneedidrfix || _utils_browser_js__webpack_imported_module_2__.default.msedge || _utils_browser_js__webpack_imported_module_2__.default.msie) ? true : false; if (this._alwaysseekkeyframe) { this._config.accurateseek = false; } } flvplayer.prototype.destroy = function () { if (this._progresschecker != null) { window.clearinterval(this._progresschecker); this._progresschecker = null; } if (this._transmuxer) { this.unload(); } if (this._mediaelement) { this.detachmediaelement(); } this.e = null; this._mediadatasource = null; this._emitter.removealllisteners(); this._emitter = null; }; flvplayer.prototype.on = function (event, listener) { var _this = this; if (event === _player_events_js__webpack_imported_module_3__.default.media_info) { if (this._mediainfo != null) { promise.resolve().then(function () { _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.media_info, _this.mediainfo); }); } } else if (event === _player_events_js__webpack_imported_module_3__.default.statistics_info) { if (this._statisticsinfo != null) { promise.resolve().then(function () { _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.statistics_info, _this.statisticsinfo); }); } } this._emitter.addlistener(event, listener); }; flvplayer.prototype.off = function (event, listener) { this._emitter.removelistener(event, listener); }; flvplayer.prototype.attachmediaelement = function (mediaelement) { var _this = this; this._mediaelement = mediaelement; mediaelement.addeventlistener('loadedmetadata', this.e.onvloadedmetadata); mediaelement.addeventlistener('seeking', this.e.onvseeking); mediaelement.addeventlistener('canplay', this.e.onvcanplay); mediaelement.addeventlistener('stalled', this.e.onvstalled); mediaelement.addeventlistener('progress', this.e.onvprogress); this._msectl = new _core_mse_controller_js__webpack_imported_module_6__.default(this._config); this._msectl.on(_core_mse_events_js__webpack_imported_module_7__.default.update_end, this._onmseupdateend.bind(this)); this._msectl.on(_core_mse_events_js__webpack_imported_module_7__.default.buffer_full, this._onmsebufferfull.bind(this)); this._msectl.on(_core_mse_events_js__webpack_imported_module_7__.default.source_open, function () { _this._msesourceopened = true; if (_this._haspendingload) { _this._haspendingload = false; _this.load(); } }); this._msectl.on(_core_mse_events_js__webpack_imported_module_7__.default.error, function (info) { _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.error, _player_errors_js__webpack_imported_module_8__.errortypes.media_error, _player_errors_js__webpack_imported_module_8__.errordetails.media_mse_error, info); }); this._msectl.attachmediaelement(mediaelement); if (this._pendingseektime != null) { try { mediaelement.currenttime = this._pendingseektime; this._pendingseektime = null; } catch (e) { // ie11 may throw invalidstateerror if readystate === 0 // we can defer set currenttime operation after loadedmetadata } } }; flvplayer.prototype.detachmediaelement = function () { if (this._mediaelement) { this._msectl.detachmediaelement(); this._mediaelement.removeeventlistener('loadedmetadata', this.e.onvloadedmetadata); this._mediaelement.removeeventlistener('seeking', this.e.onvseeking); this._mediaelement.removeeventlistener('canplay', this.e.onvcanplay); this._mediaelement.removeeventlistener('stalled', this.e.onvstalled); this._mediaelement.removeeventlistener('progress', this.e.onvprogress); this._mediaelement = null; } if (this._msectl) { this._msectl.destroy(); this._msectl = null; } }; flvplayer.prototype.load = function () { var _this = this; if (!this._mediaelement) { throw new _utils_exception_js__webpack_imported_module_10__.illegalstateexception('htmlmediaelement must be attached before load()!'); } if (this._transmuxer) { throw new _utils_exception_js__webpack_imported_module_10__.illegalstateexception('flvplayer.load() has been called, please call unload() first!'); } if (this._haspendingload) { return; } if (this._config.deferloadaftersourceopen && this._msesourceopened === false) { this._haspendingload = true; return; } if (this._mediaelement.readystate > 0) { this._requestsettime = true; // ie11 may throw invalidstateerror if readystate === 0 this._mediaelement.currenttime = 0; } this._transmuxer = new _core_transmuxer_js__webpack_imported_module_4__.default(this._mediadatasource, this._config); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.init_segment, function (type, is) { _this._msectl.appendinitsegment(is); }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.media_segment, function (type, ms) { _this._msectl.appendmediasegment(ms); // lazyload check if (_this._config.lazyload && !_this._config.islive) { var currenttime = _this._mediaelement.currenttime; if (ms.info.enddts >= (currenttime + _this._config.lazyloadmaxduration) * 1000) { if (_this._progresschecker == null) { _utils_logger_js__webpack_imported_module_1__.default.v(_this.tag, 'maximum buffering duration exceeded, suspend transmuxing task'); _this._suspendtransmuxer(); } } } }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.loading_complete, function () { _this._msectl.endofstream(); _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.loading_complete); }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.recovered_early_eof, function () { _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.recovered_early_eof); }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.io_error, function (detail, info) { _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.error, _player_errors_js__webpack_imported_module_8__.errortypes.network_error, detail, info); }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.demux_error, function (detail, info) { _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.error, _player_errors_js__webpack_imported_module_8__.errortypes.media_error, detail, { code: -1, msg: info }); }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.media_info, function (mediainfo) { _this._mediainfo = mediainfo; _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.media_info, object.assign({}, mediainfo)); }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.metadata_arrived, function (metadata) { _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.metadata_arrived, metadata); }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.scriptdata_arrived, function (data) { _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.scriptdata_arrived, data); }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.statistics_info, function (statinfo) { _this._statisticsinfo = _this._fillstatisticsinfo(statinfo); _this._emitter.emit(_player_events_js__webpack_imported_module_3__.default.statistics_info, object.assign({}, _this._statisticsinfo)); }); this._transmuxer.on(_core_transmuxing_events_js__webpack_imported_module_5__.default.recommend_seekpoint, function (milliseconds) { if (_this._mediaelement && !_this._config.accurateseek) { _this._requestsettime = true; _this._mediaelement.currenttime = milliseconds / 1000; } }); this._transmuxer.open(); }; flvplayer.prototype.unload = function () { if (this._mediaelement) { this._mediaelement.pause(); } if (this._msectl) { this._msectl.seek(0); } if (this._transmuxer) { this._transmuxer.close(); this._transmuxer.destroy(); this._transmuxer = null; } }; flvplayer.prototype.play = function () { return this._mediaelement.play(); }; flvplayer.prototype.pause = function () { this._mediaelement.pause(); }; object.defineproperty(flvplayer.prototype, "type", { get: function () { return this._type; }, enumerable: false, configurable: true }); object.defineproperty(flvplayer.prototype, "buffered", { get: function () { return this._mediaelement.buffered; }, enumerable: false, configurable: true }); object.defineproperty(flvplayer.prototype, "duration", { get: function () { return this._mediaelement.duration; }, enumerable: false, configurable: true }); object.defineproperty(flvplayer.prototype, "volume", { get: function () { return this._mediaelement.volume; }, set: function (value) { this._mediaelement.volume = value; }, enumerable: false, configurable: true }); object.defineproperty(flvplayer.prototype, "muted", { get: function () { return this._mediaelement.muted; }, set: function (muted) { this._mediaelement.muted = muted; }, enumerable: false, configurable: true }); object.defineproperty(flvplayer.prototype, "currenttime", { get: function () { if (this._mediaelement) { return this._mediaelement.currenttime; } return 0; }, set: function (seconds) { if (this._mediaelement) { this._internalseek(seconds); } else { this._pendingseektime = seconds; } }, enumerable: false, configurable: true }); object.defineproperty(flvplayer.prototype, "mediainfo", { get: function () { return object.assign({}, this._mediainfo); }, enumerable: false, configurable: true }); object.defineproperty(flvplayer.prototype, "statisticsinfo", { get: function () { if (this._statisticsinfo == null) { this._statisticsinfo = {}; } this._statisticsinfo = this._fillstatisticsinfo(this._statisticsinfo); return object.assign({}, this._statisticsinfo); }, enumerable: false, configurable: true }); flvplayer.prototype._fillstatisticsinfo = function (statinfo) { statinfo.playertype = this._type; if (!(this._mediaelement instanceof htmlvideoelement)) { return statinfo; } var hasqualityinfo = true; var decoded = 0; var dropped = 0; if (this._mediaelement.getvideoplaybackquality) { var quality = this._mediaelement.getvideoplaybackquality(); decoded = quality.totalvideoframes; dropped = quality.droppedvideoframes; } else if (this._mediaelement.webkitdecodedframecount != undefined) { decoded = this._mediaelement.webkitdecodedframecount; dropped = this._mediaelement.webkitdroppedframecount; } else { hasqualityinfo = false; } if (hasqualityinfo) { statinfo.decodedframes = decoded; statinfo.droppedframes = dropped; } return statinfo; }; flvplayer.prototype._onmseupdateend = function () { if (!this._config.lazyload || this._config.islive) { return; } var buffered = this._mediaelement.buffered; var currenttime = this._mediaelement.currenttime; var currentrangestart = 0; var currentrangeend = 0; for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); if (start <= currenttime && currenttime < end) { currentrangestart = start; currentrangeend = end; break; } } if (currentrangeend >= currenttime + this._config.lazyloadmaxduration && this._progresschecker == null) { _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, 'maximum buffering duration exceeded, suspend transmuxing task'); this._suspendtransmuxer(); } }; flvplayer.prototype._onmsebufferfull = function () { _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, 'mse sourcebuffer is full, suspend transmuxing task'); if (this._progresschecker == null) { this._suspendtransmuxer(); } }; flvplayer.prototype._suspendtransmuxer = function () { if (this._transmuxer) { this._transmuxer.pause(); if (this._progresschecker == null) { this._progresschecker = window.setinterval(this._checkprogressandresume.bind(this), 1000); } } }; flvplayer.prototype._checkprogressandresume = function () { var currenttime = this._mediaelement.currenttime; var buffered = this._mediaelement.buffered; var needresume = false; for (var i = 0; i < buffered.length; i++) { var from = buffered.start(i); var to = buffered.end(i); if (currenttime >= from && currenttime < to) { if (currenttime >= to - this._config.lazyloadrecoverduration) { needresume = true; } break; } } if (needresume) { window.clearinterval(this._progresschecker); this._progresschecker = null; if (needresume) { _utils_logger_js__webpack_imported_module_1__.default.v(this.tag, 'continue loading from paused position'); this._transmuxer.resume(); } } }; flvplayer.prototype._istimepointbuffered = function (seconds) { var buffered = this._mediaelement.buffered; for (var i = 0; i < buffered.length; i++) { var from = buffered.start(i); var to = buffered.end(i); if (seconds >= from && seconds < to) { return true; } } return false; }; flvplayer.prototype._internalseek = function (seconds) { var directseek = this._istimepointbuffered(seconds); var directseekbegin = false; var directseekbegintime = 0; if (seconds < 1.0 && this._mediaelement.buffered.length > 0) { var videobegintime = this._mediaelement.buffered.start(0); if ((videobegintime < 1.0 && seconds < videobegintime) || _utils_browser_js__webpack_imported_module_2__.default.safari) { directseekbegin = true; // also workaround for safari: seek to 0 may cause video stuck, use 0.1 to avoid directseekbegintime = _utils_browser_js__webpack_imported_module_2__.default.safari ? 0.1 : videobegintime; } } if (directseekbegin) { // seek to video begin, set currenttime directly if beginpts buffered this._requestsettime = true; this._mediaelement.currenttime = directseekbegintime; } else if (directseek) { // buffered position if (!this._alwaysseekkeyframe) { this._requestsettime = true; this._mediaelement.currenttime = seconds; } else { var idr = this._msectl.getnearestkeyframe(math.floor(seconds * 1000)); this._requestsettime = true; if (idr != null) { this._mediaelement.currenttime = idr.dts / 1000; } else { this._mediaelement.currenttime = seconds; } } if (this._progresschecker != null) { this._checkprogressandresume(); } } else { if (this._progresschecker != null) { window.clearinterval(this._progresschecker); this._progresschecker = null; } this._msectl.seek(seconds); this._transmuxer.seek(math.floor(seconds * 1000)); // in milliseconds // no need to set mediaelement.currenttime if non-accurateseek, // just wait for the recommend_seekpoint callback if (this._config.accurateseek) { this._requestsettime = true; this._mediaelement.currenttime = seconds; } } }; flvplayer.prototype._checkandapplyunbufferedseekpoint = function () { if (this._seekpointrecord) { if (this._seekpointrecord.recordtime <= this._now() - 100) { var target = this._mediaelement.currenttime; this._seekpointrecord = null; if (!this._istimepointbuffered(target)) { if (this._progresschecker != null) { window.cleartimeout(this._progresschecker); this._progresschecker = null; } // .currenttime is consists with .buffered timestamp // chrome/edge use dts, while firefox/safari use pts this._msectl.seek(target); this._transmuxer.seek(math.floor(target * 1000)); // set currenttime if accurateseek, or wait for recommend_seekpoint callback if (this._config.accurateseek) { this._requestsettime = true; this._mediaelement.currenttime = target; } } } else { window.settimeout(this._checkandapplyunbufferedseekpoint.bind(this), 50); } } }; flvplayer.prototype._checkandresumestuckplayback = function (stalled) { var media = this._mediaelement; if (stalled || !this._receivedcanplay || media.readystate < 2) { // have_current_data var buffered = media.buffered; if (buffered.length > 0 && media.currenttime < buffered.start(0)) { _utils_logger_js__webpack_imported_module_1__.default.w(this.tag, "playback seems stuck at " + media.currenttime + ", seek to " + buffered.start(0)); this._requestsettime = true; this._mediaelement.currenttime = buffered.start(0); this._mediaelement.removeeventlistener('progress', this.e.onvprogress); } } else { // playback didn't stuck, remove progress event listener this._mediaelement.removeeventlistener('progress', this.e.onvprogress); } }; flvplayer.prototype._onvloadedmetadata = function (e) { if (this._pendingseektime != null) { this._mediaelement.currenttime = this._pendingseektime; this._pendingseektime = null; } }; flvplayer.prototype._onvseeking = function (e) { var target = this._mediaelement.currenttime; var buffered = this._mediaelement.buffered; if (this._requestsettime) { this._requestsettime = false; return; } if (target < 1.0 && buffered.length > 0) { // seek to video begin, set currenttime directly if beginpts buffered var videobegintime = buffered.start(0); if ((videobegintime < 1.0 && target < videobegintime) || _utils_browser_js__webpack_imported_module_2__.default.safari) { this._requestsettime = true; // also workaround for safari: seek to 0 may cause video stuck, use 0.1 to avoid this._mediaelement.currenttime = _utils_browser_js__webpack_imported_module_2__.default.safari ? 0.1 : videobegintime; return; } } if (this._istimepointbuffered(target)) { if (this._alwaysseekkeyframe) { var idr = this._msectl.getnearestkeyframe(math.floor(target * 1000)); if (idr != null) { this._requestsettime = true; this._mediaelement.currenttime = idr.dts / 1000; } } if (this._progresschecker != null) { this._checkprogressandresume(); } return; } this._seekpointrecord = { seekpoint: target, recordtime: this._now() }; window.settimeout(this._checkandapplyunbufferedseekpoint.bind(this), 50); }; flvplayer.prototype._onvcanplay = function (e) { this._receivedcanplay = true; this._mediaelement.removeeventlistener('canplay', this.e.onvcanplay); }; flvplayer.prototype._onvstalled = function (e) { this._checkandresumestuckplayback(true); }; flvplayer.prototype._onvprogress = function (e) { this._checkandresumestuckplayback(); }; return flvplayer; }()); /* harmony default export */ __webpack_exports__["default"] = (flvplayer); /***/ }), /***/ "./src/player/native-player.js": /*!*************************************!*\ !*** ./src/player/native-player.js ***! \*************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var events__webpack_imported_module_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js"); /* harmony import */ var events__webpack_imported_module_0___default = /*#__pure__*/__webpack_require__.n(events__webpack_imported_module_0__); /* harmony import */ var _player_events_js__webpack_imported_module_1__ = __webpack_require__(/*! ./player-events.js */ "./src/player/player-events.js"); /* harmony import */ var _config_js__webpack_imported_module_2__ = __webpack_require__(/*! ../config.js */ "./src/config.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_3__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ // player wrapper for browser's native player (htmlvideoelement) without mediasource src. var nativeplayer = /** @class */ (function () { function nativeplayer(mediadatasource, config) { this.tag = 'nativeplayer'; this._type = 'nativeplayer'; this._emitter = new (events__webpack_imported_module_0___default())(); this._config = (0,_config_js__webpack_imported_module_2__.createdefaultconfig)(); if (typeof config === 'object') { object.assign(this._config, config); } if (mediadatasource.type.tolowercase() === 'flv') { throw new _utils_exception_js__webpack_imported_module_3__.invalidargumentexception('nativeplayer does\'t support flv mediadatasource input!'); } if (mediadatasource.hasownproperty('segments')) { throw new _utils_exception_js__webpack_imported_module_3__.invalidargumentexception("nativeplayer(" + mediadatasource.type + ") doesn't support multipart playback!"); } this.e = { onvloadedmetadata: this._onvloadedmetadata.bind(this) }; this._pendingseektime = null; this._statisticsreporter = null; this._mediadatasource = mediadatasource; this._mediaelement = null; } nativeplayer.prototype.destroy = function () { if (this._mediaelement) { this.unload(); this.detachmediaelement(); } this.e = null; this._mediadatasource = null; this._emitter.removealllisteners(); this._emitter = null; }; nativeplayer.prototype.on = function (event, listener) { var _this = this; if (event === _player_events_js__webpack_imported_module_1__.default.media_info) { if (this._mediaelement != null && this._mediaelement.readystate !== 0) { // have_nothing promise.resolve().then(function () { _this._emitter.emit(_player_events_js__webpack_imported_module_1__.default.media_info, _this.mediainfo); }); } } else if (event === _player_events_js__webpack_imported_module_1__.default.statistics_info) { if (this._mediaelement != null && this._mediaelement.readystate !== 0) { promise.resolve().then(function () { _this._emitter.emit(_player_events_js__webpack_imported_module_1__.default.statistics_info, _this.statisticsinfo); }); } } this._emitter.addlistener(event, listener); }; nativeplayer.prototype.off = function (event, listener) { this._emitter.removelistener(event, listener); }; nativeplayer.prototype.attachmediaelement = function (mediaelement) { this._mediaelement = mediaelement; mediaelement.addeventlistener('loadedmetadata', this.e.onvloadedmetadata); if (this._pendingseektime != null) { try { mediaelement.currenttime = this._pendingseektime; this._pendingseektime = null; } catch (e) { // ie11 may throw invalidstateerror if readystate === 0 // defer set currenttime operation after loadedmetadata } } }; nativeplayer.prototype.detachmediaelement = function () { if (this._mediaelement) { this._mediaelement.src = ''; this._mediaelement.removeattribute('src'); this._mediaelement.removeeventlistener('loadedmetadata', this.e.onvloadedmetadata); this._mediaelement = null; } if (this._statisticsreporter != null) { window.clearinterval(this._statisticsreporter); this._statisticsreporter = null; } }; nativeplayer.prototype.load = function () { if (!this._mediaelement) { throw new _utils_exception_js__webpack_imported_module_3__.illegalstateexception('htmlmediaelement must be attached before load()!'); } this._mediaelement.src = this._mediadatasource.url; if (this._mediaelement.readystate > 0) { this._mediaelement.currenttime = 0; } this._mediaelement.preload = 'auto'; this._mediaelement.load(); this._statisticsreporter = window.setinterval(this._reportstatisticsinfo.bind(this), this._config.statisticsinforeportinterval); }; nativeplayer.prototype.unload = function () { if (this._mediaelement) { this._mediaelement.src = ''; this._mediaelement.removeattribute('src'); } if (this._statisticsreporter != null) { window.clearinterval(this._statisticsreporter); this._statisticsreporter = null; } }; nativeplayer.prototype.play = function () { return this._mediaelement.play(); }; nativeplayer.prototype.pause = function () { this._mediaelement.pause(); }; object.defineproperty(nativeplayer.prototype, "type", { get: function () { return this._type; }, enumerable: false, configurable: true }); object.defineproperty(nativeplayer.prototype, "buffered", { get: function () { return this._mediaelement.buffered; }, enumerable: false, configurable: true }); object.defineproperty(nativeplayer.prototype, "duration", { get: function () { return this._mediaelement.duration; }, enumerable: false, configurable: true }); object.defineproperty(nativeplayer.prototype, "volume", { get: function () { return this._mediaelement.volume; }, set: function (value) { this._mediaelement.volume = value; }, enumerable: false, configurable: true }); object.defineproperty(nativeplayer.prototype, "muted", { get: function () { return this._mediaelement.muted; }, set: function (muted) { this._mediaelement.muted = muted; }, enumerable: false, configurable: true }); object.defineproperty(nativeplayer.prototype, "currenttime", { get: function () { if (this._mediaelement) { return this._mediaelement.currenttime; } return 0; }, set: function (seconds) { if (this._mediaelement) { this._mediaelement.currenttime = seconds; } else { this._pendingseektime = seconds; } }, enumerable: false, configurable: true }); object.defineproperty(nativeplayer.prototype, "mediainfo", { get: function () { var mediaprefix = (this._mediaelement instanceof htmlaudioelement) ? 'audio/' : 'video/'; var info = { mimetype: mediaprefix + this._mediadatasource.type }; if (this._mediaelement) { info.duration = math.floor(this._mediaelement.duration * 1000); if (this._mediaelement instanceof htmlvideoelement) { info.width = this._mediaelement.videowidth; info.height = this._mediaelement.videoheight; } } return info; }, enumerable: false, configurable: true }); object.defineproperty(nativeplayer.prototype, "statisticsinfo", { get: function () { var info = { playertype: this._type, url: this._mediadatasource.url }; if (!(this._mediaelement instanceof htmlvideoelement)) { return info; } var hasqualityinfo = true; var decoded = 0; var dropped = 0; if (this._mediaelement.getvideoplaybackquality) { var quality = this._mediaelement.getvideoplaybackquality(); decoded = quality.totalvideoframes; dropped = quality.droppedvideoframes; } else if (this._mediaelement.webkitdecodedframecount != undefined) { decoded = this._mediaelement.webkitdecodedframecount; dropped = this._mediaelement.webkitdroppedframecount; } else { hasqualityinfo = false; } if (hasqualityinfo) { info.decodedframes = decoded; info.droppedframes = dropped; } return info; }, enumerable: false, configurable: true }); nativeplayer.prototype._onvloadedmetadata = function (e) { if (this._pendingseektime != null) { this._mediaelement.currenttime = this._pendingseektime; this._pendingseektime = null; } this._emitter.emit(_player_events_js__webpack_imported_module_1__.default.media_info, this.mediainfo); }; nativeplayer.prototype._reportstatisticsinfo = function () { this._emitter.emit(_player_events_js__webpack_imported_module_1__.default.statistics_info, this.statisticsinfo); }; return nativeplayer; }()); /* harmony default export */ __webpack_exports__["default"] = (nativeplayer); /***/ }), /***/ "./src/player/player-errors.js": /*!*************************************!*\ !*** ./src/player/player-errors.js ***! \*************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "errortypes": function() { return /* binding */ errortypes; }, /* harmony export */ "errordetails": function() { return /* binding */ errordetails; } /* harmony export */ }); /* harmony import */ var _io_loader_js__webpack_imported_module_0__ = __webpack_require__(/*! ../io/loader.js */ "./src/io/loader.js"); /* harmony import */ var _demux_demux_errors_js__webpack_imported_module_1__ = __webpack_require__(/*! ../demux/demux-errors.js */ "./src/demux/demux-errors.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var errortypes = { network_error: 'networkerror', media_error: 'mediaerror', other_error: 'othererror' }; var errordetails = { network_exception: _io_loader_js__webpack_imported_module_0__.loadererrors.exception, network_status_code_invalid: _io_loader_js__webpack_imported_module_0__.loadererrors.http_status_code_invalid, network_timeout: _io_loader_js__webpack_imported_module_0__.loadererrors.connecting_timeout, network_unrecoverable_early_eof: _io_loader_js__webpack_imported_module_0__.loadererrors.unrecoverable_early_eof, media_mse_error: 'mediamseerror', media_format_error: _demux_demux_errors_js__webpack_imported_module_1__.default.format_error, media_format_unsupported: _demux_demux_errors_js__webpack_imported_module_1__.default.format_unsupported, media_codec_unsupported: _demux_demux_errors_js__webpack_imported_module_1__.default.codec_unsupported }; /***/ }), /***/ "./src/player/player-events.js": /*!*************************************!*\ !*** ./src/player/player-events.js ***! \*************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var playerevents = { error: 'error', loading_complete: 'loading_complete', recovered_early_eof: 'recovered_early_eof', media_info: 'media_info', metadata_arrived: 'metadata_arrived', scriptdata_arrived: 'scriptdata_arrived', statistics_info: 'statistics_info' }; /* harmony default export */ __webpack_exports__["default"] = (playerevents); /***/ }), /***/ "./src/remux/aac-silent.js": /*!*********************************!*\ !*** ./src/remux/aac-silent.js ***! \*********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * this file is modified from dailymotion's hls.js library (hls.js/src/helper/aac.js) * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var aac = /** @class */ (function () { function aac() { } aac.getsilentframe = function (codec, channelcount) { if (codec === 'mp4a.40.2') { // handle lc-aac if (channelcount === 1) { return new uint8array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]); } else if (channelcount === 2) { return new uint8array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]); } else if (channelcount === 3) { return new uint8array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]); } else if (channelcount === 4) { return new uint8array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]); } else if (channelcount === 5) { return new uint8array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]); } else if (channelcount === 6) { return new uint8array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]); } } else { // handle he-aac (mp4a.40.5 / mp4a.40.29) if (channelcount === 1) { // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac return new uint8array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); } else if (channelcount === 2) { // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac return new uint8array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); } else if (channelcount === 3) { // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac return new uint8array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); } } return null; }; return aac; }()); /* harmony default export */ __webpack_exports__["default"] = (aac); /***/ }), /***/ "./src/remux/mp4-generator.js": /*!************************************!*\ !*** ./src/remux/mp4-generator.js ***! \************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * this file is derived from dailymotion's hls.js library (hls.js/src/remux/mp4-generator.js) * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ // mp4 boxes generator for iso bmff (iso base media file format, defined in iso/iec 14496-12) var mp4 = /** @class */ (function () { function mp4() { } mp4.init = function () { mp4.types = { avc1: [], avcc: [], btrt: [], dinf: [], dref: [], esds: [], ftyp: [], hdlr: [], mdat: [], mdhd: [], mdia: [], mfhd: [], minf: [], moof: [], moov: [], mp4a: [], mvex: [], mvhd: [], sdtp: [], stbl: [], stco: [], stsc: [], stsd: [], stsz: [], stts: [], tfdt: [], tfhd: [], traf: [], trak: [], trun: [], trex: [], tkhd: [], vmhd: [], smhd: [], '.mp3': [] }; for (var name_1 in mp4.types) { if (mp4.types.hasownproperty(name_1)) { mp4.types[name_1] = [ name_1.charcodeat(0), name_1.charcodeat(1), name_1.charcodeat(2), name_1.charcodeat(3) ]; } } var constants = mp4.constants = {}; constants.ftyp = new uint8array([ 0x69, 0x73, 0x6f, 0x6d, 0x0, 0x0, 0x0, 0x1, 0x69, 0x73, 0x6f, 0x6d, 0x61, 0x76, 0x63, 0x31 // avc1 ]); constants.stsd_prefix = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 // entry_count ]); constants.stts = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // entry_count ]); constants.stsc = constants.stco = constants.stts; constants.stsz = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // sample_count ]); constants.hdlr_video = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x64, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: videohandler ]); constants.hdlr_audio = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x6f, 0x75, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: soundhandler ]); constants.dref = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x75, 0x72, 0x6c, 0x20, 0x00, 0x00, 0x00, 0x01 // version(0) + flags ]); // sound media header constants.smhd = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // balance(2) + reserved(2) ]); // video media header constants.vmhd = new uint8array([ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ]); }; // generate a box mp4.box = function (type) { var size = 8; var result = null; var datas = array.prototype.slice.call(arguments, 1); var arraycount = datas.length; for (var i = 0; i < arraycount; i++) { size += datas[i].bytelength; } result = new uint8array(size); result[0] = (size >>> 24) & 0xff; // size result[1] = (size >>> 16) & 0xff; result[2] = (size >>> 8) & 0xff; result[3] = (size) & 0xff; result.set(type, 4); // type var offset = 8; for (var i = 0; i < arraycount; i++) { // data body result.set(datas[i], offset); offset += datas[i].bytelength; } return result; }; // emit ftyp & moov mp4.generateinitsegment = function (meta) { var ftyp = mp4.box(mp4.types.ftyp, mp4.constants.ftyp); var moov = mp4.moov(meta); var result = new uint8array(ftyp.bytelength + moov.bytelength); result.set(ftyp, 0); result.set(moov, ftyp.bytelength); return result; }; // movie metadata box mp4.moov = function (meta) { var mvhd = mp4.mvhd(meta.timescale, meta.duration); var trak = mp4.trak(meta); var mvex = mp4.mvex(meta); return mp4.box(mp4.types.moov, mvhd, trak, mvex); }; // movie header box mp4.mvhd = function (timescale, duration) { return mp4.box(mp4.types.mvhd, new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (timescale >>> 24) & 0xff, (timescale >>> 16) & 0xff, (timescale >>> 8) & 0xff, (timescale) & 0xff, (duration >>> 24) & 0xff, (duration >>> 16) & 0xff, (duration >>> 8) & 0xff, (duration) & 0xff, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff // next_track_id ])); }; // track box mp4.trak = function (meta) { return mp4.box(mp4.types.trak, mp4.tkhd(meta), mp4.mdia(meta)); }; // track header box mp4.tkhd = function (meta) { var trackid = meta.id, duration = meta.duration; var width = meta.presentwidth, height = meta.presentheight; return mp4.box(mp4.types.tkhd, new uint8array([ 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (trackid >>> 24) & 0xff, (trackid >>> 16) & 0xff, (trackid >>> 8) & 0xff, (trackid) & 0xff, 0x00, 0x00, 0x00, 0x00, (duration >>> 24) & 0xff, (duration >>> 16) & 0xff, (duration >>> 8) & 0xff, (duration) & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, (width >>> 8) & 0xff, (width) & 0xff, 0x00, 0x00, (height >>> 8) & 0xff, (height) & 0xff, 0x00, 0x00 ])); }; // media box mp4.mdia = function (meta) { return mp4.box(mp4.types.mdia, mp4.mdhd(meta), mp4.hdlr(meta), mp4.minf(meta)); }; // media header box mp4.mdhd = function (meta) { var timescale = meta.timescale; var duration = meta.duration; return mp4.box(mp4.types.mdhd, new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (timescale >>> 24) & 0xff, (timescale >>> 16) & 0xff, (timescale >>> 8) & 0xff, (timescale) & 0xff, (duration >>> 24) & 0xff, (duration >>> 16) & 0xff, (duration >>> 8) & 0xff, (duration) & 0xff, 0x55, 0xc4, 0x00, 0x00 // pre_defined = 0 ])); }; // media handler reference box mp4.hdlr = function (meta) { var data = null; if (meta.type === 'audio') { data = mp4.constants.hdlr_audio; } else { data = mp4.constants.hdlr_video; } return mp4.box(mp4.types.hdlr, data); }; // media infomation box mp4.minf = function (meta) { var xmhd = null; if (meta.type === 'audio') { xmhd = mp4.box(mp4.types.smhd, mp4.constants.smhd); } else { xmhd = mp4.box(mp4.types.vmhd, mp4.constants.vmhd); } return mp4.box(mp4.types.minf, xmhd, mp4.dinf(), mp4.stbl(meta)); }; // data infomation box mp4.dinf = function () { var result = mp4.box(mp4.types.dinf, mp4.box(mp4.types.dref, mp4.constants.dref)); return result; }; // sample table box mp4.stbl = function (meta) { var result = mp4.box(mp4.types.stbl, // type: stbl mp4.stsd(meta), // sample description table mp4.box(mp4.types.stts, mp4.constants.stts), // time-to-sample mp4.box(mp4.types.stsc, mp4.constants.stsc), // sample-to-chunk mp4.box(mp4.types.stsz, mp4.constants.stsz), // sample size mp4.box(mp4.types.stco, mp4.constants.stco) // chunk offset ); return result; }; // sample description box mp4.stsd = function (meta) { if (meta.type === 'audio') { if (meta.codec === 'mp3') { return mp4.box(mp4.types.stsd, mp4.constants.stsd_prefix, mp4.mp3(meta)); } // else: aac -> mp4a return mp4.box(mp4.types.stsd, mp4.constants.stsd_prefix, mp4.mp4a(meta)); } else { return mp4.box(mp4.types.stsd, mp4.constants.stsd_prefix, mp4.avc1(meta)); } }; mp4.mp3 = function (meta) { var channelcount = meta.channelcount; var samplerate = meta.audiosamplerate; var data = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, channelcount, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, (samplerate >>> 8) & 0xff, (samplerate) & 0xff, 0x00, 0x00 ]); return mp4.box(mp4.types['.mp3'], data); }; mp4.mp4a = function (meta) { var channelcount = meta.channelcount; var samplerate = meta.audiosamplerate; var data = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, channelcount, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, (samplerate >>> 8) & 0xff, (samplerate) & 0xff, 0x00, 0x00 ]); return mp4.box(mp4.types.mp4a, data, mp4.esds(meta)); }; mp4.esds = function (meta) { var config = meta.config || []; var configsize = config.length; var data = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x03, 0x17 + configsize, 0x00, 0x01, 0x00, 0x04, 0x0f + configsize, 0x40, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05 // descriptor_type ].concat([ configsize ]).concat(config).concat([ 0x06, 0x01, 0x02 // gaspecificconfig ])); return mp4.box(mp4.types.esds, data); }; mp4.avc1 = function (meta) { var avcc = meta.avcc; var width = meta.codecwidth, height = meta.codecheight; var data = new uint8array([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (width >>> 8) & 0xff, (width) & 0xff, (height >>> 8) & 0xff, (height) & 0xff, 0x00, 0x48, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0a, 0x78, 0x71, 0x71, 0x2f, 0x66, 0x6c, 0x76, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0xff, 0xff // pre_defined = -1 ]); return mp4.box(mp4.types.avc1, data, mp4.box(mp4.types.avcc, avcc)); }; // movie extends box mp4.mvex = function (meta) { return mp4.box(mp4.types.mvex, mp4.trex(meta)); }; // track extends box mp4.trex = function (meta) { var trackid = meta.id; var data = new uint8array([ 0x00, 0x00, 0x00, 0x00, (trackid >>> 24) & 0xff, (trackid >>> 16) & 0xff, (trackid >>> 8) & 0xff, (trackid) & 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01 // default_sample_flags ]); return mp4.box(mp4.types.trex, data); }; // movie fragment box mp4.moof = function (track, basemediadecodetime) { return mp4.box(mp4.types.moof, mp4.mfhd(track.sequencenumber), mp4.traf(track, basemediadecodetime)); }; mp4.mfhd = function (sequencenumber) { var data = new uint8array([ 0x00, 0x00, 0x00, 0x00, (sequencenumber >>> 24) & 0xff, (sequencenumber >>> 16) & 0xff, (sequencenumber >>> 8) & 0xff, (sequencenumber) & 0xff ]); return mp4.box(mp4.types.mfhd, data); }; // track fragment box mp4.traf = function (track, basemediadecodetime) { var trackid = track.id; // track fragment header box var tfhd = mp4.box(mp4.types.tfhd, new uint8array([ 0x00, 0x00, 0x00, 0x00, (trackid >>> 24) & 0xff, (trackid >>> 16) & 0xff, (trackid >>> 8) & 0xff, (trackid) & 0xff ])); // track fragment decode time var tfdt = mp4.box(mp4.types.tfdt, new uint8array([ 0x00, 0x00, 0x00, 0x00, (basemediadecodetime >>> 24) & 0xff, (basemediadecodetime >>> 16) & 0xff, (basemediadecodetime >>> 8) & 0xff, (basemediadecodetime) & 0xff ])); var sdtp = mp4.sdtp(track); var trun = mp4.trun(track, sdtp.bytelength + 16 + 16 + 8 + 16 + 8 + 8); return mp4.box(mp4.types.traf, tfhd, tfdt, trun, sdtp); }; // sample dependency type box mp4.sdtp = function (track) { var samples = track.samples || []; var samplecount = samples.length; var data = new uint8array(4 + samplecount); // 0~4 bytes: version(0) & flags for (var i = 0; i < samplecount; i++) { var flags = samples[i].flags; data[i + 4] = (flags.isleading << 6) // is_leading: 2 (bit) | (flags.dependson << 4) // sample_depends_on | (flags.isdependedon << 2) // sample_is_depended_on | (flags.hasredundancy); // sample_has_redundancy } return mp4.box(mp4.types.sdtp, data); }; // track fragment run box mp4.trun = function (track, offset) { var samples = track.samples || []; var samplecount = samples.length; var datasize = 12 + 16 * samplecount; var data = new uint8array(datasize); offset += 8 + datasize; data.set([ 0x00, 0x00, 0x0f, 0x01, (samplecount >>> 24) & 0xff, (samplecount >>> 16) & 0xff, (samplecount >>> 8) & 0xff, (samplecount) & 0xff, (offset >>> 24) & 0xff, (offset >>> 16) & 0xff, (offset >>> 8) & 0xff, (offset) & 0xff ], 0); for (var i = 0; i < samplecount; i++) { var duration = samples[i].duration; var size = samples[i].size; var flags = samples[i].flags; var cts = samples[i].cts; data.set([ (duration >>> 24) & 0xff, (duration >>> 16) & 0xff, (duration >>> 8) & 0xff, (duration) & 0xff, (size >>> 24) & 0xff, (size >>> 16) & 0xff, (size >>> 8) & 0xff, (size) & 0xff, (flags.isleading << 2) | flags.dependson, (flags.isdependedon << 6) | (flags.hasredundancy << 4) | flags.isnonsync, 0x00, 0x00, (cts >>> 24) & 0xff, (cts >>> 16) & 0xff, (cts >>> 8) & 0xff, (cts) & 0xff ], 12 + 16 * i); } return mp4.box(mp4.types.trun, data); }; mp4.mdat = function (data) { return mp4.box(mp4.types.mdat, data); }; return mp4; }()); mp4.init(); /* harmony default export */ __webpack_exports__["default"] = (mp4); /***/ }), /***/ "./src/remux/mp4-remuxer.js": /*!**********************************!*\ !*** ./src/remux/mp4-remuxer.js ***! \**********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_logger_js__webpack_imported_module_0__ = __webpack_require__(/*! ../utils/logger.js */ "./src/utils/logger.js"); /* harmony import */ var _mp4_generator_js__webpack_imported_module_1__ = __webpack_require__(/*! ./mp4-generator.js */ "./src/remux/mp4-generator.js"); /* harmony import */ var _aac_silent_js__webpack_imported_module_2__ = __webpack_require__(/*! ./aac-silent.js */ "./src/remux/aac-silent.js"); /* harmony import */ var _utils_browser_js__webpack_imported_module_3__ = __webpack_require__(/*! ../utils/browser.js */ "./src/utils/browser.js"); /* harmony import */ var _core_media_segment_info_js__webpack_imported_module_4__ = __webpack_require__(/*! ../core/media-segment-info.js */ "./src/core/media-segment-info.js"); /* harmony import */ var _utils_exception_js__webpack_imported_module_5__ = __webpack_require__(/*! ../utils/exception.js */ "./src/utils/exception.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ // fragmented mp4 remuxer var mp4remuxer = /** @class */ (function () { function mp4remuxer(config) { this.tag = 'mp4remuxer'; this._config = config; this._islive = (config.islive === true) ? true : false; this._dtsbase = -1; this._dtsbaseinited = false; this._audiodtsbase = infinity; this._videodtsbase = infinity; this._audionextdts = undefined; this._videonextdts = undefined; this._audiostashedlastsample = null; this._videostashedlastsample = null; this._audiometa = null; this._videometa = null; this._audiosegmentinfolist = new _core_media_segment_info_js__webpack_imported_module_4__.mediasegmentinfolist('audio'); this._videosegmentinfolist = new _core_media_segment_info_js__webpack_imported_module_4__.mediasegmentinfolist('video'); this._oninitsegment = null; this._onmediasegment = null; // workaround for chrome < 50: always force first sample as a random access point in media segment // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412 this._forcefirstidr = (_utils_browser_js__webpack_imported_module_3__.default.chrome && (_utils_browser_js__webpack_imported_module_3__.default.version.major < 50 || (_utils_browser_js__webpack_imported_module_3__.default.version.major === 50 && _utils_browser_js__webpack_imported_module_3__.default.version.build < 2661))) ? true : false; // workaround for ie11/edge: fill silent aac frame after keyframe-seeking // make audio begindts equals with video begindts, in order to fix seek freeze this._fillsilentafterseek = (_utils_browser_js__webpack_imported_module_3__.default.msedge || _utils_browser_js__webpack_imported_module_3__.default.msie); // while only firefox supports 'audio/mp4, codecs="mp3"', use 'audio/mpeg' for chrome, safari, ... this._mp3usempegaudio = !_utils_browser_js__webpack_imported_module_3__.default.firefox; this._fillaudiotimestampgap = this._config.fixaudiotimestampgap; } mp4remuxer.prototype.destroy = function () { this._dtsbase = -1; this._dtsbaseinited = false; this._audiometa = null; this._videometa = null; this._audiosegmentinfolist.clear(); this._audiosegmentinfolist = null; this._videosegmentinfolist.clear(); this._videosegmentinfolist = null; this._oninitsegment = null; this._onmediasegment = null; }; mp4remuxer.prototype.binddatasource = function (producer) { producer.ondataavailable = this.remux.bind(this); producer.ontrackmetadata = this._ontrackmetadatareceived.bind(this); return this; }; object.defineproperty(mp4remuxer.prototype, "oninitsegment", { /* prototype: function oninitsegment(type: string, initsegment: arraybuffer): void initsegment: { type: string, data: arraybuffer, codec: string, container: string } */ get: function () { return this._oninitsegment; }, set: function (callback) { this._oninitsegment = callback; }, enumerable: false, configurable: true }); object.defineproperty(mp4remuxer.prototype, "onmediasegment", { /* prototype: function onmediasegment(type: string, mediasegment: mediasegment): void mediasegment: { type: string, data: arraybuffer, samplecount: int32 info: mediasegmentinfo } */ get: function () { return this._onmediasegment; }, set: function (callback) { this._onmediasegment = callback; }, enumerable: false, configurable: true }); mp4remuxer.prototype.insertdiscontinuity = function () { this._audionextdts = this._videonextdts = undefined; }; mp4remuxer.prototype.seek = function (originaldts) { this._audiostashedlastsample = null; this._videostashedlastsample = null; this._videosegmentinfolist.clear(); this._audiosegmentinfolist.clear(); }; mp4remuxer.prototype.remux = function (audiotrack, videotrack) { if (!this._onmediasegment) { throw new _utils_exception_js__webpack_imported_module_5__.illegalstateexception('mp4remuxer: onmediasegment callback must be specificed!'); } if (!this._dtsbaseinited) { this._calculatedtsbase(audiotrack, videotrack); } this._remuxvideo(videotrack); this._remuxaudio(audiotrack); }; mp4remuxer.prototype._ontrackmetadatareceived = function (type, metadata) { var metabox = null; var container = 'mp4'; var codec = metadata.codec; if (type === 'audio') { this._audiometa = metadata; if (metadata.codec === 'mp3' && this._mp3usempegaudio) { // 'audio/mpeg' for mp3 audio track container = 'mpeg'; codec = ''; metabox = new uint8array(); } else { // 'audio/mp4, codecs="codec"' metabox = _mp4_generator_js__webpack_imported_module_1__.default.generateinitsegment(metadata); } } else if (type === 'video') { this._videometa = metadata; metabox = _mp4_generator_js__webpack_imported_module_1__.default.generateinitsegment(metadata); } else { return; } // dispatch metabox (initialization segment) if (!this._oninitsegment) { throw new _utils_exception_js__webpack_imported_module_5__.illegalstateexception('mp4remuxer: oninitsegment callback must be specified!'); } this._oninitsegment(type, { type: type, data: metabox.buffer, codec: codec, container: type + "/" + container, mediaduration: metadata.duration // in timescale 1000 (milliseconds) }); }; mp4remuxer.prototype._calculatedtsbase = function (audiotrack, videotrack) { if (this._dtsbaseinited) { return; } if (audiotrack.samples && audiotrack.samples.length) { this._audiodtsbase = audiotrack.samples[0].dts; } if (videotrack.samples && videotrack.samples.length) { this._videodtsbase = videotrack.samples[0].dts; } this._dtsbase = math.min(this._audiodtsbase, this._videodtsbase); this._dtsbaseinited = true; }; mp4remuxer.prototype.flushstashedsamples = function () { var videosample = this._videostashedlastsample; var audiosample = this._audiostashedlastsample; var videotrack = { type: 'video', id: 1, sequencenumber: 0, samples: [], length: 0 }; if (videosample != null) { videotrack.samples.push(videosample); videotrack.length = videosample.length; } var audiotrack = { type: 'audio', id: 2, sequencenumber: 0, samples: [], length: 0 }; if (audiosample != null) { audiotrack.samples.push(audiosample); audiotrack.length = audiosample.length; } this._videostashedlastsample = null; this._audiostashedlastsample = null; this._remuxvideo(videotrack, true); this._remuxaudio(audiotrack, true); }; mp4remuxer.prototype._remuxaudio = function (audiotrack, force) { if (this._audiometa == null) { return; } var track = audiotrack; var samples = track.samples; var dtscorrection = undefined; var firstdts = -1, lastdts = -1, lastpts = -1; var refsampleduration = this._audiometa.refsampleduration; var mpegrawtrack = this._audiometa.codec === 'mp3' && this._mp3usempegaudio; var firstsegmentafterseek = this._dtsbaseinited && this._audionextdts === undefined; var insertprefixsilentframe = false; if (!samples || samples.length === 0) { return; } if (samples.length === 1 && !force) { // if [sample count in current batch] === 1 && (force != true) // ignore and keep in demuxer's queue return; } // else if (force === true) do remux var offset = 0; var mdatbox = null; var mdatbytes = 0; // calculate initial mdat size if (mpegrawtrack) { // for raw mpeg buffer offset = 0; mdatbytes = track.length; } else { // for fmp4 mdat box offset = 8; // size + type mdatbytes = 8 + track.length; } var lastsample = null; // pop the lastsample and waiting for stash if (samples.length > 1) { lastsample = samples.pop(); mdatbytes -= lastsample.length; } // insert [stashed lastsample in the previous batch] to the front if (this._audiostashedlastsample != null) { var sample = this._audiostashedlastsample; this._audiostashedlastsample = null; samples.unshift(sample); mdatbytes += sample.length; } // stash the lastsample of current batch, waiting for next batch if (lastsample != null) { this._audiostashedlastsample = lastsample; } var firstsampleoriginaldts = samples[0].dts - this._dtsbase; // calculate dtscorrection if (this._audionextdts) { dtscorrection = firstsampleoriginaldts - this._audionextdts; } else { // this._audionextdts == undefined if (this._audiosegmentinfolist.isempty()) { dtscorrection = 0; if (this._fillsilentafterseek && !this._videosegmentinfolist.isempty()) { if (this._audiometa.originalcodec !== 'mp3') { insertprefixsilentframe = true; } } } else { var lastsample_1 = this._audiosegmentinfolist.getlastsamplebefore(firstsampleoriginaldts); if (lastsample_1 != null) { var distance = (firstsampleoriginaldts - (lastsample_1.originaldts + lastsample_1.duration)); if (distance <= 3) { distance = 0; } var expecteddts = lastsample_1.dts + lastsample_1.duration + distance; dtscorrection = firstsampleoriginaldts - expecteddts; } else { // lastsample == null, cannot found dtscorrection = 0; } } } if (insertprefixsilentframe) { // align audio segment begindts to match with current video segment's begindts var firstsampledts = firstsampleoriginaldts - dtscorrection; var videosegment = this._videosegmentinfolist.getlastsegmentbefore(firstsampleoriginaldts); if (videosegment != null && videosegment.begindts < firstsampledts) { var silentunit = _aac_silent_js__webpack_imported_module_2__.default.getsilentframe(this._audiometa.originalcodec, this._audiometa.channelcount); if (silentunit) { var dts = videosegment.begindts; var silentframeduration = firstsampledts - videosegment.begindts; _utils_logger_js__webpack_imported_module_0__.default.v(this.tag, "insertprefixsilentaudio: dts: " + dts + ", duration: " + silentframeduration); samples.unshift({ unit: silentunit, dts: dts, pts: dts }); mdatbytes += silentunit.bytelength; } // silentunit == null: cannot generate, skip } else { insertprefixsilentframe = false; } } var mp4samples = []; // correct dts for each sample, and calculate sample duration. then output to mp4samples for (var i = 0; i < samples.length; i++) { var sample = samples[i]; var unit = sample.unit; var originaldts = sample.dts - this._dtsbase; var dts = originaldts; var needfillsilentframes = false; var silentframes = null; var sampleduration = 0; if (originaldts < -0.001) { continue; //pass the first sample with the invalid dts } if (this._audiometa.codec !== 'mp3') { // for aac codec, we need to keep dts increase based on refsampleduration var currefdts = originaldts; var maxaudioframesdrift = 3; if (this._audionextdts) { currefdts = this._audionextdts; } dtscorrection = originaldts - currefdts; if (dtscorrection <= -maxaudioframesdrift * refsampleduration) { // if we're overlapping by more than maxaudioframesdrift number of frame, drop this sample _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, "dropping 1 audio frame (originaldts: " + originaldts + " ms ,currefdts: " + currefdts + " ms) due to dtscorrection: " + dtscorrection + " ms overlap."); continue; } else if (dtscorrection >= maxaudioframesdrift * refsampleduration && this._fillaudiotimestampgap && !_utils_browser_js__webpack_imported_module_3__.default.safari) { // silent frame generation, if large timestamp gap detected && config.fixaudiotimestampgap needfillsilentframes = true; // we need to insert silent frames to fill timestamp gap var framecount = math.floor(dtscorrection / refsampleduration); _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'large audio timestamp gap detected, may cause av sync to drift. ' + 'silent frames will be generated to avoid unsync.\n' + ("originaldts: " + originaldts + " ms, currefdts: " + currefdts + " ms, ") + ("dtscorrection: " + math.round(dtscorrection) + " ms, generate: " + framecount + " frames")); dts = math.floor(currefdts); sampleduration = math.floor(currefdts + refsampleduration) - dts; var silentunit = _aac_silent_js__webpack_imported_module_2__.default.getsilentframe(this._audiometa.originalcodec, this._audiometa.channelcount); if (silentunit == null) { _utils_logger_js__webpack_imported_module_0__.default.w(this.tag, 'unable to generate silent frame for ' + (this._audiometa.originalcodec + " with " + this._audiometa.channelcount + " channels, repeat last frame")); // repeat last frame silentunit = unit; } silentframes = []; for (var j = 0; j < framecount; j++) { currefdts = currefdts + refsampleduration; var intdts = math.floor(currefdts); // change to integer var intduration = math.floor(currefdts + refsampleduration) - intdts; var frame = { dts: intdts, pts: intdts, cts: 0, unit: silentunit, size: silentunit.bytelength, duration: intduration, originaldts: originaldts, flags: { isleading: 0, dependson: 1, isdependedon: 0, hasredundancy: 0 } }; silentframes.push(frame); mdatbytes += frame.size; ; } this._audionextdts = currefdts + refsampleduration; } else { dts = math.floor(currefdts); sampleduration = math.floor(currefdts + refsampleduration) - dts; this._audionextdts = currefdts + refsampleduration; } } else { // keep the original dts calculate algorithm for mp3 dts = originaldts - dtscorrection; if (i !== samples.length - 1) { var nextdts = samples[i + 1].dts - this._dtsbase - dtscorrection; sampleduration = nextdts - dts; } else { // the last sample if (lastsample != null) { // use stashed sample's dts to calculate sample duration var nextdts = lastsample.dts - this._dtsbase - dtscorrection; sampleduration = nextdts - dts; } else if (mp4samples.length >= 1) { // use second last sample duration sampleduration = mp4samples[mp4samples.length - 1].duration; } else { // the only one sample, use reference sample duration sampleduration = math.floor(refsampleduration); } } this._audionextdts = dts + sampleduration; } if (firstdts === -1) { firstdts = dts; } mp4samples.push({ dts: dts, pts: dts, cts: 0, unit: sample.unit, size: sample.unit.bytelength, duration: sampleduration, originaldts: originaldts, flags: { isleading: 0, dependson: 1, isdependedon: 0, hasredundancy: 0 } }); if (needfillsilentframes) { // silent frames should be inserted after wrong-duration frame mp4samples.push.apply(mp4samples, silentframes); } } if (mp4samples.length === 0) { //no samples need to remux track.samples = []; track.length = 0; return; } // allocate mdatbox if (mpegrawtrack) { // allocate for raw mpeg buffer mdatbox = new uint8array(mdatbytes); } else { // allocate for fmp4 mdat box mdatbox = new uint8array(mdatbytes); // size field mdatbox[0] = (mdatbytes >>> 24) & 0xff; mdatbox[1] = (mdatbytes >>> 16) & 0xff; mdatbox[2] = (mdatbytes >>> 8) & 0xff; mdatbox[3] = (mdatbytes) & 0xff; // type field (fourcc) mdatbox.set(_mp4_generator_js__webpack_imported_module_1__.default.types.mdat, 4); } // write samples into mdatbox for (var i = 0; i < mp4samples.length; i++) { var unit = mp4samples[i].unit; mdatbox.set(unit, offset); offset += unit.bytelength; } var latest = mp4samples[mp4samples.length - 1]; lastdts = latest.dts + latest.duration; //this._audionextdts = lastdts; // fill media segment info & add to info list var info = new _core_media_segment_info_js__webpack_imported_module_4__.mediasegmentinfo(); info.begindts = firstdts; info.enddts = lastdts; info.beginpts = firstdts; info.endpts = lastdts; info.originalbegindts = mp4samples[0].originaldts; info.originalenddts = latest.originaldts + latest.duration; info.firstsample = new _core_media_segment_info_js__webpack_imported_module_4__.sampleinfo(mp4samples[0].dts, mp4samples[0].pts, mp4samples[0].duration, mp4samples[0].originaldts, false); info.lastsample = new _core_media_segment_info_js__webpack_imported_module_4__.sampleinfo(latest.dts, latest.pts, latest.duration, latest.originaldts, false); if (!this._islive) { this._audiosegmentinfolist.append(info); } track.samples = mp4samples; track.sequencenumber++; var moofbox = null; if (mpegrawtrack) { // generate empty buffer, because useless for raw mpeg moofbox = new uint8array(); } else { // generate moof for fmp4 segment moofbox = _mp4_generator_js__webpack_imported_module_1__.default.moof(track, firstdts); } track.samples = []; track.length = 0; var segment = { type: 'audio', data: this._mergeboxes(moofbox, mdatbox).buffer, samplecount: mp4samples.length, info: info }; if (mpegrawtrack && firstsegmentafterseek) { // for mpeg audio stream in mse, if seeking occurred, before appending new buffer // we need explicitly set timestampoffset to the desired point in timeline for mpeg sourcebuffer. segment.timestampoffset = firstdts; } this._onmediasegment('audio', segment); }; mp4remuxer.prototype._remuxvideo = function (videotrack, force) { if (this._videometa == null) { return; } var track = videotrack; var samples = track.samples; var dtscorrection = undefined; var firstdts = -1, lastdts = -1; var firstpts = -1, lastpts = -1; if (!samples || samples.length === 0) { return; } if (samples.length === 1 && !force) { // if [sample count in current batch] === 1 && (force != true) // ignore and keep in demuxer's queue return; } // else if (force === true) do remux var offset = 8; var mdatbox = null; var mdatbytes = 8 + videotrack.length; var lastsample = null; // pop the lastsample and waiting for stash if (samples.length > 1) { lastsample = samples.pop(); mdatbytes -= lastsample.length; } // insert [stashed lastsample in the previous batch] to the front if (this._videostashedlastsample != null) { var sample = this._videostashedlastsample; this._videostashedlastsample = null; samples.unshift(sample); mdatbytes += sample.length; } // stash the lastsample of current batch, waiting for next batch if (lastsample != null) { this._videostashedlastsample = lastsample; } var firstsampleoriginaldts = samples[0].dts - this._dtsbase; // calculate dtscorrection if (this._videonextdts) { dtscorrection = firstsampleoriginaldts - this._videonextdts; } else { // this._videonextdts == undefined if (this._videosegmentinfolist.isempty()) { dtscorrection = 0; } else { var lastsample_2 = this._videosegmentinfolist.getlastsamplebefore(firstsampleoriginaldts); if (lastsample_2 != null) { var distance = (firstsampleoriginaldts - (lastsample_2.originaldts + lastsample_2.duration)); if (distance <= 3) { distance = 0; } var expecteddts = lastsample_2.dts + lastsample_2.duration + distance; dtscorrection = firstsampleoriginaldts - expecteddts; } else { // lastsample == null, cannot found dtscorrection = 0; } } } var info = new _core_media_segment_info_js__webpack_imported_module_4__.mediasegmentinfo(); var mp4samples = []; // correct dts for each sample, and calculate sample duration. then output to mp4samples for (var i = 0; i < samples.length; i++) { var sample = samples[i]; var originaldts = sample.dts - this._dtsbase; var iskeyframe = sample.iskeyframe; var dts = originaldts - dtscorrection; var cts = sample.cts; var pts = dts + cts; if (firstdts === -1) { firstdts = dts; firstpts = pts; } var sampleduration = 0; if (i !== samples.length - 1) { var nextdts = samples[i + 1].dts - this._dtsbase - dtscorrection; sampleduration = nextdts - dts; } else { // the last sample if (lastsample != null) { // use stashed sample's dts to calculate sample duration var nextdts = lastsample.dts - this._dtsbase - dtscorrection; sampleduration = nextdts - dts; } else if (mp4samples.length >= 1) { // use second last sample duration sampleduration = mp4samples[mp4samples.length - 1].duration; } else { // the only one sample, use reference sample duration sampleduration = math.floor(this._videometa.refsampleduration); } } if (iskeyframe) { var syncpoint = new _core_media_segment_info_js__webpack_imported_module_4__.sampleinfo(dts, pts, sampleduration, sample.dts, true); syncpoint.fileposition = sample.fileposition; info.appendsyncpoint(syncpoint); } mp4samples.push({ dts: dts, pts: pts, cts: cts, units: sample.units, size: sample.length, iskeyframe: iskeyframe, duration: sampleduration, originaldts: originaldts, flags: { isleading: 0, dependson: iskeyframe ? 2 : 1, isdependedon: iskeyframe ? 1 : 0, hasredundancy: 0, isnonsync: iskeyframe ? 0 : 1 } }); } // allocate mdatbox mdatbox = new uint8array(mdatbytes); mdatbox[0] = (mdatbytes >>> 24) & 0xff; mdatbox[1] = (mdatbytes >>> 16) & 0xff; mdatbox[2] = (mdatbytes >>> 8) & 0xff; mdatbox[3] = (mdatbytes) & 0xff; mdatbox.set(_mp4_generator_js__webpack_imported_module_1__.default.types.mdat, 4); // write samples into mdatbox for (var i = 0; i < mp4samples.length; i++) { var units = mp4samples[i].units; while (units.length) { var unit = units.shift(); var data = unit.data; mdatbox.set(data, offset); offset += data.bytelength; } } var latest = mp4samples[mp4samples.length - 1]; lastdts = latest.dts + latest.duration; lastpts = latest.pts + latest.duration; this._videonextdts = lastdts; // fill media segment info & add to info list info.begindts = firstdts; info.enddts = lastdts; info.beginpts = firstpts; info.endpts = lastpts; info.originalbegindts = mp4samples[0].originaldts; info.originalenddts = latest.originaldts + latest.duration; info.firstsample = new _core_media_segment_info_js__webpack_imported_module_4__.sampleinfo(mp4samples[0].dts, mp4samples[0].pts, mp4samples[0].duration, mp4samples[0].originaldts, mp4samples[0].iskeyframe); info.lastsample = new _core_media_segment_info_js__webpack_imported_module_4__.sampleinfo(latest.dts, latest.pts, latest.duration, latest.originaldts, latest.iskeyframe); if (!this._islive) { this._videosegmentinfolist.append(info); } track.samples = mp4samples; track.sequencenumber++; // workaround for chrome < 50: force first sample as a random access point // see https://bugs.chromium.org/p/chromium/issues/detail?id=229412 if (this._forcefirstidr) { var flags = mp4samples[0].flags; flags.dependson = 2; flags.isnonsync = 0; } var moofbox = _mp4_generator_js__webpack_imported_module_1__.default.moof(track, firstdts); track.samples = []; track.length = 0; this._onmediasegment('video', { type: 'video', data: this._mergeboxes(moofbox, mdatbox).buffer, samplecount: mp4samples.length, info: info }); }; mp4remuxer.prototype._mergeboxes = function (moof, mdat) { var result = new uint8array(moof.bytelength + mdat.bytelength); result.set(moof, 0); result.set(mdat, moof.bytelength); return result; }; return mp4remuxer; }()); /* harmony default export */ __webpack_exports__["default"] = (mp4remuxer); /***/ }), /***/ "./src/utils/browser.js": /*!******************************!*\ !*** ./src/utils/browser.js ***! \******************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var browser = {}; function detect() { // modified from jquery-browser-plugin var ua = self.navigator.useragent.tolowercase(); var match = /(edge)\/([\w.]+)/.exec(ua) || /(opr)[\/]([\w.]+)/.exec(ua) || /(chrome)[ \/]([\w.]+)/.exec(ua) || /(iemobile)[\/]([\w.]+)/.exec(ua) || /(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexof('trident') >= 0 && /(rv)(?::| )([\w.]+)/.exec(ua) || ua.indexof('compatible') < 0 && /(firefox)[ \/]([\w.]+)/.exec(ua) || []; var platform_match = /(ipad)/.exec(ua) || /(ipod)/.exec(ua) || /(windows phone)/.exec(ua) || /(iphone)/.exec(ua) || /(kindle)/.exec(ua) || /(android)/.exec(ua) || /(windows)/.exec(ua) || /(mac)/.exec(ua) || /(linux)/.exec(ua) || /(cros)/.exec(ua) || []; var matched = { browser: match[5] || match[3] || match[1] || '', version: match[2] || match[4] || '0', majorversion: match[4] || match[2] || '0', platform: platform_match[0] || '' }; var browser = {}; if (matched.browser) { browser[matched.browser] = true; var versionarray = matched.majorversion.split('.'); browser.version = { major: parseint(matched.majorversion, 10), string: matched.version }; if (versionarray.length > 1) { browser.version.minor = parseint(versionarray[1], 10); } if (versionarray.length > 2) { browser.version.build = parseint(versionarray[2], 10); } } if (matched.platform) { browser[matched.platform] = true; } if (browser.chrome || browser.opr || browser.safari) { browser.webkit = true; } // msie. ie11 has 'rv' identifer if (browser.rv || browser.iemobile) { if (browser.rv) { delete browser.rv; } var msie = 'msie'; matched.browser = msie; browser[msie] = true; } // microsoft edge if (browser.edge) { delete browser.edge; var msedge = 'msedge'; matched.browser = msedge; browser[msedge] = true; } // opera 15+ if (browser.opr) { var opera = 'opera'; matched.browser = opera; browser[opera] = true; } // stock android browsers are marked as safari if (browser.safari && browser.android) { var android = 'android'; matched.browser = android; browser[android] = true; } browser.name = matched.browser; browser.platform = matched.platform; for (var key in browser) { if (browser.hasownproperty(key)) { delete browser[key]; } } object.assign(browser, browser); } detect(); /* harmony default export */ __webpack_exports__["default"] = (browser); /***/ }), /***/ "./src/utils/exception.js": /*!********************************!*\ !*** ./src/utils/exception.js ***! \********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "runtimeexception": function() { return /* binding */ runtimeexception; }, /* harmony export */ "illegalstateexception": function() { return /* binding */ illegalstateexception; }, /* harmony export */ "invalidargumentexception": function() { return /* binding */ invalidargumentexception; }, /* harmony export */ "notimplementedexception": function() { return /* binding */ notimplementedexception; } /* harmony export */ }); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var __extends = (undefined && undefined.__extends) || (function () { var extendstatics = function (d, b) { extendstatics = object.setprototypeof || ({ __proto__: [] } instanceof array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (object.prototype.hasownproperty.call(b, p)) d[p] = b[p]; }; return extendstatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new typeerror("class extends value " + string(b) + " is not a constructor or null"); extendstatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var runtimeexception = /** @class */ (function () { function runtimeexception(message) { this._message = message; } object.defineproperty(runtimeexception.prototype, "name", { get: function () { return 'runtimeexception'; }, enumerable: false, configurable: true }); object.defineproperty(runtimeexception.prototype, "message", { get: function () { return this._message; }, enumerable: false, configurable: true }); runtimeexception.prototype.tostring = function () { return this.name + ': ' + this.message; }; return runtimeexception; }()); var illegalstateexception = /** @class */ (function (_super) { __extends(illegalstateexception, _super); function illegalstateexception(message) { return _super.call(this, message) || this; } object.defineproperty(illegalstateexception.prototype, "name", { get: function () { return 'illegalstateexception'; }, enumerable: false, configurable: true }); return illegalstateexception; }(runtimeexception)); var invalidargumentexception = /** @class */ (function (_super) { __extends(invalidargumentexception, _super); function invalidargumentexception(message) { return _super.call(this, message) || this; } object.defineproperty(invalidargumentexception.prototype, "name", { get: function () { return 'invalidargumentexception'; }, enumerable: false, configurable: true }); return invalidargumentexception; }(runtimeexception)); var notimplementedexception = /** @class */ (function (_super) { __extends(notimplementedexception, _super); function notimplementedexception(message) { return _super.call(this, message) || this; } object.defineproperty(notimplementedexception.prototype, "name", { get: function () { return 'notimplementedexception'; }, enumerable: false, configurable: true }); return notimplementedexception; }(runtimeexception)); /***/ }), /***/ "./src/utils/logger.js": /*!*****************************!*\ !*** ./src/utils/logger.js ***! \*****************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var events__webpack_imported_module_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js"); /* harmony import */ var events__webpack_imported_module_0___default = /*#__pure__*/__webpack_require__.n(events__webpack_imported_module_0__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var log = /** @class */ (function () { function log() { } log.e = function (tag, msg) { if (!tag || log.force_global_tag) tag = log.global_tag; var str = "[" + tag + "] > " + msg; if (log.enable_callback) { log.emitter.emit('log', 'error', str); } if (!log.enable_error) { return; } if (console.error) { console.error(str); } else if (console.warn) { console.warn(str); } else { console.log(str); } }; log.i = function (tag, msg) { if (!tag || log.force_global_tag) tag = log.global_tag; var str = "[" + tag + "] > " + msg; if (log.enable_callback) { log.emitter.emit('log', 'info', str); } if (!log.enable_info) { return; } if (console.info) { console.info(str); } else { console.log(str); } }; log.w = function (tag, msg) { if (!tag || log.force_global_tag) tag = log.global_tag; var str = "[" + tag + "] > " + msg; if (log.enable_callback) { log.emitter.emit('log', 'warn', str); } if (!log.enable_warn) { return; } if (console.warn) { console.warn(str); } else { console.log(str); } }; log.d = function (tag, msg) { if (!tag || log.force_global_tag) tag = log.global_tag; var str = "[" + tag + "] > " + msg; if (log.enable_callback) { log.emitter.emit('log', 'debug', str); } if (!log.enable_debug) { return; } if (console.debug) { console.debug(str); } else { console.log(str); } }; log.v = function (tag, msg) { if (!tag || log.force_global_tag) tag = log.global_tag; var str = "[" + tag + "] > " + msg; if (log.enable_callback) { log.emitter.emit('log', 'verbose', str); } if (!log.enable_verbose) { return; } console.log(str); }; return log; }()); log.global_tag = 'flv.js'; log.force_global_tag = false; log.enable_error = true; log.enable_info = true; log.enable_warn = true; log.enable_debug = true; log.enable_verbose = true; log.enable_callback = false; log.emitter = new (events__webpack_imported_module_0___default())(); /* harmony default export */ __webpack_exports__["default"] = (log); /***/ }), /***/ "./src/utils/logging-control.js": /*!**************************************!*\ !*** ./src/utils/logging-control.js ***! \**************************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var events__webpack_imported_module_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js"); /* harmony import */ var events__webpack_imported_module_0___default = /*#__pure__*/__webpack_require__.n(events__webpack_imported_module_0__); /* harmony import */ var _logger_js__webpack_imported_module_1__ = __webpack_require__(/*! ./logger.js */ "./src/utils/logger.js"); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var loggingcontrol = /** @class */ (function () { function loggingcontrol() { } object.defineproperty(loggingcontrol, "forceglobaltag", { get: function () { return _logger_js__webpack_imported_module_1__.default.force_global_tag; }, set: function (enable) { _logger_js__webpack_imported_module_1__.default.force_global_tag = enable; loggingcontrol._notifychange(); }, enumerable: false, configurable: true }); object.defineproperty(loggingcontrol, "globaltag", { get: function () { return _logger_js__webpack_imported_module_1__.default.global_tag; }, set: function (tag) { _logger_js__webpack_imported_module_1__.default.global_tag = tag; loggingcontrol._notifychange(); }, enumerable: false, configurable: true }); object.defineproperty(loggingcontrol, "enableall", { get: function () { return _logger_js__webpack_imported_module_1__.default.enable_verbose && _logger_js__webpack_imported_module_1__.default.enable_debug && _logger_js__webpack_imported_module_1__.default.enable_info && _logger_js__webpack_imported_module_1__.default.enable_warn && _logger_js__webpack_imported_module_1__.default.enable_error; }, set: function (enable) { _logger_js__webpack_imported_module_1__.default.enable_verbose = enable; _logger_js__webpack_imported_module_1__.default.enable_debug = enable; _logger_js__webpack_imported_module_1__.default.enable_info = enable; _logger_js__webpack_imported_module_1__.default.enable_warn = enable; _logger_js__webpack_imported_module_1__.default.enable_error = enable; loggingcontrol._notifychange(); }, enumerable: false, configurable: true }); object.defineproperty(loggingcontrol, "enabledebug", { get: function () { return _logger_js__webpack_imported_module_1__.default.enable_debug; }, set: function (enable) { _logger_js__webpack_imported_module_1__.default.enable_debug = enable; loggingcontrol._notifychange(); }, enumerable: false, configurable: true }); object.defineproperty(loggingcontrol, "enableverbose", { get: function () { return _logger_js__webpack_imported_module_1__.default.enable_verbose; }, set: function (enable) { _logger_js__webpack_imported_module_1__.default.enable_verbose = enable; loggingcontrol._notifychange(); }, enumerable: false, configurable: true }); object.defineproperty(loggingcontrol, "enableinfo", { get: function () { return _logger_js__webpack_imported_module_1__.default.enable_info; }, set: function (enable) { _logger_js__webpack_imported_module_1__.default.enable_info = enable; loggingcontrol._notifychange(); }, enumerable: false, configurable: true }); object.defineproperty(loggingcontrol, "enablewarn", { get: function () { return _logger_js__webpack_imported_module_1__.default.enable_warn; }, set: function (enable) { _logger_js__webpack_imported_module_1__.default.enable_warn = enable; loggingcontrol._notifychange(); }, enumerable: false, configurable: true }); object.defineproperty(loggingcontrol, "enableerror", { get: function () { return _logger_js__webpack_imported_module_1__.default.enable_error; }, set: function (enable) { _logger_js__webpack_imported_module_1__.default.enable_error = enable; loggingcontrol._notifychange(); }, enumerable: false, configurable: true }); loggingcontrol.getconfig = function () { return { globaltag: _logger_js__webpack_imported_module_1__.default.global_tag, forceglobaltag: _logger_js__webpack_imported_module_1__.default.force_global_tag, enableverbose: _logger_js__webpack_imported_module_1__.default.enable_verbose, enabledebug: _logger_js__webpack_imported_module_1__.default.enable_debug, enableinfo: _logger_js__webpack_imported_module_1__.default.enable_info, enablewarn: _logger_js__webpack_imported_module_1__.default.enable_warn, enableerror: _logger_js__webpack_imported_module_1__.default.enable_error, enablecallback: _logger_js__webpack_imported_module_1__.default.enable_callback }; }; loggingcontrol.applyconfig = function (config) { _logger_js__webpack_imported_module_1__.default.global_tag = config.globaltag; _logger_js__webpack_imported_module_1__.default.force_global_tag = config.forceglobaltag; _logger_js__webpack_imported_module_1__.default.enable_verbose = config.enableverbose; _logger_js__webpack_imported_module_1__.default.enable_debug = config.enabledebug; _logger_js__webpack_imported_module_1__.default.enable_info = config.enableinfo; _logger_js__webpack_imported_module_1__.default.enable_warn = config.enablewarn; _logger_js__webpack_imported_module_1__.default.enable_error = config.enableerror; _logger_js__webpack_imported_module_1__.default.enable_callback = config.enablecallback; }; loggingcontrol._notifychange = function () { var emitter = loggingcontrol.emitter; if (emitter.listenercount('change') > 0) { var config = loggingcontrol.getconfig(); emitter.emit('change', config); } }; loggingcontrol.registerlistener = function (listener) { loggingcontrol.emitter.addlistener('change', listener); }; loggingcontrol.removelistener = function (listener) { loggingcontrol.emitter.removelistener('change', listener); }; loggingcontrol.addloglistener = function (listener) { _logger_js__webpack_imported_module_1__.default.emitter.addlistener('log', listener); if (_logger_js__webpack_imported_module_1__.default.emitter.listenercount('log') > 0) { _logger_js__webpack_imported_module_1__.default.enable_callback = true; loggingcontrol._notifychange(); } }; loggingcontrol.removeloglistener = function (listener) { _logger_js__webpack_imported_module_1__.default.emitter.removelistener('log', listener); if (_logger_js__webpack_imported_module_1__.default.emitter.listenercount('log') === 0) { _logger_js__webpack_imported_module_1__.default.enable_callback = false; loggingcontrol._notifychange(); } }; return loggingcontrol; }()); loggingcontrol.emitter = new (events__webpack_imported_module_0___default())(); /* harmony default export */ __webpack_exports__["default"] = (loggingcontrol); /***/ }), /***/ "./src/utils/polyfill.js": /*!*******************************!*\ !*** ./src/utils/polyfill.js ***! \*******************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ var polyfill = /** @class */ (function () { function polyfill() { } polyfill.install = function () { // es6 object.setprototypeof object.setprototypeof = object.setprototypeof || function (obj, proto) { obj.__proto__ = proto; return obj; }; // es6 object.assign object.assign = object.assign || function (target) { if (target === undefined || target === null) { throw new typeerror('cannot convert undefined or null to object'); } var output = object(target); for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; if (source !== undefined && source !== null) { for (var key in source) { if (source.hasownproperty(key)) { output[key] = source[key]; } } } } return output; }; // es6 promise (missing support in ie11) if (typeof self.promise !== 'function') { __webpack_require__(/*! es6-promise */ "./node_modules/es6-promise/dist/es6-promise.js").polyfill(); } }; return polyfill; }()); polyfill.install(); /* harmony default export */ __webpack_exports__["default"] = (polyfill); /***/ }), /***/ "./src/utils/utf8-conv.js": /*!********************************!*\ !*** ./src/utils/utf8-conv.js ***! \********************************/ /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* * copyright (c) 2016 bilibili. all rights reserved. * * this file is derived from c++ project libwintf8 (https://github.com/m13253/libwintf8) * @author zheng qian * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * http://www.apache.org/licenses/license-2.0 * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. */ function checkcontinuation(uint8array, start, checklength) { var array = uint8array; if (start + checklength < array.length) { while (checklength--) { if ((array[++start] & 0xc0) !== 0x80) return false; } return true; } else { return false; } } function decodeutf8(uint8array) { var out = []; var input = uint8array; var i = 0; var length = uint8array.length; while (i < length) { if (input[i] < 0x80) { out.push(string.fromcharcode(input[i])); ++i; continue; } else if (input[i] < 0xc0) { // fallthrough } else if (input[i] < 0xe0) { if (checkcontinuation(input, i, 1)) { var ucs4 = (input[i] & 0x1f) << 6 | (input[i + 1] & 0x3f); if (ucs4 >= 0x80) { out.push(string.fromcharcode(ucs4 & 0xffff)); i += 2; continue; } } } else if (input[i] < 0xf0) { if (checkcontinuation(input, i, 2)) { var ucs4 = (input[i] & 0xf) << 12 | (input[i + 1] & 0x3f) << 6 | input[i + 2] & 0x3f; if (ucs4 >= 0x800 && (ucs4 & 0xf800) !== 0xd800) { out.push(string.fromcharcode(ucs4 & 0xffff)); i += 3; continue; } } } else if (input[i] < 0xf8) { if (checkcontinuation(input, i, 3)) { var ucs4 = (input[i] & 0x7) << 18 | (input[i + 1] & 0x3f) << 12 | (input[i + 2] & 0x3f) << 6 | (input[i + 3] & 0x3f); if (ucs4 > 0x10000 && ucs4 < 0x110000) { ucs4 -= 0x10000; out.push(string.fromcharcode((ucs4 >>> 10) | 0xd800)); out.push(string.fromcharcode((ucs4 & 0x3ff) | 0xdc00)); i += 4; continue; } } } out.push(string.fromcharcode(0xfffd)); ++i; } return out.join(''); } /* harmony default export */ __webpack_exports__["default"] = (decodeutf8); /***/ }) /******/ }); /************************************************************************/ /******/ // the module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // the require function /******/ function __webpack_require__(moduleid) { /******/ // check if module is in cache /******/ var cachedmodule = __webpack_module_cache__[moduleid]; /******/ if (cachedmodule !== undefined) { /******/ return cachedmodule.exports; /******/ } /******/ // create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleid] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // execute the module function /******/ __webpack_modules__[moduleid].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = __webpack_modules__; /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ !function() { /******/ // getdefaultexport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esmodule ? /******/ function() { return module['default']; } : /******/ function() { return module; }; /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ }(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ !function() { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = function(exports, definition) { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ object.defineproperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ }(); /******/ /******/ /* webpack/runtime/global */ /******/ !function() { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalthis === 'object') return globalthis; /******/ try { /******/ return this || new function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ }(); /******/ /******/ /* webpack/runtime/hasownproperty shorthand */ /******/ !function() { /******/ __webpack_require__.o = function(obj, prop) { return object.prototype.hasownproperty.call(obj, prop); } /******/ }(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ !function() { /******/ // define __esmodule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof symbol !== 'undefined' && symbol.tostringtag) { /******/ object.defineproperty(exports, symbol.tostringtag, { value: 'module' }); /******/ } /******/ object.defineproperty(exports, '__esmodule', { value: true }); /******/ }; /******/ }(); /******/ /************************************************************************/ /******/ /******/ // module factories are used so entry inlining is disabled /******/ // startup /******/ // load entry module and return exports /******/ var __webpack_exports__ = __webpack_require__("./src/index.js"); /******/ /******/ return __webpack_exports__; /******/ })() ; }); //# sourcemappingurl=flv.js.map