nile.js
Version:
A tool for scalable peer-to-peer video streaming using WebTorrent
1 lines • 296 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Broadcaster",[],t):"object"==typeof exports?exports.Broadcaster=t():e.Broadcaster=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="dist",t(t.s=33)}({0:function(e,t,n){"use strict";var r,o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(e){"object"===("undefined"==typeof window?"undefined":o(window))&&(r=window)}e.exports=r},12:function(e,t,n){"use strict";(function(e,t){!function(e,n){function r(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n<t.length;n++)t[n]=arguments[n+1];var r={callback:e,args:t};return c[u]=r,a(u),u++}function o(e){delete c[e]}function i(e){var t=e.callback,r=e.args;switch(r.length){case 0:t();break;case 1:t(r[0]);break;case 2:t(r[0],r[1]);break;case 3:t(r[0],r[1],r[2]);break;default:t.apply(n,r)}}function s(e){if(f)setTimeout(s,0,e);else{var t=c[e];if(t){f=!0;try{i(t)}finally{o(e),f=!1}}}}if(!e.setImmediate){var a,u=1,c={},f=!1,d=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,"[object process]"==={}.toString.call(e.process)?function(){a=function(e){t.nextTick(function(){s(e)})}}():function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?function(){var t="setImmediate$"+Math.random()+"$",n=function(n){n.source===e&&"string"==typeof n.data&&0===n.data.indexOf(t)&&s(+n.data.slice(t.length))};e.addEventListener?e.addEventListener("message",n,!1):e.attachEvent("onmessage",n),a=function(n){e.postMessage(t+n,"*")}}():e.MessageChannel?function(){var e=new MessageChannel;e.port1.onmessage=function(e){s(e.data)},a=function(t){e.port2.postMessage(t)}}():d&&"onreadystatechange"in d.createElement("script")?function(){var e=d.documentElement;a=function(t){var n=d.createElement("script");n.onreadystatechange=function(){s(t),n.onreadystatechange=null,e.removeChild(n),n=null},e.appendChild(n)}}():function(){a=function(e){setTimeout(s,0,e)}}(),h.setImmediate=r,h.clearImmediate=o}}("undefined"==typeof self?void 0===e?void 0:e:self)}).call(t,n(0),n(4))},14:function(e,t,n){"use strict";function r(e,t){this._id=e,this._clearFn=t}var o=Function.prototype.apply;t.setTimeout=function(){return new r(o.call(setTimeout,window,arguments),clearTimeout)},t.setInterval=function(){return new r(o.call(setInterval,window,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},r.prototype.unref=r.prototype.ref=function(){},r.prototype.close=function(){this._clearFn.call(window,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},n(12),t.setImmediate=setImmediate,t.clearImmediate=clearImmediate},30:function(e,t,n){"use strict";(function(n){function r(e){if(!e)throw"MediaStream is mandatory.";this.start=function(n){var r;"undefined"!=typeof MediaRecorder?r=c:(k||E||w)&&(-1!==this.mimeType.indexOf("video")?r=h:-1!==this.mimeType.indexOf("audio")&&(r=f)),"image/gif"===this.mimeType&&(r=p),"audio/wav"!==this.mimeType&&"audio/pcm"!==this.mimeType||(r=f),this.recorderType&&(r=this.recorderType),t=new r(e),t.blobs=[];var o=this;t.ondataavailable=function(e){t.blobs.push(e),o.ondataavailable(e)},t.onstop=this.onstop,t.onStartedDrawingNonBlankFrames=this.onStartedDrawingNonBlankFrames,t=i(t,this),t.start(n)},this.onStartedDrawingNonBlankFrames=function(){},this.clearOldRecordedFrames=function(){t&&t.clearOldRecordedFrames()},this.stop=function(){t&&t.stop()},this.ondataavailable=function(e){console.log("ondataavailable..",e)},this.onstop=function(e){console.warn("stopped..",e)},this.save=function(e,n){if(!e){if(!t)return;return void ConcatenateBlobs(t.blobs,t.blobs[0].type,function(e){s(e)})}s(e,n)},this.pause=function(){t&&(t.pause(),console.log("Paused recording.",this.mimeType||t.mimeType))},this.resume=function(){t&&(t.resume(),console.log("Resumed recording.",this.mimeType||t.mimeType))},this.recorderType=null,this.mimeType="video/webm",this.disableLogs=!1;var t}function o(e){if(!e)throw"MediaStream is mandatory.";var t=this,n=u();this.stream=e,this.start=function(u){function c(e){a++,t.ondataavailable(e)}o=new r(e),i=new r(e),o.mimeType="audio/ogg",i.mimeType="video/webm";for(var f in this)"function"!=typeof this[f]&&(o[f]=i[f]=this[f]);o.ondataavailable=function(e){s[a]||(s[a]={}),s[a].audio=e,s[a].video&&!s[a].onDataAvailableEventFired&&(s[a].onDataAvailableEventFired=!0,c(s[a]))},i.ondataavailable=function(e){if(n)return t.ondataavailable({video:e,audio:e});s[a]||(s[a]={}),s[a].video=e,s[a].audio&&!s[a].onDataAvailableEventFired&&(s[a].onDataAvailableEventFired=!0,c(s[a]))},i.onstop=o.onstop=function(e){t.onstop(e)},n?i.start(u):(i.onStartedDrawingNonBlankFrames=function(){i.clearOldRecordedFrames(),o.start(u)},i.start(u))},this.stop=function(){o&&o.stop(),i&&i.stop()},this.ondataavailable=function(e){console.log("ondataavailable..",e)},this.onstop=function(e){console.warn("stopped..",e)},this.pause=function(){o&&o.pause(),i&&i.pause()},this.resume=function(){o&&o.resume(),i&&i.resume()};var o,i,s={},a=0}function i(e,t){for(var n in t)"function"!=typeof t[n]&&(e[n]=t[n]);return e}function s(e,t){if(!e)throw"Blob object is required.";if(!e.type)try{e.type="video/webm"}catch(e){}var n=(e.type||"video/webm").split("/")[1];if(t&&-1!==t.indexOf(".")){var r=t.split(".");t=r[0],n=r[1]}var o=(t||Math.round(9999999999*Math.random())+888888888)+"."+n;if(void 0!==navigator.msSaveOrOpenBlob)return navigator.msSaveOrOpenBlob(e,o);if(void 0!==navigator.msSaveBlob)return navigator.msSaveBlob(e,o);var i=document.createElement("a");i.href=b.createObjectURL(e),i.target="_blank",i.download=o,navigator.mozGetUserMedia&&(i.onclick=function(){(document.body||document.documentElement).removeChild(i)},(document.body||document.documentElement).appendChild(i));var s=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});i.dispatchEvent(s),navigator.mozGetUserMedia||b.revokeObjectURL(i.href)}function a(e){var t=["Bytes","KB","MB","GB","TB"];if(0===e)return"0 Bytes";var n=parseInt(Math.floor(Math.log(e)/Math.log(1e3)),10);return(e/Math.pow(1e3,n)).toPrecision(3)+" "+t[n]}function u(){var e=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,t=!!window.chrome&&!e;if(void 0!==window.InstallTrigger)return!0;if(!t)return!1;var n,r,o=(navigator.appVersion,navigator.userAgent),i=""+parseFloat(navigator.appVersion),s=parseInt(navigator.appVersion,10);return t&&(n=o.indexOf("Chrome"),i=o.substring(n+7)),-1!==(r=i.indexOf(";"))&&(i=i.substring(0,r)),-1!==(r=i.indexOf(" "))&&(i=i.substring(0,r)),s=parseInt(""+i,10),isNaN(s)&&(i=""+parseFloat(navigator.appVersion),s=parseInt(navigator.appVersion,10)),s>=49}function c(e){function t(){if("active"in e){if(!e.active)return!1}else if("ended"in e&&e.ended)return!1;return!0}var n=this;this.start=function(t,o){if(n.mimeType||(n.mimeType="video/webm"),-1!==n.mimeType.indexOf("audio")&&e.getVideoTracks().length&&e.getAudioTracks().length){var i;navigator.mozGetUserMedia?(i=new x,i.addTrack(e.getAudioTracks()[0])):i=new x(e.getAudioTracks()),e=i}-1!==n.mimeType.indexOf("audio")&&(n.mimeType=k?"audio/webm":"audio/ogg"),n.dontFireOnDataAvailableEvent=!1;var s={mimeType:n.mimeType};n.disableLogs||o||console.log("Passing following params over MediaRecorder API.",s),r&&(r=null),k&&!u()&&(s="video/vp8");try{r=new MediaRecorder(e,s)}catch(t){r=new MediaRecorder(e)}"canRecordMimeType"in r&&!1===r.canRecordMimeType(n.mimeType)&&(n.disableLogs||console.warn("MediaRecorder API seems unable to record mimeType:",n.mimeType)),r.ignoreMutedMedia=n.ignoreMutedMedia||!1;var a=!1;r.ondataavailable=function(e){if(!n.dontFireOnDataAvailableEvent&&e.data&&e.data.size&&!(e.data.size<26800)&&!a){a=!0;var o=n.getNativeBlob?e.data:new Blob([e.data],{type:n.mimeType||"video/webm"});n.ondataavailable(o),n.dontFireOnDataAvailableEvent=!0,r&&(r.stop(),r=null),n.start(t,"__disableLogs")}},r.onerror=function(e){n.disableLogs||("InvalidState"===e.name?console.error("The MediaRecorder is not in a state in which the proposed operation is allowed to be executed."):"OutOfMemory"===e.name?console.error("The UA has exhaused the available memory. User agents SHOULD provide as much additional information as possible in the message attribute."):"IllegalStreamModification"===e.name?console.error("A modification to the stream has occurred that makes it impossible to continue recording. An example would be the addition of a Track while recording is occurring. User agents SHOULD provide as much additional information as possible in the message attribute."):"OtherRecordingError"===e.name?console.error("Used for an fatal error other than those listed above. User agents SHOULD provide as much additional information as possible in the message attribute."):"GenericError"===e.name?console.error("The UA cannot provide the codec or recording option that has been requested.",e):console.error("MediaRecorder Error",e)),r&&"inactive"!==r.state&&"stopped"!==r.state&&r.stop()};try{r.start(36e5)}catch(e){r=null}setTimeout(function(){r&&"recording"===r.state&&r.requestData()},t)},this.stop=function(e){r&&"recording"===r.state&&(r.requestData(),setTimeout(function(){n.dontFireOnDataAvailableEvent=!0,r&&"recording"===r.state&&r.stop(),r=null},2e3))},this.pause=function(){r&&"recording"===r.state&&r.pause()},this.ondataavailable=function(e){console.log("recorded-blob",e)},this.resume=function(){if(this.dontFireOnDataAvailableEvent){this.dontFireOnDataAvailableEvent=!1;var e=n.disableLogs;return n.disableLogs=!0,this.record(),void(n.disableLogs=e)}r&&"paused"===r.state&&r.resume()},this.clearRecordedData=function(){r&&(this.pause(),this.dontFireOnDataAvailableEvent=!0,this.stop())};var r;!function e(){if(r)return!1===t()?void n.stop():void setTimeout(e,1e3)}()}function f(e){this.start=function(r){r=r||1e3,t=new d(e,this),t.record(),n=setInterval(function(){t.requestData()},r)},this.stop=function(){t&&(t.stop(),clearTimeout(n))},this.pause=function(){t&&t.pause()},this.resume=function(){t&&t.resume()},this.ondataavailable=function(){};var t,n}function d(e,t){function n(e,t){for(var n=e.length+t.length,r=new Float32Array(n),o=0,i=0;i<n;)r[i++]=e[o],r[i++]=t[o],o++;return r}function r(e,t){for(var n=new Float32Array(t),r=0,o=e.length,i=0;i<o;i++){var s=e[i];n.set(s,r),r+=s.length}return n}function o(e,t,n){for(var r=n.length,o=0;o<r;o++)e.setUint8(t+o,n.charCodeAt(o))}function i(e){for(var t=e.length,n=new Int16Array(t);t--;)n[t]=65535*e[t];return n.buffer}var s=44100;S.AudioContextConstructor||(S.AudioContextConstructor=new S.AudioContext),s=S.AudioContextConstructor.sampleRate;var u,c,f,d,h=[],l=[],p=!1,m=0,g=t.sampleRate||s,y=t.mimeType||"audio/wav",v=y.indexOf("audio/pcm")>-1,_=t.audioChannels||2;this.record=function(){p=!0,h.length=l.length=0,m=0},this.requestData=function(){if(!E){if(0===m)return void(w=!1);w=!0;var e=h.slice(0),s=l.slice(0),u=m;h.length=l.length=[],m=0,w=!1;var c=r(e,u),f=c;if(2===_){f=n(c,r(s,u))}if(v){var d=new Blob([i(f)],{type:"audio/pcm"});return console.debug("audio recorded blob size:",a(d.size)),void t.ondataavailable(d)}var p=new ArrayBuffer(44+2*f.length),y=new DataView(p);o(y,0,"RIFF"),y.setUint32(4,44+2*f.length-8,!0),o(y,8,"WAVE"),o(y,12,"fmt "),y.setUint32(16,16,!0),y.setUint16(20,1,!0),y.setUint16(22,_,!0),y.setUint32(24,g,!0),y.setUint32(28,g*_*2,!0),y.setUint16(32,2*_,!0),y.setUint16(34,16,!0),o(y,36,"data"),y.setUint32(40,2*f.length,!0);for(var b=f.length,k=44,x=0;x<b;x++)y.setInt16(k,32767*f[x],!0),k+=2;var d=new Blob([y],{type:"audio/wav"});console.debug("audio recorded blob size:",a(d.size)),t.ondataavailable(d)}},this.stop=function(){p=!1,this.requestData(),f.disconnect()};var d=S.AudioContextConstructor;S.VolumeGainNode=d.createGain();var c=S.VolumeGainNode;S.AudioInput=d.createMediaStreamSource(e);var f=S.AudioInput;f.connect(c);var b=t.bufferSize||2048;if(0===t.bufferSize&&(b=0),d.createJavaScriptNode)u=d.createJavaScriptNode(b,_,_);else{if(!d.createScriptProcessor)throw"WebAudio API has no support on this browser.";u=d.createScriptProcessor(b,_,_)}b=u.bufferSize,console.debug("using audio buffer-size:",b);var w=!1;window.scriptprocessornode=u,1===_&&console.debug("All right-channels are skipped.");var E=!1;this.pause=function(){E=!0},this.resume=function(){E=!1},u.onaudioprocess=function(e){if(p&&!w&&!E){var t=e.inputBuffer.getChannelData(0);if(h.push(new Float32Array(t)),2===_){var n=e.inputBuffer.getChannelData(1);l.push(new Float32Array(n))}m+=b}},c.connect(u),u.connect(d.destination)}function h(e){this.start=function(r){r=r||1e3,t=new l(e,this);for(var o in this)"function"!=typeof this[o]&&(t[o]=this[o]);t.record(),n=setInterval(function(){t.requestData()},r)},this.stop=function(){t&&(t.stop(),clearTimeout(n))},this.clearOldRecordedFrames=function(){t&&t.clearOldRecordedFrames()},this.pause=function(){t&&t.pause()},this.resume=function(){t&&t.resume()},this.ondataavailable=function(){};var t,n}function l(e,t){function n(){if(m)return f=(new Date).getTime(),void setTimeout(n,500);if(!u){if(i)return setTimeout(n,100);var e=(new Date).getTime()-f;if(!e)return n();f=(new Date).getTime(),!p.isHTMLObject&&c.paused&&c.play(),l.drawImage(c,0,0,h.width,h.height),u||d.frames.push({duration:e,image:h.toDataURL("image/webp")}),s||r(d.frames[d.frames.length-1])||(s=!0,t.onStartedDrawingNonBlankFrames()),setTimeout(n,10)}}function r(e,t,n){var r=document.createElement("canvas");r.width=h.width,r.height=h.height;var o,i,s,a=r.getContext("2d"),u={r:0,g:0,b:0},c=Math.sqrt(Math.pow(255,2)+Math.pow(255,2)+Math.pow(255,2)),f=t&&t>=0&&t<=1?t:0,d=n&&n>=0&&n<=1?n:0,l=new Image;l.src=e.image,a.drawImage(l,0,0,h.width,h.height);var p=a.getImageData(0,0,h.width,h.height);o=0,i=p.data.length,s=p.data.length/4;for(var m=0;m<i;m+=4){var g={r:p.data[m],g:p.data[m+1],b:p.data[m+2]};Math.sqrt(Math.pow(g.r-u.r,2)+Math.pow(g.g-u.g,2)+Math.pow(g.b-u.b,2))<=c*f&&o++}return!(s-o<=s*d)}function o(e,t,n,r){var o=document.createElement("canvas");o.width=h.width,o.height=h.height;for(var i=o.getContext("2d"),s=[],a=-1===t,u=t&&t>0&&t<=e.length?t:e.length,c={r:0,g:0,b:0},f=Math.sqrt(Math.pow(255,2)+Math.pow(255,2)+Math.pow(255,2)),d=n&&n>=0&&n<=1?n:0,l=r&&r>=0&&r<=1?r:0,p=!1,m=0;m<u;m++){var g,y,v;if(!p){var _=new Image;_.src=e[m].image,i.drawImage(_,0,0,h.width,h.height);var b=i.getImageData(0,0,h.width,h.height);g=0,y=b.data.length,v=b.data.length/4;for(var w=0;w<y;w+=4){var E={r:b.data[w],g:b.data[w+1],b:b.data[w+2]};Math.sqrt(Math.pow(E.r-c.r,2)+Math.pow(E.g-c.g,2)+Math.pow(E.b-c.b,2))<=f*d&&g++}}!p&&v-g<=v*l||(a&&(p=!0),s.push(e[m]))}return s=s.concat(e.slice(u)),s.length<=0&&s.push(e[e.length-1]),s}this.record=function(r){this.width||(this.width=320),this.height||(this.height=240),this.video&&this.video instanceof HTMLVideoElement&&(this.width||(this.width=c.videoWidth||c.clientWidth||320),this.height||(this.height=c.videoHeight||c.clientHeight||240)),this.video||(this.video={width:this.width,height:this.height}),this.canvas&&this.canvas.width&&this.canvas.height||(this.canvas={width:this.width,height:this.height}),h.width=this.canvas.width,h.height=this.canvas.height,this.video&&this.video instanceof HTMLVideoElement?(this.isHTMLObject=!0,c=this.video.cloneNode()):(c=document.createElement("video"),c.src=b.createObjectURL(e),c.width=this.video.width,c.height=this.video.height),c.muted=!0,c.play(),f=(new Date).getTime(),d=new I.Video(t.speed,t.quality),console.log("canvas resolutions",h.width,"*",h.height),console.log("video width/height",c.width||h.width,"*",c.height||h.height),n()},this.clearOldRecordedFrames=function(){d.frames=[]};var i=!1;this.requestData=function(){if(!m){if(!d.frames.length)return void(i=!1);i=!0;var e=d.frames.slice(0);d.frames=o(e,-1),d.compile(function(e){t.ondataavailable(e),console.debug("video recorded blob size:",a(e.size))}),d.frames=[],i=!1}};var s=!1,u=!1;this.stop=function(){u=!0,this.requestData()};var c,f,d,h=document.createElement("canvas"),l=h.getContext("2d"),p=this,m=!1;this.pause=function(){m=!0},this.resume=function(){m=!1}}function p(e){function t(){u=Date.now();var e=new Blob([new Uint8Array(f.stream().bin)],{type:"image/gif"});r.ondataavailable(e),f.stream().bin=[]}if("undefined"==typeof GIFEncoder)throw"Please link: https://cdn.webrtc-experiment.com/gif-recorder.js";this.start=function(e){function r(e){if(n)return void setTimeout(r,500,e);h=requestAnimationFrame(r),void 0===(void 0===c?"undefined":y(c))&&(c=e),e-c<90||(s.paused&&s.play(),i.drawImage(s,0,0,u,l),f.addFrame(i),c=e)}e=e||1e3;var u=this.videoWidth||320,l=this.videoHeight||240;o.width=s.width=u,o.height=s.height=l,f=new GIFEncoder,f.setRepeat(0),f.setDelay(this.frameRate||this.speed||200),f.setQuality(this.quality||1),f.start(),a=Date.now(),h=requestAnimationFrame(r),d=setTimeout(t,e)},this.stop=function(){h&&(cancelAnimationFrame(h),clearTimeout(d),t())};var n=!1;this.pause=function(){n=!0},this.resume=function(){n=!1},this.ondataavailable=function(){},this.onstop=function(){};var r=this,o=document.createElement("canvas"),i=o.getContext("2d"),s=document.createElement("video");s.muted=!0,s.autoplay=!0,s.src=b.createObjectURL(e),s.play();var a,u,c,f,d,h=null}var m,g,y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};void 0!==r&&(r.MultiStreamRecorder=o);var v="Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45";!function(e){"undefined"==typeof window&&("undefined"==typeof window&&void 0!==n&&(n.navigator={userAgent:v,getUserMedia:function(){}},e.window=n),"undefined"==typeof document&&(e.document={},document.createElement=document.captureStream=document.mozCaptureStream=function(){return{}}),"undefined"==typeof location&&(e.location={protocol:"file:",href:"",hash:""}),"undefined"==typeof screen&&(e.screen={width:0,height:0}))}(void 0!==n?n:window);var _=window.AudioContext;void 0===_&&("undefined"!=typeof webkitAudioContext&&(_=webkitAudioContext),"undefined"!=typeof mozAudioContext&&(_=mozAudioContext)),"undefined"==typeof window&&(window={});var _=window.AudioContext;void 0===_&&("undefined"!=typeof webkitAudioContext&&(_=webkitAudioContext),"undefined"!=typeof mozAudioContext&&(_=mozAudioContext));var b=window.URL;void 0===b&&"undefined"!=typeof webkitURL&&(b=webkitURL),"undefined"!=typeof navigator?(void 0!==navigator.webkitGetUserMedia&&(navigator.getUserMedia=navigator.webkitGetUserMedia),void 0!==navigator.mozGetUserMedia&&(navigator.getUserMedia=navigator.mozGetUserMedia)):navigator={getUserMedia:function(){},userAgent:v};var w=!(-1===navigator.userAgent.indexOf("Edge")||!navigator.msSaveBlob&&!navigator.msSaveOrOpenBlob),E=!1;"undefined"!=typeof opera&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("OPR/")&&(E=!0);var k=!w&&!w&&!!navigator.webkitGetUserMedia,x=window.MediaStream;void 0===x&&"undefined"!=typeof webkitMediaStream&&(x=webkitMediaStream),void 0!==x&&("getVideoTracks"in x.prototype||(x.prototype.getVideoTracks=function(){if(!this.getTracks)return[];var e=[];return this.getTracks.forEach(function(t){-1!==t.kind.toString().indexOf("video")&&e.push(t)}),e},x.prototype.getAudioTracks=function(){if(!this.getTracks)return[];var e=[];return this.getTracks.forEach(function(t){-1!==t.kind.toString().indexOf("audio")&&e.push(t)}),e}),"stop"in x.prototype||(x.prototype.stop=function(){this.getAudioTracks().forEach(function(e){e.stop&&e.stop()}),this.getVideoTracks().forEach(function(e){e.stop&&e.stop()})})),"undefined"!=typeof location&&0===location.href.indexOf("file:")&&console.error("Please load this HTML file on HTTP or HTTPS.");var S={AudioContext:_},S={AudioContext:window.AudioContext||window.webkitAudioContext};void 0!==r&&(r.MediaRecorderWrapper=c),void 0!==r&&(r.StereoAudioRecorder=f),void 0!==r&&(r.StereoAudioRecorderHelper=d),void 0!==r&&(r.WhammyRecorder=h),void 0!==r&&(r.WhammyRecorderHelper=l),void 0!==r&&(r.GifRecorder=p);var I=function(){function e(e,t){this.frames=[],e||(e=1),this.duration=1e3/e,this.quality=t||.8}function t(e){var t=b.createObjectURL(new Blob([e.toString(),"this.onmessage = function (e) {"+e.name+"(e.data);}"],{type:"application/javascript"})),n=new Worker(t);return b.revokeObjectURL(t),n}function n(e){function t(e){var t=r(e);if(!t)return[];for(var o=[{id:440786851,data:[{data:1,id:17030},{data:1,id:17143},{data:4,id:17138},{data:8,id:17139},{data:"webm",id:17026},{data:2,id:17031},{data:2,id:17029}]},{id:408125543,data:[{id:357149030,data:[{data:1e6,id:2807729},{data:"whammy",id:19840},{data:"whammy",id:22337},{data:h(t.duration),id:17545}]},{id:374648427,data:[{id:174,data:[{data:1,id:215},{data:1,id:29637},{data:0,id:156},{data:"und",id:2274716},{data:"V_VP8",id:134},{data:"VP8",id:2459272},{data:1,id:131},{id:224,data:[{data:t.width,id:176},{data:t.height,id:186}]}]}]}]}],i=0,s=0;i<e.length;){var u=[],c=0;do{u.push(e[i]),c+=e[i].duration,i++}while(i<e.length&&c<3e4);var f={id:524531317,data:n(s,0,u)};o[1].data.push(f),s+=c}return a(o)}function n(e,t,n){return[{data:e,id:231}].concat(n.map(function(e){var n=u({discardable:0,frame:e.data.slice(4),invisible:0,keyframe:1,lacing:0,trackNum:1,timecode:Math.round(t)});return t+=e.duration,{data:n,id:163}}))}function r(e){if(!e[0])return void postMessage({error:"Something went wrong. Maybe WebP format is not supported in the current browser."});for(var t=e[0].width,n=e[0].height,r=e[0].duration,o=1;o<e.length;o++)r+=e[o].duration;return{duration:r,width:t,height:n}}function o(e){for(var t=[];e>0;)t.push(255&e),e>>=8;return new Uint8Array(t.reverse())}function i(e){return new Uint8Array(e.split("").map(function(e){return e.charCodeAt(0)}))}function s(e){var t=[];e=(e.length%8?new Array(9-e.length%8).join("0"):"")+e;for(var n=0;n<e.length;n+=8)t.push(parseInt(e.substr(n,8),2));return new Uint8Array(t)}function a(e){for(var t=[],n=0;n<e.length;n++){var r=e[n].data;"object"===(void 0===r?"undefined":y(r))&&(r=a(r)),"number"==typeof r&&(r=s(r.toString(2))),"string"==typeof r&&(r=i(r));var u=r.size||r.byteLength||r.length,c=Math.ceil(Math.ceil(Math.log(u)/Math.log(2))/8),f=u.toString(2),d=new Array(7*c+7+1-f.length).join("0")+f,h=new Array(c).join("0")+"1"+d;t.push(o(e[n].id)),t.push(s(h)),t.push(r)}return new Blob(t,{type:"video/webm"})}function u(e){var t=0;if(e.keyframe&&(t|=128),e.invisible&&(t|=8),e.lacing&&(t|=e.lacing<<1),e.discardable&&(t|=1),e.trackNum>127)throw"TrackNumber > 127 not supported";return[128|e.trackNum,e.timecode>>8,255&e.timecode,t].map(function(e){return String.fromCharCode(e)}).join("")+e.frame}function c(e){for(var t=e.RIFF[0].WEBP[0],n=t.indexOf("*"),r=0,o=[];r<4;r++)o[r]=t.charCodeAt(n+3+r);var i,s,a;return a=o[1]<<8|o[0],i=16383&a,a=o[3]<<8|o[2],s=16383&a,{width:i,height:s,data:t,riff:e}}function f(e,t){return parseInt(e.substr(t+4,4).split("").map(function(e){var t=e.charCodeAt(0).toString(2);return new Array(8-t.length+1).join("0")+t}).join(""),2)}function d(e){for(var t=0,n={};t<e.length;){var r=e.substr(t,4),o=f(e,t),i=e.substr(t+4+4,o);t+=8+o,n[r]=n[r]||[],"RIFF"===r||"LIST"===r?n[r].push(d(i)):n[r].push(i)}return n}function h(e){return[].slice.call(new Uint8Array(new Float64Array([e]).buffer),0).map(function(e){return String.fromCharCode(e)}).reverse().join("")}var l=new t(e.map(function(e){var t=c(d(atob(e.image.slice(23))));return t.duration=e.duration,t}));postMessage(l)}return e.prototype.add=function(e,t){if("canvas"in e&&(e=e.canvas),"toDataURL"in e&&(e=e.toDataURL("image/webp",this.quality)),!/^data:image\/webp;base64,/gi.test(e))throw"Input must be formatted properly as a base64 encoded DataURI of type image/webp";this.frames.push({image:e,duration:t||this.duration})},e.prototype.compile=function(e){var r=t(n);r.onmessage=function(t){if(t.data.error)return void console.error(t.data.error);e(t.data)},r.postMessage(this.frames)},{Video:e}}();void 0!==r&&(r.Whammy=I),function(){window.ConcatenateBlobs=function(e,t,n){function r(){if(!e[s])return o();var t=new FileReader;t.onload=function(e){i.push(e.target.result),s++,r()},t.readAsArrayBuffer(e[s])}function o(){var e=0;i.forEach(function(t){e+=t.byteLength});var r=new Uint16Array(e),o=0;i.forEach(function(e){var t=e.byteLength;t%2!=0&&(e=e.slice(0,t-1)),r.set(new Uint16Array(e),o),o+=t});var s=new Blob([r.buffer],{type:t});n(s)}var i=[],s=0;r()}}(),e.exports=r,m=[],void 0!==(g=function(){return r}.apply(t,m))&&(e.exports=g)}).call(t,n(0))},33:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(5),a=r(s),u=n(30),c=r(u),f=function(){function e(t,n,r,i){o(this,e),this.recordInterval=t,this.ID_of_NodeToRenderVideo=n,this.startStreamID=r,this.stopStreamID=i,this.broadcaster=new a.default,this.videoStream=null,this.wasLastBroadcaster1=!1,this.wasLastBroadcaster2=!1,this.createBroadcast(),this.$video=document.getElementById("broadcaster"),this.torrentInfo={magnetURI1:0,magnetURI2:0,magnetURI3:0},this.startSeeding=this.startSeeding.bind(this),this.startStream()}return i(e,[{key:"startStream",value:function(){var e=this.recordInterval,t=this.startSeeding,n=this.videoStream,r=this.$video;this.$video.defaultMuted=!0;var o=window.URL?window.URL.createObjectURL:function(e){return e},i=this.wasLastBroadcaster1,s=this.wasLastBroadcaster1;document.getElementById(""+this.startStreamID).addEventListener("click",function(){function a(a){var u=new c.default(a);u.start(e),u.mimeType="video/webm",u.ondataavailable=function(e){var n=new File([e],"nilejs.webm",{type:"video/webm"});i&&s?(t(n,"magnetURI3","3"),i=s=!1):i?(t(n,"magnetURI2","2"),s=!0):(t(n,"magnetURI1","1"),i=!0)},n=a.getTracks(),r.src=o(a),r.play()}function u(e){console.error("media error",e)}var f={audio:!0,video:!0};navigator.getUserMedia(f,a,u)}),document.getElementById(""+this.stopStreamID).addEventListener("click",function(){r.pause(),n.forEach(function(e){return e.stop()})})}},{key:"startSeeding",value:function(e,t,n){var r=this;this.torrentInfo[t]&&this.broadcaster.remove(this.torrentInfo[t],function(){console.log("magnet "+n+" removed")}),this.broadcaster.seed(e,function(e){r.torrentInfo[t]=e.magnetURI,console.log("broadcaster "+n+" is seeding ",e.magnetURI),r.sendMagnetToServer(e.magnetURI)}),this.broadcaster.on("error",function(e){console.log("webtorrents has encountered an error",e)})}},{key:"sendMagnetToServer",value:function(e){var t=new XMLHttpRequest;t.open("POST","/magnet",!0),t.onreadystatechange=function(){200===this.status?console.log("Magnet Emitted"):console.log("Emit Failed")},t.setRequestHeader("Content-type","application/json"),t.send(JSON.stringify({magnetURI:e}))}},{key:"createBroadcast",value:function(){var e=document.createElement("video");e.setAttribute("id","broadcaster"),document.getElementById(this.ID_of_NodeToRenderVideo).appendChild(e)}}]),e}();e.exports=f},4:function(e,t,n){"use strict";function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(e){if(d===setTimeout)return setTimeout(e,0);if((d===r||!d)&&setTimeout)return d=setTimeout,setTimeout(e,0);try{return d(e,0)}catch(t){try{return d.call(null,e,0)}catch(t){return d.call(this,e,0)}}}function s(e){if(h===clearTimeout)return clearTimeout(e);if((h===o||!h)&&clearTimeout)return h=clearTimeout,clearTimeout(e);try{return h(e)}catch(t){try{return h.call(null,e)}catch(t){return h.call(this,e)}}}function a(){g&&p&&(g=!1,p.length?m=p.concat(m):y=-1,m.length&&u())}function u(){if(!g){var e=i(a);g=!0;for(var t=m.length;t;){for(p=m,m=[];++y<t;)p&&p[y].run();y=-1,t=m.length}p=null,g=!1,s(e)}}function c(e,t){this.fun=e,this.array=t}function f(){}var d,h,l=e.exports={};!function(){try{d="function"==typeof setTimeout?setTimeout:r}catch(e){d=r}try{h="function"==typeof clearTimeout?clearTimeout:o}catch(e){h=o}}();var p,m=[],g=!1,y=-1;l.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];m.push(new c(e,t)),1!==m.length||g||i(u)},c.prototype.run=function(){this.fun.apply(null,this.array)},l.title="browser",l.browser=!0,l.env={},l.argv=[],l.version="",l.versions={},l.on=f,l.addListener=f,l.once=f,l.off=f,l.removeListener=f,l.removeAllListeners=f,l.emit=f,l.prependListener=f,l.prependOnceListener=f,l.listeners=function(e){return[]},l.binding=function(e){throw new Error("process.binding is not supported")},l.cwd=function(){return"/"},l.chdir=function(e){throw new Error("process.chdir is not supported")},l.umask=function(){return 0}},5:function(e,t,n){"use strict";(function(n,r){var o,i,s,a,a,u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};!function(n){if("object"==u(t)&&void 0!==e)e.exports=n();else{i=[],o=n,void 0!==(s="function"==typeof o?o.apply(t,i):o)&&(e.exports=s)}}(function(){var e;return function e(t,n,r){function o(s,u){if(!n[s]){if(!t[s]){var c="function"==typeof a&&a;if(!u&&c)return a(s,!0);if(i)return a(s,!0);var f=new Error("Cannot find module '"+s+"'");throw f.code="MODULE_NOT_FOUND",f}var d=n[s]={exports:{}};t[s][0].call(d.exports,function(e){return o(t[s][1][e]||e)},d,d.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof a&&a,s=0;s<r.length;s++)o(r[s]);return o}({1:[function(e,t,n){function r(e,t){s.Readable.call(this,t),this.destroyed=!1,this._torrent=e._torrent;var n=t&&t.start||0,r=t&&t.end&&t.end<e.length?t.end:e.length-1,o=e._torrent.pieceLength;this._startPiece=(n+e.offset)/o|0,this._endPiece=(r+e.offset)/o|0,this._piece=this._startPiece,this._offset=n+e.offset-this._startPiece*o,this._missing=r-n+1,this._reading=!1,this._notifying=!1,this._criticalLength=Math.min(1048576/o|0,2)}t.exports=r;var o=e("debug")("webtorrent:file-stream"),i=e("inherits"),s=e("readable-stream");i(r,s.Readable),r.prototype._read=function(){this._reading||(this._reading=!0,this._notify())},r.prototype._notify=function(){var e=this;if(e._reading&&0!==e._missing){if(!e._torrent.bitfield.get(e._piece))return e._torrent.critical(e._piece,e._piece+e._criticalLength);if(!e._notifying){e._notifying=!0;var t=e._piece;e._torrent.store.get(t,function(n,r){if(e._notifying=!1,!e.destroyed){if(n)return e._destroy(n);o("read %s (length %s) (err %s)",t,r.length,n&&n.message),e._offset&&(r=r.slice(e._offset),e._offset=0),e._missing<r.length&&(r=r.slice(0,e._missing)),e._missing-=r.length,o("pushing buffer of length %s",r.length),e._reading=!1,e.push(r),0===e._missing&&e.push(null)}}),e._piece+=1}}},r.prototype.destroy=function(e){this._destroy(null,e)},r.prototype._destroy=function(e,t){this.destroyed||(this.destroyed=!0,this._torrent.destroyed||this._torrent.deselect(this._startPiece,this._endPiece,!0),e&&this.emit("error",e),this.emit("close"),t&&t())}},{debug:30,inherits:41,"readable-stream":82}],2:[function(e,t,n){(function(n){function r(e,t){i.call(this),this._torrent=e,this._destroyed=!1,this.name=t.name,this.path=t.path,this.length=t.length,this.offset=t.offset,this.done=!1;var n=t.offset,r=n+t.length-1;this._startPiece=n/this._torrent.pieceLength|0,this._endPiece=r/this._torrent.pieceLength|0,0===this.length&&(this.done=!0,this.emit("done"))}t.exports=r;var o=e("end-of-stream"),i=e("events").EventEmitter,s=e("./file-stream"),a=e("inherits"),u=e("path"),c=e("render-media"),f=e("readable-stream"),d=e("stream-to-blob"),h=e("stream-to-blob-url"),l=e("stream-with-known-length-to-buffer");a(r,i),Object.defineProperty(r.prototype,"downloaded",{get:function(){if(!this._torrent.bitfield)return 0;for(var e=0,t=this._startPiece;t<=this._endPiece;++t)if(this._torrent.bitfield.get(t))e+=this._torrent.pieceLength;else{var n=this._torrent.pieces[t];e+=n.length-n.missing}return e}}),r.prototype.select=function(e){0!==this.length&&this._torrent.select(this._startPiece,this._endPiece,e)},r.prototype.deselect=function(){0!==this.length&&this._torrent.deselect(this._startPiece,this._endPiece,!1)},r.prototype.createReadStream=function(e){var t=this;if(0===this.length){var r=new f.PassThrough;return n.nextTick(function(){r.end()}),r}var i=new s(t,e);return t._torrent.select(i._startPiece,i._endPiece,!0,function(){i._notify()}),o(i,function(){t._destroyed||t._torrent.destroyed||t._torrent.deselect(i._startPiece,i._endPiece,!0)}),i},r.prototype.getBuffer=function(e){l(this.createReadStream(),this.length,e)},r.prototype.getBlob=function(e){if("undefined"==typeof window)throw new Error("browser-only method");d(this.createReadStream(),this._getMimeType(),e)},r.prototype.getBlobURL=function(e){if("undefined"==typeof window)throw new Error("browser-only method");h(this.createReadStream(),this._getMimeType(),e)},r.prototype.appendTo=function(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");c.append(this,e,t,n)},r.prototype.renderTo=function(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");c.render(this,e,t,n)},r.prototype._getMimeType=function(){return c.mime[u.extname(this.name).toLowerCase()]},r.prototype._destroy=function(){this._destroyed=!0,this._torrent=null}}).call(this,e("_process"))},{"./file-stream":1,_process:66,"end-of-stream":33,events:34,inherits:41,path:63,"readable-stream":82,"render-media":83,"stream-to-blob":100,"stream-to-blob-url":99,"stream-with-known-length-to-buffer":101}],3:[function(e,t,n){function r(e,t){var n=this;n.id=e,n.type=t,s("new Peer %s",e),n.addr=null,n.conn=null,n.swarm=null,n.wire=null,n.connected=!1,n.destroyed=!1,n.timeout=null,n.retries=0,n.sentHandshake=!1}function o(){}var i=e("unordered-array-remove"),s=e("debug")("webtorrent:peer"),a=e("bittorrent-protocol"),u=e("./webconn");n.createWebRTCPeer=function(e,t){var n=new r(e.id,"webrtc");return n.conn=e,n.swarm=t,n.conn.connected?n.onConnect():(n.conn.once("connect",function(){n.onConnect()}),n.conn.once("error",function(e){n.destroy(e)}),n.startConnectTimeout()),n},n.createTCPIncomingPeer=function(e){var t=e.remoteAddress+":"+e.remotePort,n=new r(t,"tcpIncoming");return n.conn=e,n.addr=t,n.onConnect(),n},n.createTCPOutgoingPeer=function(e,t){var n=new r(e,"tcpOutgoing");return n.addr=e,n.swarm=t,n},n.createWebSeedPeer=function(e,t){var n=new r(e,"webSeed");return n.swarm=t,n.conn=new u(e,t),n.onConnect(),n},r.prototype.onConnect=function(){var e=this;if(!e.destroyed){e.connected=!0,s("Peer %s connected",e.id),clearTimeout(e.connectTimeout);var t=e.conn;t.once("end",function(){e.destroy()}),t.once("close",function(){e.destroy()}),t.once("finish",function(){e.destroy()}),t.once("error",function(t){e.destroy(t)});var n=e.wire=new a;n.type=e.type,n.once("end",function(){e.destroy()}),n.once("close",function(){e.destroy()}),n.once("finish",function(){e.destroy()}),n.once("error",function(t){e.destroy(t)}),n.once("handshake",function(t,n){e.onHandshake(t,n)}),e.startHandshakeTimeout(),t.pipe(n).pipe(t),e.swarm&&!e.sentHandshake&&e.handshake()}},r.prototype.onHandshake=function(e,t){var n=this;if(n.swarm&&!n.destroyed){if(n.swarm.destroyed)return n.destroy(new Error("swarm already destroyed"));if(e!==n.swarm.infoHash)return n.destroy(new Error("unexpected handshake info hash for this swarm"));if(t===n.swarm.peerId)return n.destroy(new Error("refusing to connect to ourselves"));s("Peer %s got handshake %s",n.id,e),clearTimeout(n.handshakeTimeout),n.retries=0;var r=n.addr;!r&&n.conn.remoteAddress&&(r=n.conn.remoteAddress+":"+n.conn.remotePort),n.swarm._onWire(n.wire,r),n.swarm&&!n.swarm.destroyed&&(n.sentHandshake||n.handshake())}},r.prototype.handshake=function(){var e=this,t={dht:!e.swarm.private&&!!e.swarm.client.dht};e.wire.handshake(e.swarm.infoHash,e.swarm.client.peerId,t),e.sentHandshake=!0},r.prototype.startConnectTimeout=function(){var e=this;clearTimeout(e.connectTimeout),e.connectTimeout=setTimeout(function(){e.destroy(new Error("connect timeout"))},"webrtc"===e.type?25e3:5e3),e.connectTimeout.unref&&e.connectTimeout.unref()},r.prototype.startHandshakeTimeout=function(){var e=this;clearTimeout(e.handshakeTimeout),e.handshakeTimeout=setTimeout(function(){e.destroy(new Error("handshake timeout"))},25e3),e.handshakeTimeout.unref&&e.handshakeTimeout.unref()},r.prototype.destroy=function(e){var t=this;if(!t.destroyed){t.destroyed=!0,t.connected=!1,s("destroy %s (error: %s)",t.id,e&&(e.message||e)),clearTimeout(t.connectTimeout),clearTimeout(t.handshakeTimeout);var n=t.swarm,r=t.conn,a=t.wire;t.swarm=null,t.conn=null,t.wire=null,n&&a&&i(n.wires,n.wires.indexOf(a)),r&&(r.on("error",o),r.destroy()),a&&a.destroy(),n&&n.removePeer(t.id)}}},{"./webconn":6,"bittorrent-protocol":14,debug:30,"unordered-array-remove":111}],4:[function(e,t,n){function r(e){var t=this;t._torrent=e,t._numPieces=e.pieces.length,t._pieces=[],t._onWire=function(e){t.recalculate(),t._initWire(e)},t._onWireHave=function(e){t._pieces[e]+=1},t._onWireBitfield=function(){t.recalculate()},t._torrent.wires.forEach(function(e){t._initWire(e)}),t._torrent.on("wire",t._onWire),t.recalculate()}function o(){return!0}t.exports=r,r.prototype.getRarestPiece=function(e){e||(e=o);for(var t=[],n=1/0,r=0;r<this._numPieces;++r)if(e(r)){var i=this._pieces[r];i===n?t.push(r):i<n&&(t=[r],n=i)}return t.length>0?t[Math.random()*t.length|0]:-1},r.prototype.destroy=function(){var e=this;e._torrent.removeListener("wire",e._onWire),e._torrent.wires.forEach(function(t){e._cleanupWireEvents(t)}),e._torrent=null,e._pieces=null,e._onWire=null,e._onWireHave=null,e._onWireBitfield=null},r.prototype._initWire=function(e){var t=this;e._onClose=function(){t._cleanupWireEvents(e);for(var n=0;n<this._numPieces;++n)t._pieces[n]-=e.peerPieces.get(n)},e.on("have",t._onWireHave),e.on("bitfield",t._onWireBitfield),e.once("close",e._onClose)},r.prototype.recalculate=function(){var e;for(e=0;e<this._numPieces;++e)this._pieces[e]=0;var t=this._torrent.wires.length;for(e=0;e<t;++e)for(var n=this._torrent.wires[e],r=0;r<this._numPieces;++r)this._pieces[r]+=n.peerPieces.get(r)},r.prototype._cleanupWireEvents=function(e){e.removeListener("have",this._onWireHave),e.removeListener("bitfield",this._onWireBitfield),e._onClose&&e.removeListener("close",e._onClose),e._onClose=null}},{}],5:[function(e,t,r){(function(n,r){function o(e,t,n){m.call(this),this._debugId="unknown infohash",this.client=t,this.announce=n.announce,this.urlList=n.urlList,this.path=n.path,this._store=n.store||_,this._getAnnounceOpts=n.getAnnounceOpts,this.strategy=n.strategy||"sequential",this.maxWebConns=n.maxWebConns||4,this._rechokeNumSlots=!1===n.uploads||0===n.uploads?0:+n.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=!1,this.done=!1,this.metadata=null,this.store=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=M(),this._uploadSpeed=M(),this._servers=[],this._xsRequests=[],this._fileModtimes=n.fileModtimes,null!==e&&this._onTorrentId(e),this._debug("new torrent")}function i(e,t){return 2+Math.ceil(t*e.downloadSpeed()/C.BLOCK_LENGTH)}function s(e,t,n){return 1+Math.ceil(t*e.downloadSpeed()/n)}function a(e){return Math.random()*e|0}function u(){}t.exports=o;var c,f=e("addr-to-ip-port"),d=e("bitfield"),h=e("chunk-store-stream/write"),l=e("debug")("webtorrent:torrent"),p=e("torrent-discovery"),m=e("events").EventEmitter,g=e("xtend"),y=e("xtend/mutable"),v=e("fs"),_=e("fs-chunk-store"),b=e("simple-get"),w=e("immediate-chunk-store"),E=e("inherits"),k=e("multistream"),x=e("net"),S=e("os"),I=e("run-parallel"),T=e("run-parallel-limit"),A=e("parse-torrent"),B=e("path"),C=e("torrent-piece"),L=e("pump"),U=e("random-iterate"),R=e("simple-sha1"),M=e("speedometer"),O=e("uniq"),P=e("ut_metadata"),j=e("ut_pex"),H=e("./file"),D=e("./peer"),N=e("./rarity-map"),q=e("./server"),F=5e3,z=3*C.BLOCK_LENGTH,W=[1e3,5e3,15e3],V=e("../package.json").version,G="WebTorrent/"+V+" (https://webtorrent.io)";try{c=B.join(v.statSync("/tmp")&&"/tmp","webtorrent")}catch(e){c=B.join("function"==typeof S.tmpdir?S.tmpdir():"/","webtorrent")}E(o,m),Object.defineProperty(o.prototype,"timeRemaining",{get:function(){return this.done?0:0===this.downloadSpeed?1/0:(this.length-this.downloaded)/this.downloadSpeed*1e3}}),Object.defineProperty(o.prototype,"downloaded",{get:function(){if(!this.bitfield)return 0;for(var e=0,t=0,n=this.pieces.length;t<n;++t)if(this.bitfield.get(t))e+=t===n-1?this.lastPieceLength:this.pieceLength;else{var r=this.pieces[t];e+=r.length-r.missing}return e}}),Object.defineProperty(o.prototype,"downloadSpeed",{get:function(){return this._downloadSpeed()}}),Object.defineProperty(o.prototype,"uploadSpeed",{get:function(){return this._uploadSpeed()}}),Object.defineProperty(o.prototype,"progress",{get:function(){return this.length?this.downloaded/this.length:0}}),Object.defineProperty(o.prototype,"ratio",{get:function(){return this.uploaded/(this.received||1)}}),Object.defineProperty(o.prototype,"numPeers",{get:function(){return this.wires.length}}),Object.defineProperty(o.prototype,"torrentFileBlobURL",{get:function(){if("undefined"==typeof window)throw new Error("browser-only property");return this.torrentFile?URL.createObjectURL(new Blob([this.torrentFile],{type:"application/x-bittorrent"})):null}}),Object.defineProperty(o.prototype,"_numQueued",{get:function(){return this._queue.length+(this._peersLength-this._numConns)}}),Object.defineProperty(o.prototype,"_numConns",{get:function(){var e=this,t=0;for(var n in e._peers)e._peers[n].connected&&(t+=1);return t}}),Object.defineProperty(o.prototype,"swarm",{get:function(){return console.warn("WebTorrent: `torrent.swarm` is deprecated. Use `torrent` directly instead."),this}}),o.prototype._onTorrentId=function(e){var t=this;if(!t.destroyed){var r;try{r=A(e)}catch(e){}r?(t.infoHash=r.infoHash,t._debugId=r.infoHash.toString("hex").substring(0,7),n.nextTick(function(){t.destroyed||t._onParsedTorrent(r)})):A.remote(e,function(e,n){if(!t.destroyed)return e?t._destroy(e):void t._onParsedTorrent(n)})}},o.prototype._onParsedTorrent=function(e){var t=this;if(!t.destroyed){if(t._processParsedTorrent(e),!t.infoHash)return t._destroy(new Error("Malformed torrent data: No info hash"));t.path||(t.path=B.join(c,t.infoHash)),t._rechokeIntervalId=setInterval(function(){t._rechoke()},1e4),t._rechokeIntervalId.unref&&t._rechokeIntervalId.unref(),t.emit("_infoHash",t.infoHash),t.destroyed||(t.emit("infoHash",t.infoHash),t.destroyed||(t.client.listening?t._onListening():t.client.once("listening",function(){t._onListening()})))}},o.prototype._processParsedTorrent=function(e){this._debugId=e.infoHash.toString("hex").substring(0,7),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&r.WEBTORRENT_ANNOUNCE&&!this.private&&(e.announce=e.announce.concat(r.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),O(e.announce),O(e.urlList),y(this,e),this.magnetURI=A.toMagnetURI(e),this.torrentFile=A.toTorrentFile(e)},o.prototype._onListening=function(){function e(e){i._destroy(e)}function t(e){"string"==typeof e&&i.done||i.addPeer(e)}function n(){i.emit("trackerAnnounce"),0===i.numPeers&&i.emit("noPeers","tracker")}function r(){i.emit("dhtAnnounce"),0===i.numPeers&&i.emit("noPeers","dht")}function o(e){i.emit("warning",e)}var i=this;if(!i.discovery&&!i.destroyed){var s=i.client.tracker;s&&(s=g(i.client.tracker,{getAnnounceOpts:function(){var e={uploaded:i.uploaded,downloaded:i.downloaded,left:Math.max(i.length-i.downloaded,0)};return i.client.tracker.getAnnounceOpts&&y(e,i.client.tracker.getAnnounceOpts()),i._getAnnounceOpts&&y(e,i._getAnnounceOpts()),e}})),i.discovery=new p({infoHash:i.infoHash,announce:i.announce,peerId:i.client.peerId,dht:!i.private&&i.client.dht,tracker:s,port:i.client.torrentPort,userAgent:G}),i.discovery.on("error",e),i.discovery.on("peer",t),i.discovery.on("trackerAnnounce",n),i.discovery.on("dhtAnnounce",r),i.discovery.on("warning",o),i.info?i._onMetadata(i):i.xs&&i._getMetadataFromServer()}},o.prototype._getMetadataFromServer=function(){function e(e,n){function r(r,o,i){if(t.destroyed)return n(null);if(t.metadata)return n(null);if(r)return t.emit("warning",new Error("http error from xs param: "+e)),n(null);if(200!==o.statusCode)return t.emit("warning",new Error("non-200 status code "+o.statusCode+" from xs param: "+e)),n(null);var s;try{s=A(i)}catch(r){}return s?s.infoHash!==t.infoHash?(t.emit("warning",new Error("got torrent file with incorrect info hash from xs param: "+e)),n(null)):(t._onMetadata(s),void n(null)):(t.emit("warning",new Error("got invalid torrent file from xs param: "+e)),n(null))}if(0!==e.indexOf("http://")&&0!==e.indexOf("https://"))return t.emit("warning",new Error("skipping non-http xs param: "+e)),n(null);var o,i={url:e,method:"GET",headers:{"user-agent":G}};try{o=b.concat(i,r)}catch(r){return t.emit("warning",new Error("skipping invalid url xs param: "+e)),n(null)}t._xsRequests.push(o)}var t=this,n=Array.isArray(t.xs)?t.xs:[t.xs],r=n.map(function(t){return function(n){e(t,n)}});I(r)},o.prototype._onMetadata=function(e){var t=this;if(!t.metadata&&!t.destroyed){t._debug("got metadata"),t._xsRequests.forEach(function(e){e.abort()}),t._xsRequests=[];var n;if(e&&e.infoHash)n=e;else try{n=A(e)}catch(e){return t._destroy(e)}t._processParsedTorrent(n),t.metadata=t.torrentFile,t.client.enableWebSeeds&&t.urlList.forEach(function(e){t.addWebSeed(e)}),0!==t.pieces.length&&t.select(0,t.pieces.length-1,!1),t._rarityMap=new N(t),t.store=new w(new t._store(t.pieceLength,{torrent:{infoHash:t.infoHash},files:t.files.map(function(e){return{path:B.join(t.path,e.path),length:e.length,offset:e.offset}}),length:t.length})),t.files=t.files.map(function(e){return new H(t,e)}),t._hashes=t.pieces,t.pieces=t.pieces.map(function(e,n){var r=n===t.pieces.length-1?t.lastPieceLength:t.pieceLength;return new C(r)}),t._reservations=t.pieces.map(function(){return[]}),t.bitfield=new d(t.pieces.length),t.wires.forEach(function(e){e.ut_metadata&&e.ut_metadata.setMetadata(t.metadata),t._onWireWithMetadata(e)}),t._debug("verifying existing torrent data"),t._fileModtimes&&t._store===_?t.getFileModtimes(function(e,n){if(e)return t._destroy(e);if(t.files.map(function(e,r){return n[r]===t._fileModtimes[r]}).every(function(e){return e})){for(var r=0;r<t.pieces.length;r++)t._markVerified(r);t._onStore()}else t._verifyPieces()}):t._verifyPieces(),t.emit("metadata")}},o.prototype.getFileModtimes=function(e){var t=this,n=[];T(t.files.map(function(e,r){return function(o){v.stat(B.join(t.path,e.path),function(e,t){if(e&&"ENOENT"!==e.code)return o(e);n[r]=t&&t.mtime.getTime(),o(null)})}}),2,function(r){t._debug("done getting file modtimes"),e(r,n)})},o.prototype._verifyPieces=function(){var e=this;T(e.pieces.map(function(t,r){return function(t){if(e.destroyed)return t(new Error("torrent is destroyed"));e.store.get(r,function(o,i){return e.destroyed?t(new Error("torrent is destroyed")):o?n.nextTick(t,null):void R(i,function(n){if(e.destroyed)return t(new Error("torrent is destroyed"));if(n===e._hashes[r]){if(!e.pieces[r])return;e._debug("piece verified %s",r),e._markVerified(r)}else e._debug("piece invalid %s",r);t(null)})})}}),2,function(t){if(t)return e._destroy(t);e._debug("done verifying"),e._onStore()})},o.prototype._markVerified=function(e){this.pieces[e]=null,this._reservations[e]=null,this.bitfield.set(e,!0)},o.prototype._onStore=function(){var e=this;e.destroyed||(e._debug("on store"),e.ready=!0,e.emit("ready"),e._checkDone(),e._updateSelections())},o.prototype.destroy=function(e){this._destroy(null,e)},o.prototype._destroy=function(e,t){var n=this;if(!n.destroyed){n.destroyed=!0,n._debug("destroy"),n.client._remove(n),clearInterval(n._rechokeIntervalId),n._xsRequests.forEach(function(e){e.abort()}),n._rarityMap&&n._rarityMap.destroy();for(var r in n._peers)n.removePeer(r);n.files.forEach(function(e){e instanceof H&&e._destroy()});var o=n._servers.map(function(e){return function(t){e.destroy(t)}});n.discovery&&o.push(function(e){n.discovery.destroy(e)}),n.store&&o.push(function(e){n.store.close(e)}),I(o,t),e&&(0===n.listenerCount("error")?n.client.emit("error",e):n.emit("error",e)),n.emit("close"),n.client=null,n.files=[],n.discovery=null,n.store=null,n._rarityMap=null,n._peers=null,n._servers=null,n._xsRequests=null}},o.prototype.addPeer=function(e){var t=this;if(t.destroyed)throw new Error("torrent is destroyed");if(!t.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(t.client.blocked){var n;if("string"==typeof e){var r;try{r=f(e)}catch(n){return t._debug("ignoring peer: invalid %s",e),t.emit(