Greasy Fork is available in English.

下载知乎视频

为知乎的视频播放器添加下载功能

La data de 13-07-2018. Vezi ultima versiune.

// ==UserScript==
// @name         下载知乎视频
// @version      1.1
// @description  为知乎的视频播放器添加下载功能
// @author       Chao
// @include      *://www.zhihu.com/*
// @match        *://www.zhihu.com/*
// @include      https://v.vzuu.com/video/*
// @match        https://v.vzuu.com/video/*
// @connect      zhihu.com
// @connect      vzuu.com
// @grant        GM_info
// @grant        GM_download
// @grant        unsafeWindow
// @namespace    https://greasyfork.org/users/38953
// ==/UserScript==
/* jshint esversion: 6 */

(async () => {
    if (window.location.host == 'www.zhihu.com') return;

    // jDataView
    !function(a){var b=unsafeWindow;"object"==typeof exports?module.exports=a(b):"function"==typeof define&&define.amd?define([],function(){return a(b)}):b.jDataView=a(b)}(function(a){"use strict";function b(a,b){return"object"!=typeof a||null===a?!1:a.constructor===b||Object.prototype.toString.call(a)==="[object "+b.name+"]"}function c(a,c){return!c&&b(a,Array)?a:Array.prototype.slice.call(a)}function d(a,b){return void 0!==a?a:b}function e(a,c,f,g){if(e.is(a)){var h=a.slice(c,c+f);return h._littleEndian=d(g,h._littleEndian),h}if(!e.is(this))return new e(a,c,f,g);if(this.buffer=a=e.wrapBuffer(a),this._isArrayBuffer=j.ArrayBuffer&&b(a,ArrayBuffer),this._isPixelData=!0&&j.PixelData&&b(a,CanvasPixelArray),this._isDataView=j.DataView&&this._isArrayBuffer,this._isNodeBuffer=!1,!this._isArrayBuffer&&!this._isPixelData&&!b(a,Array))throw new TypeError("jDataView buffer has an incompatible type");this._littleEndian=!!g;var i="byteLength"in a?a.byteLength:a.length;this.byteOffset=c=d(c,0),this.byteLength=f=d(f,i-c),this._offset=this._bitOffset=0,this._isDataView?this._view=new DataView(a,c,f):this._checkBounds(c,f,i),this._engineAction=this._isDataView?this._dataViewAction:this._isArrayBuffer?this._arrayBufferAction:this._arrayAction}function f(a){for(var b=j.ArrayBuffer?Uint8Array:Array,c=new b(a.length),d=0,e=a.length;e>d;d++)c[d]=255&a.charCodeAt(d);return c}function g(a){return a>=0&&31>a?1<<a:g[a]||(g[a]=Math.pow(2,a))}function h(a,b){this.lo=a,this.hi=b}function i(){h.apply(this,arguments)}var j={NodeBuffer:!1,DataView:"DataView"in a,ArrayBuffer:"ArrayBuffer"in a,PixelData:!0&&"CanvasPixelArray"in a&&!("Uint8ClampedArray"in a)&&"document"in a},k=a.TextEncoder,l=a.TextDecoder;if(j.PixelData)var m=document.createElement("canvas").getContext("2d"),n=function(a,b){var c=m.createImageData((a+3)/4,1).data;if(c.byteLength=a,void 0!==b)for(var d=0;a>d;d++)c[d]=b[d];return c};var o={Int8:1,Int16:2,Int32:4,Uint8:1,Uint16:2,Uint32:4,Float32:4,Float64:8};e.wrapBuffer=function(a){switch(typeof a){case"number":if(j.ArrayBuffer)a=new Uint8Array(a).buffer;else if(j.PixelData)a=n(a);else{a=new Array(a);for(var d=0;d<a.length;d++)a[d]=0}return a;case"string":a=f(a);default:return"length"in a&&!(j.ArrayBuffer&&b(a,ArrayBuffer)||j.PixelData&&b(a,CanvasPixelArray))&&(j.ArrayBuffer?b(a,ArrayBuffer)||(a=new Uint8Array(a).buffer,b(a,ArrayBuffer)||(a=new Uint8Array(c(a,!0)).buffer)):a=j.PixelData?n(a.length,a):c(a)),a}},e.is=function(a){return a&&a.jDataView},e.from=function(){return new e(arguments)},e.Uint64=h,h.prototype={valueOf:function(){return this.lo+g(32)*this.hi},toString:function(){return Number.prototype.toString.apply(this.valueOf(),arguments)}},h.fromNumber=function(a){var b=Math.floor(a/g(32)),c=a-b*g(32);return new h(c,b)},e.Int64=i,i.prototype="create"in Object?Object.create(h.prototype):new h,i.prototype.valueOf=function(){return this.hi<g(31)?h.prototype.valueOf.apply(this,arguments):-(g(32)-this.lo+g(32)*(g(32)-1-this.hi))},i.fromNumber=function(a){var b,c;if(a>=0){var d=h.fromNumber(a);b=d.lo,c=d.hi}else c=Math.floor(a/g(32)),b=a-c*g(32),c+=g(32);return new i(b,c)};var p=e.prototype={compatibility:j,jDataView:!0,_checkBounds:function(a,b,c){if("number"!=typeof a)throw new TypeError("Offset is not a number.");if("number"!=typeof b)throw new TypeError("Size is not a number.");if(0>b)throw new RangeError("Length is negative.");if(0>a||a+b>d(c,this.byteLength))throw new RangeError("Offsets are out of bounds.")},_action:function(a,b,c,e,f){return this._engineAction(a,b,d(c,this._offset),d(e,this._littleEndian),f)},_dataViewAction:function(a,b,c,d,e){return this._offset=c+o[a],b?this._view["get"+a](c,d):this._view["set"+a](c,e,d)},_arrayBufferAction:function(b,c,e,f,g){var h,i=o[b],j=a[b+"Array"];if(f=d(f,this._littleEndian),1===i||(this.byteOffset+e)%i===0&&f)return h=new j(this.buffer,this.byteOffset+e,1),this._offset=e+i,c?h[0]:h[0]=g;var k=new Uint8Array(c?this.getBytes(i,e,f,!0):i);return h=new j(k.buffer,0,1),c?h[0]:(h[0]=g,void this._setBytes(e,k,f))},_arrayAction:function(a,b,c,d,e){return b?this["_get"+a](c,d):this["_set"+a](c,e,d)},_getBytes:function(a,b,e){e=d(e,this._littleEndian),b=d(b,this._offset),a=d(a,this.byteLength-b),this._checkBounds(b,a),b+=this.byteOffset,this._offset=b-this.byteOffset+a;var f=this._isArrayBuffer?new Uint8Array(this.buffer,b,a):(this.buffer.slice||Array.prototype.slice).call(this.buffer,b,b+a);return e||1>=a?f:c(f).reverse()},getBytes:function(a,b,e,f){var g=this._getBytes(a,b,d(e,!0));return f?c(g):g},_setBytes:function(a,b,e){var f=b.length;if(0!==f){if(e=d(e,this._littleEndian),a=d(a,this._offset),this._checkBounds(a,f),!e&&f>1&&(b=c(b,!0).reverse()),a+=this.byteOffset,this._isArrayBuffer)new Uint8Array(this.buffer,a,f).set(b);else for(var g=0;f>g;g++)this.buffer[a+g]=b[g];this._offset=a-this.byteOffset+f}},setBytes:function(a,b,c){this._setBytes(a,b,d(c,!0))},getString:function(a,b,c){var d=this._getBytes(a,b,!0);if(c="utf8"===c?"utf-8":c||"binary",l&&"binary"!==c)return new l(c).decode(this._isArrayBuffer?d:new Uint8Array(d));var e="";a=d.length;for(var f=0;a>f;f++)e+=String.fromCharCode(d[f]);return"utf-8"===c&&(e=decodeURIComponent(escape(e))),e},setString:function(a,b,c){c="utf8"===c?"utf-8":c||"binary";var d;k&&"binary"!==c?d=new k(c).encode(b):("utf-8"===c&&(b=unescape(encodeURIComponent(b))),d=f(b)),this._setBytes(a,d,!0)},getChar:function(a){return this.getString(1,a)},setChar:function(a,b){this.setString(a,b)},tell:function(){return this._offset},seek:function(a){return this._checkBounds(a,0),this._offset=a},skip:function(a){return this.seek(this._offset+a)},slice:function(a,b,c){function f(a,b){return 0>a?a+b:a}return a=f(a,this.byteLength),b=f(d(b,this.byteLength),this.byteLength),c?new e(this.getBytes(b-a,a,!0,!0),void 0,void 0,this._littleEndian):new e(this.buffer,this.byteOffset+a,b-a,this._littleEndian)},alignBy:function(a){return this._bitOffset=0,1!==d(a,1)?this.skip(a-(this._offset%a||a)):this._offset},_getFloat64:function(a,b){var c=this._getBytes(8,a,b),d=1-2*(c[7]>>7),e=((c[7]<<1&255)<<3|c[6]>>4)-1023,f=(15&c[6])*g(48)+c[5]*g(40)+c[4]*g(32)+c[3]*g(24)+c[2]*g(16)+c[1]*g(8)+c[0];return 1024===e?0!==f?0/0:1/0*d:-1023===e?d*f*g(-1074):d*(1+f*g(-52))*g(e)},_getFloat32:function(a,b){var c=this._getBytes(4,a,b),d=1-2*(c[3]>>7),e=(c[3]<<1&255|c[2]>>7)-127,f=(127&c[2])<<16|c[1]<<8|c[0];return 128===e?0!==f?0/0:1/0*d:-127===e?d*f*g(-149):d*(1+f*g(-23))*g(e)},_get64:function(a,b,c){c=d(c,this._littleEndian),b=d(b,this._offset);for(var e=c?[0,4]:[4,0],f=0;2>f;f++)e[f]=this.getUint32(b+e[f],c);return this._offset=b+8,new a(e[0],e[1])},getInt64:function(a,b){return this._get64(i,a,b)},getUint64:function(a,b){return this._get64(h,a,b)},_getInt32:function(a,b){var c=this._getBytes(4,a,b);return c[3]<<24|c[2]<<16|c[1]<<8|c[0]},_getUint32:function(a,b){return this._getInt32(a,b)>>>0},_getInt16:function(a,b){return this._getUint16(a,b)<<16>>16},_getUint16:function(a,b){var c=this._getBytes(2,a,b);return c[1]<<8|c[0]},_getInt8:function(a){return this._getUint8(a)<<24>>24},_getUint8:function(a){return this._getBytes(1,a)[0]},_getBitRangeData:function(a,b){var c=(d(b,this._offset)<<3)+this._bitOffset,e=c+a,f=c>>>3,g=e+7>>>3,h=this._getBytes(g-f,f,!0),i=0;(this._bitOffset=7&e)&&(this._bitOffset-=8);for(var j=0,k=h.length;k>j;j++)i=i<<8|h[j];return{start:f,bytes:h,wideValue:i}},getSigned:function(a,b){var c=32-a;return this.getUnsigned(a,b)<<c>>c},getUnsigned:function(a,b){var c=this._getBitRangeData(a,b).wideValue>>>-this._bitOffset;return 32>a?c&~(-1<<a):c},_setBinaryFloat:function(a,b,c,d,e){var f,h,i=0>b?1:0,j=~(-1<<d-1),k=1-j;0>b&&(b=-b),0===b?(f=0,h=0):isNaN(b)?(f=2*j+1,h=1):1/0===b?(f=2*j+1,h=0):(f=Math.floor(Math.log(b)/Math.LN2),f>=k&&j>=f?(h=Math.floor((b*g(-f)-1)*g(c)),f+=j):(h=Math.floor(b/g(k-c)),f=0));for(var l=[];c>=8;)l.push(h%256),h=Math.floor(h/256),c-=8;for(f=f<<c|h,d+=c;d>=8;)l.push(255&f),f>>>=8,d-=8;l.push(i<<d|f),this._setBytes(a,l,e)},_setFloat32:function(a,b,c){this._setBinaryFloat(a,b,23,8,c)},_setFloat64:function(a,b,c){this._setBinaryFloat(a,b,52,11,c)},_set64:function(a,b,c,e){"object"!=typeof c&&(c=a.fromNumber(c)),e=d(e,this._littleEndian),b=d(b,this._offset);var f=e?{lo:0,hi:4}:{lo:4,hi:0};for(var g in f)this.setUint32(b+f[g],c[g],e);this._offset=b+8},setInt64:function(a,b,c){this._set64(i,a,b,c)},setUint64:function(a,b,c){this._set64(h,a,b,c)},_setUint32:function(a,b,c){this._setBytes(a,[255&b,b>>>8&255,b>>>16&255,b>>>24],c)},_setUint16:function(a,b,c){this._setBytes(a,[255&b,b>>>8&255],c)},_setUint8:function(a,b){this._setBytes(a,[255&b])},setUnsigned:function(a,b,c){var d=this._getBitRangeData(c,a),e=d.wideValue,f=d.bytes;e&=~(~(-1<<c)<<-this._bitOffset),e|=(32>c?b&~(-1<<c):b)<<-this._bitOffset;for(var g=f.length-1;g>=0;g--)f[g]=255&e,e>>>=8;this._setBytes(d.start,f,!0)}};for(var q in o)!function(a){p["get"+a]=function(b,c){return this._action(a,!0,b,c)},p["set"+a]=function(b,c,d){this._action(a,!1,b,d,c)}}(q);p._setInt32=p._setUint32,p._setInt16=p._setUint16,p._setInt8=p._setUint8,p.setSigned=p.setUnsigned;for(var r in p)"set"===r.slice(0,3)&&!function(a){p["write"+a]=function(){Array.prototype.unshift.call(arguments,void 0),this["set"+a].apply(this,arguments)}}(r.slice(3));return e});

    // jBinary
    !function(a){var b=unsafeWindow;"object"==typeof exports?module.exports=a(b,require("jdataview")):"function"==typeof define&&define.amd?define(["jdataview"],function(c){return a(b,c)}):b.jBinary=a(b,b.jDataView)}(function(a,b){"use strict";function c(a,b){return b&&a instanceof b}function d(a){for(var b=1,c=arguments.length;c>b;++b){var d=arguments[b];for(var e in d)void 0!==d[e]&&(a[e]=d[e])}return a}function e(a){return arguments[0]=m(a),d.apply(null,arguments)}function f(a,b,d){return c(d,Function)?d.call(a,b.contexts[0]):d}function g(a){return function(){var b=arguments,d=b.length-1,e=a.length-1,f=b[d];if(b.length=e+1,!c(f,Function)){var g=this;return new l(function(c,d){b[e]=function(a,b){return a?d(a):c(b)},a.apply(g,b)})}b[d]=void 0,b[e]=f,a.apply(this,b)}}function h(a,d){return c(a,h)?a.as(d):(c(a,b)||(a=new b(a,void 0,void 0,d?d["jBinary.littleEndian"]:void 0)),c(this,h)?(this.view=a,this.view.seek(0),this.contexts=[],this.as(d,!0)):new h(a,d))}function i(a){return e(i.prototype,a)}function j(a){return e(j.prototype,a,{createProperty:function(){var b=(a.createProperty||j.prototype.createProperty).apply(this,arguments);return b.getBaseType&&(b.baseType=b.binary.getType(b.getBaseType(b.binary.contexts[0]))),b}})}var k=a.document;"atob"in a&&"btoa"in a||!function(){function b(a){var b,c,e,f,g,h;for(e=a.length,c=0,b="";e>c;){if(f=255&a.charCodeAt(c++),c==e){b+=d.charAt(f>>2),b+=d.charAt((3&f)<<4),b+="==";break}if(g=a.charCodeAt(c++),c==e){b+=d.charAt(f>>2),b+=d.charAt((3&f)<<4|(240&g)>>4),b+=d.charAt((15&g)<<2),b+="=";break}h=a.charCodeAt(c++),b+=d.charAt(f>>2),b+=d.charAt((3&f)<<4|(240&g)>>4),b+=d.charAt((15&g)<<2|(192&h)>>6),b+=d.charAt(63&h)}return b}function c(a){var b,c,d,f,g,h,i;for(h=a.length,g=0,i="";h>g;){do b=e[255&a.charCodeAt(g++)];while(h>g&&-1==b);if(-1==b)break;do c=e[255&a.charCodeAt(g++)];while(h>g&&-1==c);if(-1==c)break;i+=String.fromCharCode(b<<2|(48&c)>>4);do{if(d=255&a.charCodeAt(g++),61==d)return i;d=e[d]}while(h>g&&-1==d);if(-1==d)break;i+=String.fromCharCode((15&c)<<4|(60&d)>>2);do{if(f=255&a.charCodeAt(g++),61==f)return i;f=e[f]}while(h>g&&-1==f);if(-1==f)break;i+=String.fromCharCode((3&d)<<6|f)}return i}var d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1];a.btoa||(a.btoa=b),a.atob||(a.atob=c)}();var l=a.Promise||function(a){this.then=a},m=Object.create;m||(m=function(a){var b=function(){};return b.prototype=a,new b});var n=h.prototype,o=n.typeSet={};n.toValue=function(a){return f(this,this,a)},n._named=function(a,b,c){return a.displayName=b+" @ "+(void 0!==c?c:this.view.tell()),a};var p=Object.defineProperty;if(p)try{p({},"x",{})}catch(q){p=void 0}else p=function(a,b,c,d){d&&(a[b]=c.value)};var r="jBinary.Cache",s=0;n._getCached=function(a,b,c){if(a.hasOwnProperty(this.cacheKey))return a[this.cacheKey];var d=b.call(this,a);return p(a,this.cacheKey,{value:d},c),d},n.getContext=function(a){switch(typeof a){case"undefined":a=0;case"number":return this.contexts[a];case"string":return this.getContext(function(b){return a in b});case"function":for(var b=0,c=this.contexts.length;c>b;b++){var d=this.contexts[b];if(a.call(this,d))return d}}},n.inContext=function(a,b){this.contexts.unshift(a);var c=b.call(this);return this.contexts.shift(),c},i.prototype={inherit:function(a,b){function c(a,b){var c=f[a];c&&(d||(d=e(f)),b.call(d,c),d[a]=null)}var d,f=this;return c("params",function(b){for(var c=0,d=b.length;d>c;c++)this[b[c]]=a[c]}),c("setParams",function(b){b.apply(this,a)}),c("typeParams",function(a){for(var c=0,d=a.length;d>c;c++){var e=a[c],f=this[e];f&&(this[e]=b(f))}}),c("resolve",function(a){a.call(this,b)}),d||f},createProperty:function(a){return e(this,{binary:a,view:a.view})},toValue:function(a,b){return b!==!1&&"string"==typeof a?this.binary.getContext(a)[a]:f(this,this.binary,a)}},h.Type=i,j.prototype=e(i.prototype,{setParams:function(){this.baseType&&(this.typeParams=["baseType"].concat(this.typeParams||[]))},baseRead:function(){return this.binary.read(this.baseType)},baseWrite:function(a){return this.binary.write(this.baseType,a)}}),d(j.prototype,{read:j.prototype.baseRead,write:j.prototype.baseWrite}),h.Template=j,n.as=function(a,b){var c=b?this:e(this);return a=a||o,c.typeSet=a===o||o.isPrototypeOf(a)?a:e(o,a),c.cacheKey=r,c.cacheKey=c._getCached(a,function(){return r+"."+ ++s},!0),c},n.seek=function(a,b){if(a=this.toValue(a),void 0!==b){var c=this.view.tell();this.view.seek(a);var d=b.call(this);return this.view.seek(c),d}return this.view.seek(a)},n.tell=function(){return this.view.tell()},n.skip=function(a,b){return this.seek(this.tell()+this.toValue(a),b)},n.slice=function(a,b,c){return new h(this.view.slice(a,b,c),this.typeSet)},n._getType=function(a,b){switch(typeof a){case"string":if(!(a in this.typeSet))throw new ReferenceError("Unknown type: "+a);return this._getType(this.typeSet[a],b);case"number":return this._getType(o.bitfield,[a]);case"object":if(c(a,i)){var d=this;return a.inherit(b||[],function(a){return d.getType(a)})}return c(a,Array)?this._getCached(a,function(a){return this.getType(a[0],a.slice(1))},!0):this._getCached(a,function(a){return this.getType(o.object,[a])},!1)}},n.getType=function(a,b){var d=this._getType(a,b);return d&&!c(a,i)&&(d.name="object"==typeof a?c(a,Array)?a[0]+"("+a.slice(1).join(", ")+")":"object":String(a)),d},n._action=function(a,b,c){if(void 0!==a){a=this.getType(a);var d=this._named(function(){return c.call(this,a.createProperty(this),this.contexts[0])},"["+a.name+"]",b);return void 0!==b?this.seek(b,d):d.call(this)}},n.read=function(a,b){return this._action(a,b,function(a,b){return a.read(b)})},n.readAll=function(){return this.read("jBinary.all",0)},n.write=function(a,b,c){return this._action(a,c,function(a,c){var d=this.tell();return a.write(b,c),this.tell()-d})},n.writeAll=function(a){return this.write("jBinary.all",a,0)},function(a,b){for(var c=0,d=b.length;d>c;c++){var f=b[c];o[f.toLowerCase()]=e(a,{dataType:f})}}(i({params:["littleEndian"],read:function(){return this.view["get"+this.dataType](void 0,this.littleEndian)},write:function(a){this.view["write"+this.dataType](a,this.littleEndian)}}),["Uint8","Uint16","Uint32","Uint64","Int8","Int16","Int32","Int64","Float32","Float64","Char"]),d(o,{"byte":o.uint8,"float":o.float32,"double":o.float64}),o.array=j({params:["baseType","length"],read:function(){var a=this.toValue(this.length);if(this.baseType===o.uint8)return this.view.getBytes(a,void 0,!0,!0);var b;if(void 0!==a){b=new Array(a);for(var c=0;a>c;c++)b[c]=this.baseRead()}else{var d=this.view.byteLength;for(b=[];this.binary.tell()<d;)b.push(this.baseRead())}return b},write:function(a){if(this.baseType===o.uint8)return this.view.writeBytes(a);for(var b=0,c=a.length;c>b;b++)this.baseWrite(a[b])}}),o.binary=j({params:["length","typeSet"],read:function(){var a=this.binary.tell(),b=this.binary.skip(this.toValue(this.length)),c=this.view.slice(a,b);return new h(c,this.typeSet)},write:function(a){this.binary.write("blob",a.read("blob",0))}}),o.bitfield=i({params:["bitSize"],read:function(){return this.view.getUnsigned(this.bitSize)},write:function(a){this.view.writeUnsigned(a,this.bitSize)}}),o.blob=i({params:["length"],read:function(){return this.view.getBytes(this.toValue(this.length))},write:function(a){this.view.writeBytes(a,!0)}}),o["const"]=j({params:["baseType","value","strict"],read:function(){var a=this.baseRead();if(this.strict&&a!==this.value){if(c(this.strict,Function))return this.strict(a);throw new TypeError("Unexpected value ("+a+" !== "+this.value+").")}return a},write:function(a){this.baseWrite(this.strict||void 0===a?this.value:a)}}),o["enum"]=j({params:["baseType","matches"],setParams:function(a,b){this.backMatches={};for(var c in b)this.backMatches[b[c]]=c},read:function(){var a=this.baseRead();return a in this.matches?this.matches[a]:a},write:function(a){this.baseWrite(a in this.backMatches?this.backMatches[a]:a)}}),o.extend=i({setParams:function(){this.parts=arguments},resolve:function(a){for(var b=this.parts,c=b.length,d=new Array(c),e=0;c>e;e++)d[e]=a(b[e]);this.parts=d},read:function(){var a=this.parts,b=this.binary.read(a[0]);return this.binary.inContext(b,function(){for(var c=1,e=a.length;e>c;c++)d(b,this.read(a[c]))}),b},write:function(a){var b=this.parts;this.binary.inContext(a,function(){for(var c=0,d=b.length;d>c;c++)this.write(b[c],a)})}}),o["if"]=j({params:["condition","trueType","falseType"],typeParams:["trueType","falseType"],getBaseType:function(){return this.toValue(this.condition)?this.trueType:this.falseType}}),o.if_not=o.ifNot=j({setParams:function(a,b,c){this.baseType=["if",a,c,b]}}),o.lazy=j({marker:"jBinary.Lazy",params:["innerType","length"],getBaseType:function(){return["binary",this.length,this.binary.typeSet]},read:function(){var a=function(b){return 0===arguments.length?"value"in a?a.value:a.value=a.binary.read(a.innerType):d(a,{wasChanged:!0,value:b}).value};return a[this.marker]=!0,d(a,{binary:d(this.baseRead(),{contexts:this.binary.contexts.slice()}),innerType:this.innerType})},write:function(a){a.wasChanged||!a[this.marker]?this.binary.write(this.innerType,a()):this.baseWrite(a.binary)}}),o.object=i({params:["structure","proto"],resolve:function(a){var b={};for(var d in this.structure)b[d]=c(this.structure[d],Function)?this.structure[d]:a(this.structure[d]);this.structure=b},read:function(){var a=this,b=this.structure,d=this.proto?e(this.proto):{};return this.binary.inContext(d,function(){for(var e in b)this._named(function(){var f=c(b[e],Function)?b[e].call(a,d):this.read(b[e]);void 0!==f&&(d[e]=f)},e).call(this)}),d},write:function(a){var b=this,d=this.structure;this.binary.inContext(a,function(){for(var e in d)this._named(function(){c(d[e],Function)?a[e]=d[e].call(b,a):this.write(d[e],a[e])},e).call(this)})}}),o.skip=i({params:["length"],read:function(){this.view.skip(this.toValue(this.length))},write:function(){this.read()}}),o.string=j({params:["length","encoding"],read:function(){return this.view.getString(this.toValue(this.length),void 0,this.encoding)},write:function(a){this.view.writeString(a,this.encoding)}}),o.string0=i({params:["length","encoding"],read:function(){var a=this.view,b=this.length;if(void 0===b){var c,d=a.tell(),e=0;for(b=a.byteLength-d;b>e&&(c=a.getUint8());)e++;var f=a.getString(e,d,this.encoding);return b>e&&a.skip(1),f}return a.getString(b,void 0,this.encoding).replace(/\0.*$/,"")},write:function(a){var b=this.view,c=void 0===this.length?1:this.length-a.length;b.writeString(a,void 0,this.encoding),c>0&&(b.writeUint8(0),b.skip(c-1))}});h.loadData=g(function(b,d){var e;if(c(b,a.Blob)){var f;if("FileReader"in a)f=new FileReader,f.onload=f.onerror=function(){d(this.error,this.result)},f.readAsArrayBuffer(b);else{f=new FileReaderSync;var g,h;try{h=f.readAsArrayBuffer(b)}catch(i){g=i}finally{d(g,h)}}}else{if("string"!=typeof b)d(new TypeError("Unsupported source type."));else if(e=b.match(/^data:(.+?)(;base64)?,(.*)$/))try{var j=e[2],k=e[3];d(null,(j?atob:decodeURIComponent)(k))}catch(i){d(i)}else if("XMLHttpRequest"in a){var l=new XMLHttpRequest;l.open("GET",b,!0),"responseType"in l?l.responseType="arraybuffer":"overrideMimeType"in l?l.overrideMimeType("text/plain; charset=x-user-defined"):l.setRequestHeader("Accept-Charset","x-user-defined"),"onload"in l||(l.onreadystatechange=function(){4===this.readyState&&this.onload()});var m=function(a){d(new Error(a))};l.onload=function(){return 0!==this.status&&200!==this.status?m("HTTP Error #"+this.status+": "+this.statusText):("response"in this||(this.response=new VBArray(this.responseBody).toArray()),void d(null,this.response))},l.onerror=function(){m("Network error.")},l.send(null)}else d(new TypeError("Unsupported source type."))}}),h.load=g(function(a,b,c){var d=h.loadData(a);h.load.getTypeSet(a,b,function(a){d.then(function(b){c(null,new h(b,a))},c)})}),h.load.getTypeSet=function(a,b,c){c(b)},n._toURI="URL"in a&&"createObjectURL"in URL?function(a){var b=this.seek(0,function(){return this.view.getBytes()});return URL.createObjectURL(new Blob([b],{type:a}))}:function(a){var b=this.seek(0,function(){return this.view.getString(void 0,void 0,"binary")});return"data:"+a+";base64,"+btoa(b)},n._mimeType=function(a){return a||this.typeSet["jBinary.mimeType"]||"application/octet-stream"},n.toURI=function(a){return this._toURI(this._mimeType(a))};if(k){var t=h.downloader=k.createElement("a");t.style.display="none"}return n.saveAs=g(function(a,b,c){if("string"==typeof a){"msSaveBlob"in navigator?navigator.msSaveBlob(new Blob([this.read("blob",0)],{type:this._mimeType(b)}),a):k?(t.parentNode||k.body.appendChild(t),t.href=this.toURI(b),t.download=a,t.click(),t.href=t.download=""):c(new TypeError("Saving from Web Worker is not supported.")),c()}else c(new TypeError("Unsupported storage type."))}),h});

    // mpegts/mpegts.js
    !function(e,t){"function"==typeof define&&define.amd?define(["jbinary"],t):"object"==typeof exports?module.exports=t(require("jbinary")):e.MPEGTS=t(e.jBinary)}(unsafeWindow,function(e){"use strict";return{PCR:{pts:33,_reserved:6,extension:9},DynamicArray:e.Template({setParams:function(e,t){this.baseType={length:e,array:["array",t,"length"]}},read:function(){return this.baseRead().array},write:function(e){this.baseWrite({length:e.length,array:e})}}),Field:["DynamicArray","uint8","uint8"],Flag:e.Template({baseType:1,params:["dependentField"],write:function(e,t){this.baseWrite(this.dependentField in t?1:0)}}),FlagDependent:e.Template({params:["flagField","baseType"],read:function(){return this.binary.read(["if",this.flagField,this.baseType])}}),AdaptationField:{length:"uint8",_endOf:function(e){return this.binary.tell()+e.length},discontinuity:1,randomAccess:1,priority:1,_hasPCR:["Flag","pcr"],_hasOPCR:["Flag","opcr"],_hasSplicingPoint:["Flag","spliceCountdown"],_hasTransportPrivateData:["Flag","privateData"],_hasExtension:["Flag","extension"],pcr:["FlagDependent","_hasPCR","PCR"],opcr:["FlagDependent","_hasOPCR","PCR"],spliceCountdown:["FlagDependent","_hasSplicingPoint","uint8"],privateData:["FlagDependent","_hasTransportPrivateData","Field"],extension:["FlagDependent","_hasExtension","Field"],_toEnd:function(e){this.binary.seek(e._endOf)}},ES:{_rawStream:["blob",function(){return this.binary.getContext(1)._endof-this.binary.tell()}]},PATItem:["array",{programNumber:"uint16",_reserved:3,pid:13},function(e){return e._dataLength/4}],PMTHeader:{_reserved:3,pcrPID:13,_reserved2:4,programDescriptors:["DynamicArray",12,"uint8"]},PMTItem:{streamType:"uint8",_reserved:3,elementaryPID:13,_reserved2:4,esInfo:["DynamicArray",12,"uint8"]},PrivateSection:["extend",{pointerField:["if","payloadStart","uint8"],tableId:["enum","uint8",["PAT","CAT","PMT"]],isLongSection:1,isPrivate:1,_reserved:2,_sectionLength:12},["if","isLongSection",{tableIdExt:"uint16",_reserved:2,versionNumber:5,currentNextIndicator:1,sectionNumber:"uint8",lastSectionNumber:"uint8",_dataLength:function(){return this.binary.getContext(1)._sectionLength-9},data:e.Type({read:function(e){var t,n=this.binary.getContext(3),a=e._dataLength;switch(this.binary.getContext(1).tableId){case"PAT":t=this.binary.read("PATItem"),0==e.sectionNumber&&(n.pat={});for(var i=0;i<t.length;i++)n.pat[t[i].pid]=t[i];break;case"PMT":for((t=this.binary.read("PMTHeader")).mappings=[],a-=4+t.programDescriptors.length;a>0;){var r=this.binary.read("PMTItem");t.mappings.push(r),a-=5+r.esInfo.length}0==e.sectionNumber&&(n.pmt={});for(i=0;i<t.mappings.length;i++){r=t.mappings[i];n.pmt[r.elementaryPID]=r}}return t}}),crc32:"uint32"},["blob","_sectionLength"]]],Packet:{_startof:function(){return this.binary.tell()},_endof:function(e){return e._startof+188},_syncByte:["const","uint8",71,!0],transportError:1,payloadStart:1,transportPriority:1,pid:13,scramblingControl:2,_hasAdaptationField:["Flag","adaptationField"],_hasPayload:["Flag","payload"],contCounter:4,adaptationField:["FlagDependent","_hasAdaptationField","AdaptationField"],payload:["FlagDependent","_hasPayload",e.Template({getBaseType:function(e){var t=e.pid,n=this.binary.getContext(1);return t<2||t in n.pat?"PrivateSection":t in n.pmt?"ES":void 0}})],_toEnd:function(e){this.binary.seek(e._endof)}},File:e.Template({baseType:["array","Packet"],read:function(){this.pat={},this.pmt={};var e=this;return this.binary.inContext(this,function(){return e.baseRead()})},write:function(e){var t=this;this.binary.inContext(this,function(){t.baseWrite(e)})}})}});

    // mpegts/mp4.js
    !function(e,t){"function"==typeof define&&define.amd?define(["jbinary"],t):"object"==typeof exports?module.exports=t(require("jbinary")):e.MP4=t(e.jBinary)}(unsafeWindow,function(e){"use strict";var t=new Date(1970,0,1)-new Date(1904,0,1);function i(e){return function(t){return t.type===e}}return{ShortName:["string0",4],Rate:["FixedPoint","int32",16],Dimensions:e.Template({setParams:function(e){this.baseType={horz:e,vert:e}}}),BoxHeader:{_begin:function(){return this.binary.tell()},_size:e.Template({baseType:"uint32",write:function(e,t){var i=t.size;this.baseWrite(i?i<Math.pow(2,32)?i:1:0)}}),type:"ShortName",size:e.Type({read:function(e){var t=e._size;switch(t){case 0:return this.binary.view.byteLength-this.binary.tell()+8;case 1:return this.binary.read("uint64");default:return t}},write:function(e){e>=Math.pow(2,32)&&this.binary.write("uint64",e)}}),_end:function(e){return e._begin+e.size}},FullBox:["extend","BoxHeader",{version:"uint8",flags:24}],Box:e.Type({read:function(){var e=this.binary.skip(0,function(){return this.read("BoxHeader")}),t=this.binary.read(e.type)||e;return t===e&&console.log(e.type),this.binary.seek(e._end),t},write:function(e){this.binary.write(e.type,e);var t=this.binary.tell()-e._begin;this.binary.seek(e._begin,function(){this.write("uint32",t)})}}),Time:e.Template({params:["baseType"],read:function(){var e=this.baseRead();if(e)return new Date(e+t)},write:function(e){this.baseWrite(e-t>>>0)}}),FixedPoint:e.Template({params:["baseType"],setParams:function(e,t){this.coef=1<<t},read:function(){return this.baseRead()/this.coef},write:function(e){this.baseWrite(e*this.coef)}}),Atoms:e.Type({params:["end"],read:function(){for(var e={},t=this.toValue(this.end)||this.binary.getContext("_end")._end;this.binary.tell()<t;){var i=this.binary.read("Box");(e[i.type]||(e[i.type]=[])).push(i)}return e},write:function(e){for(var t in e)for(var i=e[t],n=0,a=i.length;n<a;n++)i[n].type=t,this.binary.write("Box",i[n])}}),ChildAtoms:{atoms:"Atoms"},MultiBox:["extend","BoxHeader","ChildAtoms"],TransformationMatrix:{a:["FixedPoint","uint32",16],b:["FixedPoint","uint32",16],u:["FixedPoint","uint32",30],c:["FixedPoint","uint32",16],d:["FixedPoint","uint32",16],v:["FixedPoint","uint32",30],x:["FixedPoint","uint32",16],y:["FixedPoint","uint32",16],w:["FixedPoint","uint32",30]},Volume:["FixedPoint","uint16",8],FBVersionable:e.Template({setParams:function(e,t){this.baseType=["if","version",t,e]}}),FBUint:["FBVersionable","uint32","uint64"],FBTime:["Time","FBUint"],TimestampBox:["extend","FullBox",{creation_time:"FBTime",modification_time:"FBTime"}],DurationBox:["extend","TimestampBox",{timescale:"uint32",duration:"FBUint"}],ftyp:["extend","BoxHeader",{major_brand:"ShortName",minor_version:"uint32",compatible_brands:["array","ShortName",function(){return(this.binary.getContext(1)._end-this.binary.tell())/4}]}],free:"BoxHeader",RawData:{_rawData:["blob",function(){return this.binary.getContext("_end")._end-this.binary.tell()}]},mdat:["extend","BoxHeader","RawData"],ParamSets:e.Template({setParams:function(t){this.baseType=["DynamicArray",t,e.Template({baseType:{length:"uint16",paramSet:["blob","length"]},read:function(){return this.baseRead().paramSet},write:function(e){this.baseWrite({length:e.length,paramSet:e})}})]}}),avcC:["extend","BoxHeader",{version:["const","uint8",1],profileIndication:"uint8",profileCompatibility:"uint8",levelIndication:"uint8",_reserved:["const",6,-1],lengthSizeMinusOne:2,_reserved2:["const",3,-1],seqParamSets:["ParamSets",5],pictParamSets:["ParamSets","uint8"]}],moov:"MultiBox",mvhd:["extend","DurationBox",{rate:"Rate",volume:"Volume",_reserved:["skip",10],matrix:"TransformationMatrix",_reserved2:["skip",24],next_track_ID:"uint32"}],trak:"MultiBox",tkhd:["extend","TimestampBox",{track_ID:"uint32",_reserved:["skip",4],duration:"FBUint",_reserved2:["skip",8],layer:"int16",alternate_group:"uint16",volume:"Volume",_reserved3:["skip",2],matrix:"TransformationMatrix",dimensions:["Dimensions","Rate"]}],tref:"MultiBox",TrackReferenceTypeBox:["extend","BoxHeader",{track_IDs:["array","uint32",function(){return(this.binary.getContext(1)._end-this.binary.tell())/4}]}],hint:"TrackReferenceTypeBox",cdsc:"TrackReferenceTypeBox",hind:"TrackReferenceTypeBox",mdia:"MultiBox",mdhd:["extend","DurationBox",{_padding:1,lang:e.Type({read:function(){return String.fromCharCode.apply(String,this.binary.read(["array",5,3]).map(function(e){return e+96}))},write:function(e){for(var t=0;t<3;t++)this.binary.write(5,e.charCodeAt(t)-96)}}),_reserved:["skip",2]}],hdlr:["extend","FullBox",{_reserved:["skip",4],handler_type:"ShortName",_set_handler_type:function(e){this.binary.getContext(i("trak"))._handler_type=e.handler_type},_reserved2:["skip",12],name:"string0"}],minf:"MultiBox",vmhd:["extend","FullBox",{graphicsmode:"uint16",opcolor:{r:"uint16",g:"uint16",b:"uint16"}}],smhd:["extend","FullBox",{balance:["FixedPoint","int16",8],_reserved:["skip",2]}],hmhd:["extend","FullBox",{maxPDUsize:"uint16",avgPDUsize:"uint16",maxbitrate:"uint32",avgbitrate:"uint32",_reserved:["skip",4]}],stbl:"MultiBox",SampleEntry:["extend","BoxHeader",{_reserved:["skip",6],data_reference_index:"uint16"}],btrt:["extend","BoxHeader",{bufferSizeDB:"uint32",maxBitrate:"uint32",avgBitrate:"uint32"}],metx:["extend","SampleEntry",{content_encoding:"string0",namespace:"string0",schema_location:"string0",bitratebox:"btrt"}],mett:["extend","SampleEntry",{content_encoding:"string0",mime_format:"string0",bitratebox:"btrt"}],pasp:["extend","BoxHeader",{spacing:["Dimensions","uint32"]}],ClapInnerFormat:["Dimensions",{N:"uint32",D:"uint32"}],clap:["extend","BoxHeader",{cleanAperture:"ClapInnerFormat",off:"ClapInnerFormat"}],VisualSampleEntry:["extend","SampleEntry",{_reserved:["skip",16],dimensions:["Dimensions","uint16"],resolution:["Dimensions","Rate"],_reserved2:["skip",4],frame_count:["const","uint16",1],compressorname:e.Template({baseType:{length:"uint8",string:["string","length"],_skip:["skip",function(e){return 31-e.length}]},read:function(){return this.baseRead().string},write:function(e){this.baseWrite({length:e.length,string:e})}}),depth:"uint16",_reserved3:["const","int16",-1]},e.Type({setParams:function(){this.optional={cleanaperture:"clap",pixelaspectratio:"pasp"}},read:function(){var e={};for(var t in this.optional){var i=this.optional[t];this.binary.skip(0,function(){return this.read("BoxHeader")}).type===i&&(e[t]=this.binary.read(i))}return e},write:function(e){for(var t in this.optional){var i=e[t];i&&this.binary.write(this.optional[t],i)}}}),"ChildAtoms"],AudioSampleEntry:["extend","SampleEntry",{_reserved:["skip",8],channelcount:"uint16",samplesize:"uint16",_reserved2:["skip",4],samplerate:"Rate"},"ChildAtoms"],DynamicArray:e.Template({setParams:function(e,t){this.baseType={length:e,array:["array",t,"length"]}},read:function(){return this.baseRead().array},write:function(e){this.baseWrite({length:e.length,array:e})}}),ArrayBox:e.Template({setParams:function(e){this.baseType=["extend","FullBox",{entries:["DynamicArray","uint32",e]}]}}),stsd:["ArrayBox",e.Template({getBaseType:function(){return{soun:"AudioSampleEntry",vide:"VisualSampleEntry",meta:"Box"}[this.binary.getContext(i("trak"))._handler_type]||"SampleEntry"},write:function(e){var t=this.binary.tell();this.baseWrite(e);var i=this.binary.tell()-t;this.binary.seek(t,function(){this.write("uint32",i)})}})],stdp:["extend","FullBox",{priorities:["array","uint16",function(){return this.binary.getContext(i("stbl"))._sample_count}]}],stsl:["extend","FullBox",{_reserved:7,constraint_flag:"bool",scale_method:["enum","uint8",[!1,"fill","hidden","meet","slice-x","slice-y"]],display_center:["Dimensions","int16"]}],stts:["ArrayBox",{sample_count:"uint32",sample_delta:"uint32"}],ctts:["ArrayBox",{sample_count:"uint32",sample_offset:"uint32"}],stss:["ArrayBox","uint32"],stsh:["ArrayBox",{shadowed_sample_number:"uint32",sync_sample_number:"uint32"}],ExtendedBoolean:["enum",2,[void 0,!0,!1]],sdtp:["extend","FullBox",{dependencies:["array",{_reserved:2,sample_depends_on:"ExtendedBoolean",sample_is_depended_on:"ExtendedBoolean",sample_has_redundancy:"ExtendedBoolean"},function(){return this.binary.getContext(i("stbl"))._sample_count}]}],edts:"MultiBox",elst:["ArrayBox",{segment_duration:"FBUint",media_time:["FBVersionable","int32","int64"],media_rate:"Rate"}],dinf:"MultiBox","url ":["extend","FullBox",{location:"string0"}],"urn ":["extend","FullBox",{name:"string0",location:"string0"}],dref:["ArrayBox","Box"],stsz:["extend","FullBox",{sample_size:"uint32",sample_count:"uint32",_sample_count_to_stbl:function(e){this.binary.getContext(i("stbl"))._sample_count=e.sample_count},sample_sizes:["if_not","sample_size",["array","uint32","sample_count"]]}],stz2:["extend","FullBox",{_reserved:["skip",3],field_size:"uint8",sample_count:"uint32",_sample_count_to_stbl:function(e){this.binary.getContext(i("stbl"))._sample_count=e.sample_count},sample_sizes:["array",e.Template({getBaseType:function(e){return e.field_size}}),"sample_count"]}],stsc:["ArrayBox",{first_chunk:"uint32",samples_per_chunk:"uint32",sample_description_index:"uint32"}],stco:["ArrayBox","uint32"],co64:["ArrayBox","uint64"],padb:["extend","FullBox",{pads:["DynamicArray","uint32",e.Template({baseType:{_skip:["const",1,0],pad:3},read:function(){return this.baseRead().pad},write:function(e){this.baseWrite({pad:e})}})]}],subs:["ArrayBox",{sample_delta:"uint32",subsamples:["DynamicArray","uint16",{subsample_size:["FBVersionable","uint16","uint32"],subsample_priority:"uint8",discardable:"uint8",_reserved:["skip",4]}]}],mvex:"MultiBox",mehd:["extend","FullBox",{fragment_duration:"FBUint"}],esds_section:["extend",{descriptor_type:"uint8",ext_type:e.Type({read:function(){var e=this.binary.read("uint8");if(128===e||129===e||254===e)return this.binary.skip(2),e;this.binary.skip(-1)},write:function(e){void 0!==e&&this.binary.write("blob",[e,e,e])}}),length:"uint8"},e.Template({getBaseType:function(t){switch(t.descriptor_type){case 3:return{es_id:"uint16",stream_priority:"uint8"};case 4:return{type:["enum","uint8",{1:"v1",2:"v2",32:"mpeg4_video",33:"mpeg4_avc_sps",34:"mpeg4_avc_pps",64:"mpeg4_audio",96:"mpeg2_simple_video",97:"mpeg2_main_video",98:"mpeg2_snr_video",99:"mpeg2_spatial_video",100:"mpeg2_high_video",101:"mpeg2_422_video",102:"mpeg4_adts_main",103:"mpeg4_adts_low_complexity",104:"mpeg4_adts_scaleable_sampling",105:"mpeg2_adts_main",106:"mpeg1_video",107:"mpeg1_adts",108:"jpeg_video",192:"private_audio",208:"private_video",224:"pcm_little_endian_audio",225:"vorbis_audio",226:"dolby_v3_audio",227:"alaw_audio",228:"mulaw_audio",229:"adpcm_audio",230:"pcm_big_endian_audio",240:"yv12_video",241:"h264_video",242:"h263_video",243:"h261_video"}],stream_type:["enum",6,[null,"object","clock","scene","visual","audio","mpeg-7","ipmp","oci","mpeg-java"]],upstream_flag:1,_reserved:["const",1,1],buffer_size:24,maxBitrate:"uint32",avgBitrate:"uint32"};case 5:return{audio_profile:["enum",5,[null,"aac-main","aac-lc","aac-ssr","aac-ltp","sbr","aac-scalable","twinvq","celp","hxvc",null,null,"ttsi","main-synthesis","wavetable-synthesis","general-midi","algorithmic-synthesis-and-audio-effects","er-aac-lc","reserved","er-aac-ltp","er-aac-scalable","er-twinvq","er-bsac","er-aac-ld","er-celp","er-hvxc","er-hiln","er-parametric","ssc","ps","mpeg-surround"]],sampling_freq:e.Type({setParams:function(){this.freqList=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350]},read:function(){var e=this.binary.read(4);return 15!==e?this.freqList[e]:this.binary.read(24)},write:function(e){var t=this.freqList.indexOf(e);-1!==t?this.binary.write(4,t):(this.binary.write(4,15),this.binary.write(24,e))}}),channelConfig:4,frameLength:["enum",1,[1024,960]],dependsOnCoreCoder:1,extensionFlag:1};case 6:return{sl:["const","uint8",2]}}}})],esds:["extend","FullBox",{sections:e.Template({baseType:"esds_section",read:function(){for(var e=this.binary.getContext("_end")._end,t=[];this.binary.tell()<e;)t.push(this.baseRead());return t},write:function(e){for(var t=0,i=e.length;t<i;t++)this.baseWrite(e[t])}})}],File:["Atoms",function(){return this.binary.view.byteLength}]}});

    // mpegts/h264.js
    !function(i,e){"function"==typeof define&&define.amd?define(["jbinary"],e):"object"==typeof exports?module.exports=e(require("jbinary")):i.H264=e(i.jBinary)}(unsafeWindow,function(i){"use strict";return{ExpGolomb:i.Type({params:["isSigned"],read:function(){for(var i=0;!this.binary.read(1);)i++;var e=1<<i|this.binary.read(i);return this.isSigned?1&e?-(e>>1):e>>1:e-1},write:function(i){this.isSigned?(i<<=1)<=0&&(i=1|-i):i++;var e=i.toString(2).length;this.binary.write(e-1,0),this.binary.write(e,i)}}),Optional:i.Template({params:["baseType"],read:function(){if(this.binary.read(1))return this.baseRead()},write:function(i){this.binary.write(null!=i?1:0),null!=i&&this.baseWrite(i)}}),ScalingList:i.Template({setParams:function(i){this.baseType=["array",{},i]}}),SPS:["extend",{profile_idc:"uint8",constraint_set_flags:["array",1,8],level_idc:"uint8",seq_parameter_set_id:"ExpGolomb"},["if",function(i){return[100,110,122,244,44,83,86,118].indexOf(i.profile_idc)>=0},{chroma_format:["enum","ExpGolomb",["MONO","YUV420","YUV422","YUV444"]],separate_color_plane_flag:["if",function(i){return"YUV444"===i.chroma_format},1],bit_depth_luma_minus8:"ExpGolomb",bit_depth_chroma_minus8:"ExpGolomb",qpprime_y_zero_transform_bypass_flag:1,scaling_matrix:["Optional",{scalingList4x4:["array",["ScalingList",16],6],scalingList8x8:["array",["ScalingList",64],function(){return"YUV444"!==this.binary.getContext(1).chroma_format?2:6}]}]}],{log2_max_frame_num_minus4:"ExpGolomb",pic_order_cnt_type:"ExpGolomb",pic_order:["if_not","pic_order_cnt_type",{log2_max_pic_order_cnt_lsb_minus4:"ExpGolomb"},["if",function(i){return 1===i.pic_order_cnt_type},{delta_pic_order_always_zero_flag:1,offset_for_non_ref_pic:["ExpGolomb",!0],offset_for_top_to_bottom_field:["ExpGolomb",!0],_num_ref_frames_in_pic_order_cnt_cycle:i.Template({baseType:"ExpGolomb",write:function(i,e){this.baseWrite(e.offset_for_ref_frame.length)}}),offset_for_ref_frame:["array",["ExpGolomb",!0],function(i){return i._num_ref_frames_in_pic_order_cnt_cycle}]}]],max_num_ref_frames:"ExpGolomb",gaps_in_frame_num_value_allowed_flag:1,pic_width_in_mbs_minus_1:"ExpGolomb",pic_height_in_map_units_minus_1:"ExpGolomb",frame_mbs_only_flag:1,mb_adaptive_frame_field_flag:["if_not","frame_mbs_only_flag",1],direct_8x8_inference_flag:1,frame_cropping:["Optional",{left:"ExpGolomb",right:"ExpGolomb",top:"ExpGolomb",bottom:"ExpGolomb"}]}],NALUnit:i.Type({read:function(){0===this.binary.read(["blob",3])[2]&&this.binary.skip(1);for(var i=this.binary.view.byteLength,e=this.binary.tell(),r=this.binary.skip(0,function(){return this.view.getBytes()}),t=1,n=r.length-3;t<n;t++)if(0===r[t]&&0===r[t+1]&&(1===r[t+2]||0===r[t+2]&&1===r[t+3])){i=e+t;break}return this.binary.read(["blob",i-e])}})}});

    // mpegts/pes.js
    !function(t,e){"function"==typeof define&&define.amd?define(["jbinary"],e):"object"==typeof exports?module.exports=e(require("jbinary")):t.PES=e(t.jBinary)}(unsafeWindow,function(t){"use strict";return{Flag:t.Template({baseType:1,params:["dependentField"],write:function(t,e){this.baseWrite(this.dependentField in e?1:0)}}),FlagDependent:t.Template({params:["flagField","baseType"],read:function(){return this.binary.read(["if",this.flagField,this.baseType])}}),PESTimeStamp:t.Template({setParams:function(t){var e=["const",1,1,!0];this.baseType={_prefix:["const",4,t,!0],hiPart:3,_skip1:e,midPart:15,_skip2:e,loPart:15,_skip3:e}},read:function(){var t=this.baseRead();return t.loPart|t.midPart<<15|t.hiPart<<30},write:function(t){this.baseWrite({hiPart:t>>>30,midPart:t>>>15&32767,loPart:32767&t})}}),PESPacket:["extend",{_startCode0:["const","uint8",0,!0],_startCode1:["const","uint8",0,!0],_startCode2:["const","uint8",1,!0],streamId:"uint8",length:"uint16",_end:function(t){var e=this.binary.tell(),a=t.length;if(a){if((e+=a)>this.view.byteLength-4)return e;if(0===(i=this.binary.read(["blob",4],e))[0]&&0===i[1]&&1===i[2]&&128&i[3])return e;e-=a}for(var n=this.view.byteLength,i=this.binary.read("blob",e),r=0;r<i.length-4;r++)if(0===i[r]&&0===i[r+1]&&1===i[r+2]&&128&i[r+3])return e+r;return n}},t.Template({baseType:{_marker:["const",2,2,!0],scramblingControl:["enum",2,["not_scrambled"]],priority:1,dataAlignmentIndicator:1,hasCopyright:1,isOriginal:1,_hasPTS:["Flag","pts"],_hasDTS:["Flag","dts"],_hasESCR:["Flag","escr"],_hasESRate:["Flag","esRate"],dsmTrickMode:1,_hasAdditionalCopyInfo:["Flag","additionalCopyInfo"],_hasPESCRC:["Flag","pesCRC"],_hasExtension:["Flag","extension"],dataLength:"uint8",_headerEnd:function(t){return this.binary.tell()+t.dataLength},pts:["FlagDependent","_hasPTS",["if","_hasDTS",["PESTimeStamp",3],["PESTimeStamp",2]]],dts:["FlagDependent","_hasDTS",["PESTimeStamp",1]],_toHeaderEnd:function(t){this.binary.seek(t._headerEnd)}},read:function(){var t=this.binary.tell();try{return this.baseRead()}catch(e){this.binary.seek(t),this.binary.view.alignBy()}}}),{data:["blob",function(){return this.binary.getContext("_end")._end-this.binary.tell()}]}]}});

    // mpegts/adts.js
    !function(e,n){"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?module.exports=n():e.ADTS=n()}(unsafeWindow,function(){"use strict";return{ADTSPacket:{_start:function(){return this.binary.tell()},_syncWord:["const",12,4095,!0],version:["enum",1,["mpeg-4","mpeg-2"]],layer:["const",2,0],isProtectionAbsent:1,profileMinusOne:2,samplingFreq:["enum",4,[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350]],_privateStream:1,channelConfig:3,_reserved:4,frameLength:13,bufferFullness:11,aacFramesCountMinusOne:2,data:["blob",function(e){return e.frameLength-(this.binary.tell()-e._start)}]}}});

    // mpegts/index.js
    !function(e,t){"function"==typeof define&&define.amd?define(["jdataview","jbinary","./mp4","./h264","./pes","./adts"],t):"object"==typeof exports?module.exports=t(require("jdataview"),require("jbinary"),require("./mp4"),require("./h264"),require("./pes"),require("./adts")):e.mpegts_to_mp4=t(e.jDataView,e.jBinary,e.MP4,e.H264,e.PES,e.ADTS)}(unsafeWindow,function(e,t,s,a,r,n){"use strict";return function(i){for(var l=i.read("File"),o=new e(i.view.byteLength),d=0,m=l.length;d<m;d++){(u=l[d]).adaptationField;var p=u.payload;p&&p._rawStream&&o.writeBytes(p._rawStream)}var f=new t(o.slice(0,o.tell()),r),_=new t(o.byteLength,n),c=[];for(o=new e(o.byteLength);f.tell()<f.view.byteLength;){var u;if(192===(u=f.read("PESPacket")).streamId)_.write("blob",u.data);else if(224===u.streamId){var g=new t(u.data,a),h=u.pts,v=u.dts,y={offset:o.tell(),pts:h,dts:void 0!==v?v:h};for(c.push(y);g.tell()<g.view.byteLength;){var b=g.read("NALUnit");switch(31&b[0]){case 7:if(!w){var w=b,k=new t(w,a).read("SPS"),x=16*(k.pic_width_in_mbs_minus_1+1),z=(2-k.frame_mbs_only_flag)*(k.pic_height_in_map_units_minus_1+1)*16,S=k.frame_cropping;S&&(x-=2*(S.left+S.right),z-=2*(S.top+S.bottom))}break;case 8:if(!D)var D=b;break;case 5:y.isIDR=!0;default:o.writeUint32(b.length),o.writeBytes(b)}}}}c.push({offset:o.tell()});var I=[],j=[],q=[],P=[],B=c[0],L={sum:0,count:0},M=0;for(d=0,m=c.length-1;d<m;d++){var F=c[d+1];I.push(F.offset-B.offset);var C=F.dts-B.dts;C?(j.push({sample_count:1,sample_delta:C}),M+=C,L.sum+=C,L.count++):j.length++,B.isIDR&&q.push(d+1),P.push({first_chunk:P.length+1,sample_count:1,sample_offset:B.dtsFix=B.pts-B.dts}),B=F}L=Math.round(L.sum/L.count);for(d=0,m=j.length;d<m;d++)void 0===j[d]&&(j[d]={first_chunk:d+1,sample_count:1,sample_delta:L},M+=L);var A=!0;for(d=1,m=j.length;d<m;d++)if(j[d].sample_delta!==j[0].sample_delta){A=!1;break}A&&(j=[{first_chunk:1,sample_count:I.length,sample_delta:j[0].sample_delta}]);var H,E=o.tell(),O=_.tell(),R=[],T=0;for(_.seek(0);_.tell()<O;)H=_.read("ADTSPacket"),R.push(H.data.length),H.data.length>T&&(T=H.data.length),o.writeBytes(H.data);var U=new t(o.byteLength,s),V=[{atoms:{tkhd:[{version:0,flags:15,track_ID:1,duration:M,layer:0,alternate_group:0,volume:1,matrix:{a:1,b:0,x:0,c:0,d:1,y:0,u:0,v:0,w:1},dimensions:{horz:x,vert:z}}],mdia:[{atoms:{mdhd:[{version:0,flags:0,timescale:9e4,duration:M,lang:"und"}],hdlr:[{version:0,flags:0,handler_type:"vide",name:"VideoHandler"}],minf:[{atoms:{vmhd:[{version:0,flags:1,graphicsmode:0,opcolor:{r:0,g:0,b:0}}],dinf:[{atoms:{dref:[{version:0,flags:0,entries:[{type:"url ",version:0,flags:1,location:""}]}]}}],stbl:[{atoms:{stsd:[{version:0,flags:0,entries:[{type:"avc1",data_reference_index:1,dimensions:{horz:x,vert:z},resolution:{horz:72,vert:72},frame_count:1,compressorname:"",depth:24,atoms:{avcC:[{version:1,profileIndication:k.profile_idc,profileCompatibility:parseInt(k.constraint_set_flags.join(""),2),levelIndication:k.level_idc,lengthSizeMinusOne:3,seqParamSets:[w],pictParamSets:[D]}]}}]}],stts:[{version:0,flags:0,entries:j}],stss:[{version:0,flags:0,entries:q}],ctts:[{version:0,flags:0,entries:P}],stsc:[{version:0,flags:0,entries:[{first_chunk:1,samples_per_chunk:I.length,sample_description_index:1}]}],stsz:[{version:0,flags:0,sample_size:0,sample_count:I.length,sample_sizes:I}],stco:[{version:0,flags:0,entries:[40]}]}}]}}]}}]}}];O>0&&V.push({atoms:{tkhd:[{version:0,flags:15,track_ID:2,duration:M,layer:0,alternate_group:1,volume:1,matrix:{a:1,b:0,x:0,c:0,d:1,y:0,u:0,v:0,w:1},dimensions:{horz:0,vert:0}}],mdia:[{atoms:{mdhd:[{version:0,flags:0,timescale:9e4,duration:M,lang:"eng"}],hdlr:[{version:0,flags:0,handler_type:"soun",name:"SoundHandler"}],minf:[{atoms:{smhd:[{version:0,flags:0,balance:0}],dinf:[{atoms:{dref:[{version:0,flags:0,entries:[{type:"url ",version:0,flags:1,location:""}]}]}}],stbl:[{atoms:{stsd:[{version:0,flags:0,entries:[{type:"mp4a",data_reference_index:1,channelcount:2,samplesize:16,samplerate:22050,atoms:{esds:[{version:0,flags:0,sections:[{descriptor_type:3,ext_type:128,length:34,es_id:2,stream_priority:0},{descriptor_type:4,ext_type:128,length:20,type:"mpeg4_audio",stream_type:"audio",upstream_flag:0,buffer_size:0,maxBitrate:Math.round(T/(M/9e4/R.length)),avgBitrate:Math.round((o.tell()-E)/(M/9e4))},{descriptor_type:5,ext_type:128,length:2,audio_profile:H.profileMinusOne+1,sampling_freq:H.samplingFreq,channelConfig:H.channelConfig},{descriptor_type:6,ext_type:128,length:1,sl:2}]}]}}]}],stts:[{version:0,flags:0,entries:[{sample_count:R.length,sample_delta:Math.round(M/R.length)}]}],stsc:[{version:0,flags:0,entries:[{first_chunk:1,samples_per_chunk:R.length,sample_description_index:1}]}],stsz:[{version:0,flags:0,sample_size:0,sample_count:R.length,sample_sizes:R}],stco:[{version:0,flags:0,entries:[40+E]}]}}]}}]}}]}});var N=new Date;return U.write("File",{ftyp:[{major_brand:"isom",minor_version:512,compatible_brands:["isom","iso2","avc1","mp41"]}],mdat:[{_rawData:o.getBytes(o.tell(),0)}],moov:[{atoms:{mvhd:[{version:0,flags:0,creation_time:N,modification_time:N,timescale:9e4,duration:M,rate:1,volume:1,matrix:{a:1,b:0,x:0,c:0,d:1,y:0,u:0,v:0,w:1},next_track_ID:2}],trak:V}}]}),U.slice(0,U.tell())}});

    // QRCode
    let QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this.parsedData=[];for(var b=[],d=0,e=this.data.length;e>d;d++){var f=this.data.charCodeAt(d);f>65536?(b[0]=240|(1835008&f)>>>18,b[1]=128|(258048&f)>>>12,b[2]=128|(4032&f)>>>6,b[3]=128|63&f):f>2048?(b[0]=224|(61440&f)>>>12,b[1]=128|(4032&f)>>>6,b[2]=128|63&f):f>128?(b[0]=192|(1984&f)>>>6,b[1]=128|63&f):b[0]=f,this.parsedData=this.parsedData.concat(b)}this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function b(a,b){this.typeNumber=a,this.errorCorrectLevel=b,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function i(a,b){if(void 0==a.length)throw new Error(a.length+"/"+b);for(var c=0;c<a.length&&0==a[c];)c++;this.num=new Array(a.length-c+b);for(var d=0;d<a.length-c;d++)this.num[d]=a[d+c]}function j(a,b){this.totalCount=a,this.dataCount=b}function k(){this.buffer=[],this.length=0}function m(){return"undefined"!=typeof CanvasRenderingContext2D}function n(){var a=!1,b=navigator.userAgent;return/android/i.test(b)&&(a=!0,aMat=b.toString().match(/android ([0-9]\.[0-9])/i),aMat&&aMat[1]&&(a=parseFloat(aMat[1]))),a}function r(a,b){for(var c=1,e=s(a),f=0,g=l.length;g>=f;f++){var h=0;switch(b){case d.L:h=l[f][0];break;case d.M:h=l[f][1];break;case d.Q:h=l[f][2];break;case d.H:h=l[f][3]}if(h>=e)break;c++}if(c>l.length)throw new Error("Too long data");return c}function s(a){var b=encodeURI(a).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return b.length+(b.length!=a?3:0)}a.prototype={getLength:function(){return this.parsedData.length},write:function(a){for(var b=0,c=this.parsedData.length;c>b;b++)a.put(this.parsedData[b],8)}},b.prototype={addData:function(b){var c=new a(b);this.dataList.push(c),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b)throw new Error(a+","+b);return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var d=0;d<this.moduleCount;d++){this.modules[d]=new Array(this.moduleCount);for(var e=0;e<this.moduleCount;e++)this.modules[d][e]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(a,c),this.typeNumber>=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=b.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,b){for(var c=-1;7>=c;c++)if(!(-1>=a+c||this.moduleCount<=a+c))for(var d=-1;7>=d;d++)-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)},getBestMaskPattern:function(){for(var a=0,b=0,c=0;8>c;c++){this.makeImpl(!0,c);var d=f.getLostPoint(this);(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var d=a.createEmptyMovieClip(b,c),e=1;this.make();for(var f=0;f<this.modules.length;f++)for(var g=f*e,h=0;h<this.modules[f].length;h++){var i=h*e,j=this.modules[f][h];j&&(d.beginFill(0,100),d.moveTo(i,g),d.lineTo(i+e,g),d.lineTo(i+e,g+e),d.lineTo(i,g+e),d.endFill())}return d},setupTimingPattern:function(){for(var a=8;a<this.moduleCount-8;a++)null==this.modules[a][6]&&(this.modules[a][6]=0==a%2);for(var b=8;b<this.moduleCount-8;b++)null==this.modules[6][b]&&(this.modules[6][b]=0==b%2)},setupPositionAdjustPattern:function(){for(var a=f.getPatternPosition(this.typeNumber),b=0;b<a.length;b++)for(var c=0;c<a.length;c++){var d=a[b],e=a[c];if(null==this.modules[d][e])for(var g=-2;2>=g;g++)for(var h=-2;2>=h;h++)this.modules[d+g][e+h]=-2==g||2==g||-2==h||2==h||0==g&&0==h?!0:!1}},setupTypeNumber:function(a){for(var b=f.getBCHTypeNumber(this.typeNumber),c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(var c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){for(var c=this.errorCorrectLevel<<3|b,d=f.getBCHTypeInfo(c),e=0;15>e;e++){var g=!a&&1==(1&d>>e);6>e?this.modules[e][8]=g:8>e?this.modules[e+1][8]=g:this.modules[this.moduleCount-15+e][8]=g}for(var e=0;15>e;e++){var g=!a&&1==(1&d>>e);8>e?this.modules[8][this.moduleCount-e-1]=g:9>e?this.modules[8][15-e-1+1]=g:this.modules[8][15-e-1]=g}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){for(var c=-1,d=this.moduleCount-1,e=7,g=0,h=this.moduleCount-1;h>0;h-=2)for(6==h&&h--;;){for(var i=0;2>i;i++)if(null==this.modules[d][h-i]){var j=!1;g<a.length&&(j=1==(1&a[g]>>>e));var k=f.getMask(b,d,h-i);k&&(j=!j),this.modules[d][h-i]=j,e--,-1==e&&(g++,e=7)}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}},b.PAD0=236,b.PAD1=17,b.createData=function(a,c,d){for(var e=j.getRSBlocks(a,c),g=new k,h=0;h<d.length;h++){var i=d[h];g.put(i.mode,4),g.put(i.getLength(),f.getLengthInBits(i.mode,a)),i.write(g)}for(var l=0,h=0;h<e.length;h++)l+=e[h].dataCount;if(g.getLengthInBits()>8*l)throw new Error("code length overflow. ("+g.getLengthInBits()+">"+8*l+")");for(g.getLengthInBits()+4<=8*l&&g.put(0,4);0!=g.getLengthInBits()%8;)g.putBit(!1);for(;;){if(g.getLengthInBits()>=8*l)break;if(g.put(b.PAD0,8),g.getLengthInBits()>=8*l)break;g.put(b.PAD1,8)}return b.createBytes(g,e)},b.createBytes=function(a,b){for(var c=0,d=0,e=0,g=new Array(b.length),h=new Array(b.length),j=0;j<b.length;j++){var k=b[j].dataCount,l=b[j].totalCount-k;d=Math.max(d,k),e=Math.max(e,l),g[j]=new Array(k);for(var m=0;m<g[j].length;m++)g[j][m]=255&a.buffer[m+c];c+=k;var n=f.getErrorCorrectPolynomial(l),o=new i(g[j],n.getLength()-1),p=o.mod(n);h[j]=new Array(n.getLength()-1);for(var m=0;m<h[j].length;m++){var q=m+p.getLength()-h[j].length;h[j][m]=q>=0?p.get(q):0}}for(var r=0,m=0;m<b.length;m++)r+=b[m].totalCount;for(var s=new Array(r),t=0,m=0;d>m;m++)for(var j=0;j<b.length;j++)m<g[j].length&&(s[t++]=g[j][m]);for(var m=0;e>m;m++)for(var j=0;j<b.length;j++)m<h[j].length&&(s[t++]=h[j][m]);return s};for(var c={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},d={L:1,M:0,Q:3,H:2},e={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},f={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(a){for(var b=a<<10;f.getBCHDigit(b)-f.getBCHDigit(f.G15)>=0;)b^=f.G15<<f.getBCHDigit(b)-f.getBCHDigit(f.G15);return(a<<10|b)^f.G15_MASK},getBCHTypeNumber:function(a){for(var b=a<<12;f.getBCHDigit(b)-f.getBCHDigit(f.G18)>=0;)b^=f.G18<<f.getBCHDigit(b)-f.getBCHDigit(f.G18);return a<<12|b},getBCHDigit:function(a){for(var b=0;0!=a;)b++,a>>>=1;return b},getPatternPosition:function(a){return f.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,b,c){switch(a){case e.PATTERN000:return 0==(b+c)%2;case e.PATTERN001:return 0==b%2;case e.PATTERN010:return 0==c%3;case e.PATTERN011:return 0==(b+c)%3;case e.PATTERN100:return 0==(Math.floor(b/2)+Math.floor(c/3))%2;case e.PATTERN101:return 0==b*c%2+b*c%3;case e.PATTERN110:return 0==(b*c%2+b*c%3)%2;case e.PATTERN111:return 0==(b*c%3+(b+c)%2)%2;default:throw new Error("bad maskPattern:"+a)}},getErrorCorrectPolynomial:function(a){for(var b=new i([1],0),c=0;a>c;c++)b=b.multiply(new i([1,g.gexp(c)],0));return b},getLengthInBits:function(a,b){if(b>=1&&10>b)switch(a){case c.MODE_NUMBER:return 10;case c.MODE_ALPHA_NUM:return 9;case c.MODE_8BIT_BYTE:return 8;case c.MODE_KANJI:return 8;default:throw new Error("mode:"+a)}else if(27>b)switch(a){case c.MODE_NUMBER:return 12;case c.MODE_ALPHA_NUM:return 11;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 10;default:throw new Error("mode:"+a)}else{if(!(41>b))throw new Error("type:"+b);switch(a){case c.MODE_NUMBER:return 14;case c.MODE_ALPHA_NUM:return 13;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 12;default:throw new Error("mode:"+a)}}},getLostPoint:function(a){for(var b=a.getModuleCount(),c=0,d=0;b>d;d++)for(var e=0;b>e;e++){for(var f=0,g=a.isDark(d,e),h=-1;1>=h;h++)if(!(0>d+h||d+h>=b))for(var i=-1;1>=i;i++)0>e+i||e+i>=b||(0!=h||0!=i)&&g==a.isDark(d+h,e+i)&&f++;f>5&&(c+=3+f-5)}for(var d=0;b-1>d;d++)for(var e=0;b-1>e;e++){var j=0;a.isDark(d,e)&&j++,a.isDark(d+1,e)&&j++,a.isDark(d,e+1)&&j++,a.isDark(d+1,e+1)&&j++,(0==j||4==j)&&(c+=3)}for(var d=0;b>d;d++)for(var e=0;b-6>e;e++)a.isDark(d,e)&&!a.isDark(d,e+1)&&a.isDark(d,e+2)&&a.isDark(d,e+3)&&a.isDark(d,e+4)&&!a.isDark(d,e+5)&&a.isDark(d,e+6)&&(c+=40);for(var e=0;b>e;e++)for(var d=0;b-6>d;d++)a.isDark(d,e)&&!a.isDark(d+1,e)&&a.isDark(d+2,e)&&a.isDark(d+3,e)&&a.isDark(d+4,e)&&!a.isDark(d+5,e)&&a.isDark(d+6,e)&&(c+=40);for(var k=0,e=0;b>e;e++)for(var d=0;b>d;d++)a.isDark(d,e)&&k++;var l=Math.abs(100*k/b/b-50)/5;return c+=10*l}},g={glog:function(a){if(1>a)throw new Error("glog("+a+")");return g.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;a>=256;)a-=255;return g.EXP_TABLE[a]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},h=0;8>h;h++)g.EXP_TABLE[h]=1<<h;for(var h=8;256>h;h++)g.EXP_TABLE[h]=g.EXP_TABLE[h-4]^g.EXP_TABLE[h-5]^g.EXP_TABLE[h-6]^g.EXP_TABLE[h-8];for(var h=0;255>h;h++)g.LOG_TABLE[g.EXP_TABLE[h]]=h;i.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var b=new Array(this.getLength()+a.getLength()-1),c=0;c<this.getLength();c++)for(var d=0;d<a.getLength();d++)b[c+d]^=g.gexp(g.glog(this.get(c))+g.glog(a.get(d)));return new i(b,0)},mod:function(a){if(this.getLength()-a.getLength()<0)return this;for(var b=g.glog(this.get(0))-g.glog(a.get(0)),c=new Array(this.getLength()),d=0;d<this.getLength();d++)c[d]=this.get(d);for(var d=0;d<a.getLength();d++)c[d]^=g.gexp(g.glog(a.get(d))+b);return new i(c,0).mod(a)}},j.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],j.getRSBlocks=function(a,b){var c=j.getRsBlockTable(a,b);if(void 0==c)throw new Error("bad rs block @ typeNumber:"+a+"/errorCorrectLevel:"+b);for(var d=c.length/3,e=[],f=0;d>f;f++)for(var g=c[3*f+0],h=c[3*f+1],i=c[3*f+2],k=0;g>k;k++)e.push(new j(h,i));return e},j.getRsBlockTable=function(a,b){switch(b){case d.L:return j.RS_BLOCK_TABLE[4*(a-1)+0];case d.M:return j.RS_BLOCK_TABLE[4*(a-1)+1];case d.Q:return j.RS_BLOCK_TABLE[4*(a-1)+2];case d.H:return j.RS_BLOCK_TABLE[4*(a-1)+3];default:return void 0}},k.prototype={get:function(a){var b=Math.floor(a/8);return 1==(1&this.buffer[b]>>>7-a%8)},put:function(a,b){for(var c=0;b>c;c++)this.putBit(1==(1&a>>>b-c-1))},getLengthInBits:function(){return this.length},putBit:function(a){var b=Math.floor(this.length/8);this.buffer.length<=b&&this.buffer.push(0),a&&(this.buffer[b]|=128>>>this.length%8),this.length++}};var l=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]],o=function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){function g(a,b){var c=document.createElementNS("http://www.w3.org/2000/svg",a);for(var d in b)b.hasOwnProperty(d)&&c.setAttribute(d,b[d]);return c}var b=this._htOption,c=this._el,d=a.getModuleCount();Math.floor(b.width/d),Math.floor(b.height/d),this.clear();var h=g("svg",{viewBox:"0 0 "+String(d)+" "+String(d),width:"100%",height:"100%",fill:b.colorLight});h.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"),c.appendChild(h),h.appendChild(g("rect",{fill:b.colorDark,width:"1",height:"1",id:"template"}));for(var i=0;d>i;i++)for(var j=0;d>j;j++)if(a.isDark(i,j)){var k=g("use",{x:String(i),y:String(j)});k.setAttributeNS("http://www.w3.org/1999/xlink","href","#template"),h.appendChild(k)}},a.prototype.clear=function(){for(;this._el.hasChildNodes();)this._el.removeChild(this._el.lastChild)},a}(),p="svg"===document.documentElement.tagName.toLowerCase(),q=p?o:m()?function(){function a(){this._elImage.src=this._elCanvas.toDataURL("image/png"),this._elImage.style.display="block",this._elCanvas.style.display="none"}function d(a,b){var c=this;if(c._fFail=b,c._fSuccess=a,null===c._bSupportDataURI){var d=document.createElement("img"),e=function(){c._bSupportDataURI=!1,c._fFail&&_fFail.call(c)},f=function(){c._bSupportDataURI=!0,c._fSuccess&&c._fSuccess.call(c)};return d.onabort=e,d.onerror=e,d.onload=f,d.src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",void 0}c._bSupportDataURI===!0&&c._fSuccess?c._fSuccess.call(c):c._bSupportDataURI===!1&&c._fFail&&c._fFail.call(c)}if(this._android&&this._android<=2.1){var b=1/window.devicePixelRatio,c=CanvasRenderingContext2D.prototype.drawImage;CanvasRenderingContext2D.prototype.drawImage=function(a,d,e,f,g,h,i,j){if("nodeName"in a&&/img/i.test(a.nodeName))for(var l=arguments.length-1;l>=1;l--)arguments[l]=arguments[l]*b;else"undefined"==typeof j&&(arguments[1]*=b,arguments[2]*=b,arguments[3]*=b,arguments[4]*=b);c.apply(this,arguments)}}var e=function(a,b){this._bIsPainted=!1,this._android=n(),this._htOption=b,this._elCanvas=document.createElement("canvas"),this._elCanvas.width=b.width,this._elCanvas.height=b.height,a.appendChild(this._elCanvas),this._el=a,this._oContext=this._elCanvas.getContext("2d"),this._bIsPainted=!1,this._elImage=document.createElement("img"),this._elImage.style.display="none",this._el.appendChild(this._elImage),this._bSupportDataURI=null};return e.prototype.draw=function(a){var b=this._elImage,c=this._oContext,d=this._htOption,e=a.getModuleCount(),f=d.width/e,g=d.height/e,h=Math.round(f),i=Math.round(g);b.style.display="none",this.clear();for(var j=0;e>j;j++)for(var k=0;e>k;k++){var l=a.isDark(j,k),m=k*f,n=j*g;c.strokeStyle=l?d.colorDark:d.colorLight,c.lineWidth=1,c.fillStyle=l?d.colorDark:d.colorLight,c.fillRect(m,n,f,g),c.strokeRect(Math.floor(m)+.5,Math.floor(n)+.5,h,i),c.strokeRect(Math.ceil(m)-.5,Math.ceil(n)-.5,h,i)}this._bIsPainted=!0},e.prototype.makeImage=function(){this._bIsPainted&&d.call(this,a)},e.prototype.isPainted=function(){return this._bIsPainted},e.prototype.clear=function(){this._oContext.clearRect(0,0,this._elCanvas.width,this._elCanvas.height),this._bIsPainted=!1},e.prototype.round=function(a){return a?Math.floor(1e3*a)/1e3:a},e}():function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){for(var b=this._htOption,c=this._el,d=a.getModuleCount(),e=Math.floor(b.width/d),f=Math.floor(b.height/d),g=['<table style="border:0;border-collapse:collapse;">'],h=0;d>h;h++){g.push("<tr>");for(var i=0;d>i;i++)g.push('<td style="border:0;border-collapse:collapse;padding:0;margin:0;width:'+e+"px;height:"+f+"px;background-color:"+(a.isDark(h,i)?b.colorDark:b.colorLight)+';"></td>');g.push("</tr>")}g.push("</table>"),c.innerHTML=g.join("");var j=c.childNodes[0],k=(b.width-j.offsetWidth)/2,l=(b.height-j.offsetHeight)/2;k>0&&l>0&&(j.style.margin=l+"px "+k+"px")},a.prototype.clear=function(){this._el.innerHTML=""},a}();QRCode=function(a,b){if(this._htOption={width:256,height:256,typeNumber:4,colorDark:"#000000",colorLight:"#ffffff",correctLevel:d.H},"string"==typeof b&&(b={text:b}),b)for(var c in b)this._htOption[c]=b[c];"string"==typeof a&&(a=document.getElementById(a)),this._android=n(),this._el=a,this._oQRCode=null,this._oDrawing=new q(this._el,this._htOption),this._htOption.text&&this.makeCode(this._htOption.text)},QRCode.prototype.makeCode=function(a){this._oQRCode=new b(r(a,this._htOption.correctLevel),this._htOption.correctLevel),this._oQRCode.addData(a),this._oQRCode.make(),this._el.title=a,this._oDrawing.draw(this._oQRCode),this.makeImage()},QRCode.prototype.makeImage=function(){"function"==typeof this._oDrawing.makeImage&&(!this._android||this._android>=3)&&this._oDrawing.makeImage()},QRCode.prototype.clear=function(){this._oDrawing.clear()},QRCode.CorrectLevel=d}();
    //await wait(1000);

    const playlistBaseUrl = 'https://lens.zhihu.com/api/videos/';
    const videoBaseUrl = 'https://v.vzuu.com/video/';
    const videoId = window.location.pathname.split('/').pop(); // 视频id
    const menuStyle = 'transform:none !important; left:auto !important; right:-0.5em !important;';
    const playerSelector = '#player';
    const controlBarSelector = playerSelector + ' > div:first-child > div:last-child > div:last-child > div:first-child';
    const svgDownload = '<path d="M9.5,4 H14.5 V10 H17.8 L12,15.8 L6.2,10 H9.5 Z M6.2,18 H17.8 V20 H6.2 Z"></path>';
    const svgCircle = '<circle cx="12" cy="12" r="8" fill="none" stroke-width="2" stroke="#555" />' +
        '<text x="50%" y="50%" dy=".4em" text-anchor="middle" fill="#fff" font-size="9"></text>' +
        '<path fill="none" r="8" transform="translate(12,12)" stroke-width="2" stroke="#fff" />';
    const svgConvert = '<circle cx="12" cy="12" r="8" fill="none" stroke-width="2" stroke="#fff" />' +
        '<path d="M13,7 L17,10 V11 H7 V10 H15 L12,8 Z M9,16 L7,14 V13 H17 V14 H9 L10,16 Z"></path>';
    const wechatIcon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABuElEQVQ4T6WSv2uTQRjHv9/L+4YiCWpbo6jgJE5u4lIVAnYwl6SjIFLQv8HBRcFFBBcVoaXgIl0UMVwuBHR0sLSdClKogw5iqyIogjhE7itXUnkb3qagBzfc8+PzPPd9HuI/D7P5zrkJY8w5SSnJDWPMmrX21bAamwDv/R4ATwHYwWBJi0mSXK3Vaqt5IHrvxwG8BnB8SKUfks43m83lwRi22+27JK9FRwjhkDHmPoCLANTr9Q4kSfKI5JSk9XK5fKxarf7OQiLgE8mDfeNHSRWSaXxL+kByRNIzkl9IPq7X6++2Abz3PwFEDfLOCwC3JN0keRLAYQBfATwolUp3Yjexg5ckJ3Oy34QQrpN8TrKY419K0/RCFPG0pAWSJhsk6RLJGQB7AdyQNEXylKTbJM8CiHd2a4xXAMwBSLYgIYTLxpj5jDYjJMckfQZAkhVJ3/8ukvd+Q9IvAOMky5Kmo2i7LOq3TUC32z0aQjhjrX1CUtHW6XT2S3rf/8JOnIfbVnkwyjk3SbKzg4gLhUKhOhQQgc65EyTv9cd4pL8bowAmGo3Gyq6AvN5brda+YrFYsda+/SdAFvoH5C+l3GRotdcAAAAASUVORK5CYII=';
    let videos = []; // 存储各分辨率的视频信息
    let format = []; // 下载的格式; ts, mp4
    let blobs = null; // 存储视频段
    let ratio;
    let errors = 0;

    while (!document.querySelector(playerSelector).childNodes.length) {
        await wait(500);
    }

    const domControlBar = document.querySelector(controlBarSelector);
    const domFullScreenBtn = document.querySelector(controlBarSelector + '> div:nth-last-of-type(1)');
    const domResolutionBtn = document.querySelector(controlBarSelector + '> div:nth-last-of-type(3)');
    let domDownloadBtn = domResolutionBtn.cloneNode(true); // 克隆分辨率按钮为下载按钮
    let domMenuItem = domDownloadBtn.querySelectorAll('button')[1];
    let domMenu = domMenuItem.parentNode;

    function wait(time) {
        return new Promise(function (resolve, reject) {
            setTimeout(resolve, time);
        });
    }

    function fetchRetry(url, options = {}, times = 1, delay = 1000, checkStatus = true) {
        return new Promise((resolve, reject) => {
            // fetch 成功处理函数
            function success(res) {
                if (checkStatus && !res.ok) {
                    failure(res);
                } else {
                    resolve(res);
                }
            }

            // 单次失败处理函数
            function failure(error) {
                times--;

                if (times) {
                    setTimeout(fetchUrl, delay);
                }
                else {
                    reject(error);
                }
            }

            // 总体失败处理函数
            function finalHandler(error) {
                throw error;
            }

            function fetchUrl() {
                return fetch(url, options)
                    .then(success)
                    .catch(failure)
                    .catch(finalHandler);
            }

            fetchUrl();
        });
    }

    function fileSize(size) {
        let n = Math.log(size) / Math.log(1024) | 0;
        return (size / Math.pow(1024, n)).toFixed(0) + ' ' + (n ? 'KMGTPEZY'[--n] + 'B' : 'Bytes');
    }

    // 下载 m3u8 文件
    async function downloadM3u8(url) {
        const res = await fetchRetry(url, {}, 3);
        const m3u8 = await res.text();
        let i = 0;

        blobs = [];
        ratio = 0;
        errors = 0;

        // 初始化进度显示
        domDownloadBtn.querySelector('svg').innerHTML = svgCircle;
        updateProgress(0);

        m3u8.split('\n').forEach(function (line) {
            if (line.match(/\.ts/)) {
                blobs[i] = undefined;
                downloadTs(url.replace(/\/[^\/]+?$/, '/' + line), i++);
            }
        });
    }

    // 下载 m3u8 文件中的单个 ts 文件
    async function downloadTs(url, order) {
        let res;
        let blob;

        try {
            res = await fetchRetry(url, {}, 5);
            blob = await res.blob();

        } catch (e) {
            if (++errors == 1) {
                resetDownloadIcon();
                alert('下载视频失败,请重新下载。');
            }
            return;
        }

        ratio++;
        blobs[order] = blob;

        errors ? resetDownloadIcon() : updateProgress(Math.round(100 * ratio / blobs.length));

        store();
    }

    // 保存视频文件
    async function store() {
        for (let [index, blob] of blobs.entries()) {
            if (blob === undefined) return;
        }

        let blob = new Blob(blobs, {type: 'video/h264'});

        blobs = null;

        if (format == 'mp4') {
            domDownloadBtn.querySelector('svg').innerHTML = svgConvert;
            blob = await convertToMp4(blob);
        }

        downloadBlob(blob);
    }

    // 下载 blob 里的视频
    function downloadBlob(blob) {
        let name = (new Date()).valueOf() + '.mp4';
        let navigator = window.navigator;
        let url;

        // 结束进度显示
        resetDownloadIcon();

        // edge
        if (navigator && navigator.msSaveBlob) {
            navigator.msSaveBlob(blob, name);
        }
        else {
            url = URL.createObjectURL(blob);

            // Chrome 可以使用 Tampermonkey 的 GM_download 函数绕过 CSP(Content Security Policy) 的限制
            if (navigator.userAgent.indexOf('Chrome') > 0 && window.GM_download) {
                GM_download({url, name});
            }
            else {
                // firefox 需要禁用 CSP, about:config -> security.csp.enable => false
                // violentmonkey(暴力猴)没有 GM_download 函数
                var a = document.createElement('a');
                document.body.appendChild(a);
                a.href = url;
                a.download = name;
                //a.target = '_blank';
                a.click();
                document.body.removeChild(a);

                setTimeout(function () {
                    URL.revokeObjectURL(url);
                }, 100);
            }
        }
    }

    // 重置下载图标
    function resetDownloadIcon() {
        domDownloadBtn.querySelector('svg').innerHTML = svgDownload;
    }

    // 更新下载进度界面
    function updateProgress(percent) {
        let r = 8;
        let degrees = (percent == 100 ? 99.9999 : percent) / 100 * 360; // 进度对应的角度值
        let rad = degrees * (Math.PI / 180); // 角度对应的弧度值
        let x = (Math.sin(rad) * r).toFixed(2); // 极坐标转换成直角坐标
        let y = -(Math.cos(rad) * r).toFixed(2);
        let lenghty = Number(degrees > 180); // 大于180°时画大角度弧,小于180°时画小角度弧,(deg > 180) ? 1 : 0
        let paths = ['M', 0, -r, 'A', r, r, 0, lenghty, 1, x, y]; // path 属性

        domDownloadBtn.querySelector('svg > path').setAttribute('d', paths.join(' '));
        domDownloadBtn.querySelector('svg > text').textContent = percent;
    }

    // ts blob -> mp4 blob
    async function convertToMp4(blob) {
        let mpegts = await unsafeWindow.jBinary.load(blob, unsafeWindow.MPEGTS);
        let mp4 = unsafeWindow.mpegts_to_mp4(mpegts);
        let res = await fetch(mp4.toURI());
        blob = await res.blob();
        return blob;
    }

    function showShareQrcode() {
        const url = videoBaseUrl + videoId;
        //const img = jrQrcode.getQrBase64(url, {width: 200, height: 200});
        const maskHtml =
            `<div id="download-video-mask"
                  style="position:absolute;
                         top:0; right:0; bottom:0; left:0; 
                         background-color:rgba(0,0,0,0.5);
                         z-index:99999;
                         display:flex; justify-content:center; align-items:center;"
                  onclick="document.body.removeChild(this)">
                 <div id="download-video-qrcode" style="position:relative; text-align:center; padding:10px; background-color:#fff;"></div>
            </div>`;
        let template = document.createElement('template');
        let mask;

        template.innerHTML = maskHtml;
        mask = template.content.firstChild;
        new QRCode(mask.querySelector('#download-video-qrcode'), {
            text: url,
            width: 256,
            height: 256,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.H
        });
        document.body.appendChild(mask);
    }

    //await wait(500);

    // 获取视频信息
    const res = await fetchRetry(playlistBaseUrl + videoId, {
        headers: {
            'referer': 'refererBaseUrl + videoId',
            'authorization': 'oauth c3cef7c66a1843f8b3a9e6a1e3160e20' // in zplayer.min.js of zhihu
        }
    }, 3);
    const videoInfo = await res.json();

    // 获取不同分辨率视频的信息
    for (let [key, video] of Object.entries(videoInfo.playlist)) {
        video.name = key;
        videos.push(video);
    }

    // 按分辨率大小排序
    videos = videos.sort(function (v1, v2) {
        return v1.width == v2.width ? 0 : (v1.width > v2.width ? 1 : -1);
    }).reverse();

    // 生成下载按钮图标
    domDownloadBtn.querySelector('button:first-child').outerHTML = domFullScreenBtn.cloneNode(true).querySelector('button').outerHTML;
    domDownloadBtn.querySelector('svg').innerHTML = svgDownload;

    // 生成菜单项
    domMenuItem.className = domMenuItem.className.split('-').shift();
    domMenuItem.parentNode.innerHTML = '';

    // 分享到微信
    let node = domMenuItem.cloneNode();
    node.innerHTML = `<img src="${wechatIcon}" style="vertical-align:middle;"> 分享到微信`;
    node.style.width = '100%';
    node.style.textAlign = 'left';
    node.dataset.action = 'wechat';
    domMenu.appendChild(node);

    // mp4 菜单项
    if (['Tampermonkey', 'Violentmonkey'].includes(GM_info.scriptHandler)) {
        for (let [index, video] of videos.entries()) {
            if (index == videos.length - 1) continue; // 最低分辨率转换出来的视频在微信中无法正常播放
            let node = domMenuItem.cloneNode();
            node.innerHTML = `MP4 - ${video.width}`;
            node.style.width = '100%';
            node.style.textAlign = 'left';
            node.dataset.action = 'download';
            node.dataset.videoIndex = index;
            node.dataset.videoFormat = 'mp4';
            domMenu.appendChild(node);
        }
    }

    // ts 菜单项
    for (let [index, video] of videos.entries()) {
        let node = domMenuItem.cloneNode();
        node.innerHTML = `TS - ${video.width} (${fileSize(video.size)})`;
        node.style.width = '100%';
        node.style.textAlign = 'left';
        node.dataset.action = 'download';
        node.dataset.videoIndex = index;
        node.dataset.videoFormat = 'ts';
        domMenu.appendChild(node);
    }

    // 鼠标事件 - 显示菜单
    domDownloadBtn.addEventListener('pointerenter', () => {
        if (blobs === null) {
            domMenu.parentNode.style.cssText = menuStyle + 'opacity:1 !important; visibility:visible !important';
        }
    });

    // 鼠标事件 - 隐藏菜单
    domDownloadBtn.addEventListener('pointerleave', () => {
        if (blobs === null) {
            domMenu.parentNode.style.cssText = menuStyle;
        }
    });

    // 鼠标事件 - 暂停下载
    // domDownloadBtn.addEventListener('pointerdown', () => {});

    // 鼠标事件 - 选择菜单项
    domDownloadBtn.addEventListener('pointerup', event => {
        let e = event.srcElement || event.target;
        let action = e.dataset.action;
        let video;

        if (action) {
            if (action == 'wechat') {
                showShareQrcode();
            }
            else if (action == 'download') {
                video = videos[e.dataset.videoIndex];
                format = e.dataset.videoFormat;

                downloadM3u8(video.play_url);
            }

            // 隐藏菜单
            domMenu.dispatchEvent(new MouseEvent('pointerleave', {
                'bubbles': true,
                'cancelable': true
            }));
        }
    });

    // 显示下载按钮
    domControlBar.appendChild(domDownloadBtn);
})();