From 5142f076353011c0b99f6f022a21038b64bb6ef2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20Rodr=C3=ADguez=20B?= Date: Mon, 30 Nov 2015 22:11:37 -0500 Subject: [PATCH 01/44] =?UTF-8?q?Added=20=CE=B2Torrent=20to=20production?= =?UTF-8?q?=20list?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f0af8068ab..6b2f525aa3 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ npm install webtorrent -g - **[Webtorrentapp](https://github.com/alexeisavca/webtorrentapp)** – A tool/platform for launching web apps from torrents - **[People-driven web](http://www.peopledrivenweb.com/)** – Decentralized content management system ([source code](https://github.com/peopledrivenweb/pwjs)) - **[PeerCloud](https://github.com/jhiesey/peercloud)** - Serverless websites via WebTorrent +- **[βTorrent](https://btorrent.xyz)** - Fully-featured WebTorrent browser client ([source code](https://github.com/DiegoRBaquero/bTorrent)) - Your app here! (send a PR or open an issue with your app's URL) ### Usage From 06937116680d61028d1ca6d18a11939872b20af3 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 30 Nov 2015 22:45:28 -0800 Subject: [PATCH 02/44] add new collaborators --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 6b2f525aa3..a277900c70 100644 --- a/README.md +++ b/README.md @@ -695,6 +695,12 @@ WebTorrent is only possible due to the excellent work of the following contribut Iván TodorovichGitHub/ivantodorovichTwitter/@ivantodorovich Mathias BuusGitHub/mafintoshTwitter/@mafintosh Bob RenGitHub/bobrenjc93Twitter/@bobrenjc93 +James HallidayGitHub/substackTwitter/@substack +Gilles De MeyGitHub/gillesdemeyTwitter/@gdemey +Valérian GalliatGitHub/valeriangalliatTwitter/@valeriangalliat +Joseph FrazierGitHub/josephfrazier +Lucas PelegrinoGitHub/lucaswxpTwitter/@lucaswxp +Diego Rodríguez B.GitHub/DiegoRBaqueroTwitter/@DiegoRBaquero #### Clone the code From 2c3f59d7052dd30ea84df8a627ec6b6447041f46 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 00:24:26 -0800 Subject: [PATCH 03/44] executable@2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index bb371fba49..77566d7ca7 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "cross-spawn-async": "^2.0.0", "debug": "^2.1.0", "end-of-stream": "^1.0.0", - "executable": "^1.1.0", + "executable": "^2.1.0", "fs-chunk-store": "^1.3.4", "hat": "0.0.3", "immediate-chunk-store": "^1.0.7", From 388dd3f6b9188b7f227c41c333655621948ec616 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 00:31:55 -0800 Subject: [PATCH 04/44] bittorrent-dht@4 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 77566d7ca7..4bffb001e3 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "dependencies": { "addr-to-ip-port": "^1.0.1", "bitfield": "^1.0.2", - "bittorrent-dht": "^3.0.0", + "bittorrent-dht": "^4.0.4", "bittorrent-swarm": "^5.0.0", "chunk-store-stream": "^2.0.0", "clivas": "^0.2.0", From e0db3e813a4534367e9a91bfc2cadc918832da94 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 01:05:41 -0800 Subject: [PATCH 05/44] fix test for create-torrent change --- test/basic-node.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/basic-node.js b/test/basic-node.js index cc093ecae2..70e96163ce 100644 --- a/test/basic-node.js +++ b/test/basic-node.js @@ -124,7 +124,7 @@ test('client.seed: filesystem path to folder with multiple files, string', funct client.seed(numbersPath, opts, function (torrent) { t.equal(torrent.infoHash, '80562f38656b385ea78959010e51a2cc9db41ea0') - t.equal(torrent.magnetURI, 'magnet:?xt=urn:btih:80562f38656b385ea78959010e51a2cc9db41ea0&dn=numbers&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.webtorrent.io%3A80&tr=wss%3A%2F%2Ftracker.webtorrent.io') + t.equal(torrent.magnetURI, 'magnet:?xt=urn:btih:80562f38656b385ea78959010e51a2cc9db41ea0&dn=numbers&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.internetwarriors.net%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=wss%3A%2F%2Ftracker.webtorrent.io') client.destroy() }) }) From 08ae55cb702ae1c397e295297a8dd2505e6cdb1f Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 01:08:56 -0800 Subject: [PATCH 06/44] remove npm cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It’s causing the tests to fail because there’s an old version of create-torrent being used. --- .travis.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 185b24bc44..677df6fa6a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,6 +7,3 @@ env: global: - secure: AJsEWFnWC5W8hcF3hJzm3PT7heazJpKg85xiSvIWVzLHZU/s0h4+WfJ6t0F9v3L4awaowm62vy8CRaxRkB4lJyJg+JK2K0QN7lNFGj2f8Jx2cFlVJ1IyY959GY4iUg66JrNj1yzS02+yQfweDngyifqzb7IlxnowiveDjUO2gyo= - secure: hvihwLUqlPchrGFXKWFF7iKRugISU7r/gLBo6O63nPeg0OwnYqYcC2BnBWoSiOdu9oR5bM4a5u0os04XL+bP3dqt324g0uBTqvyyxD6NhBsphVFkUmdUH3HMe7IQY6JTns96KT/6UkQapKhIuW4CUDeidR+5NFKvyRdKIjSawS4= -cache: - directories: - - node_modules From 149a2f0556075bea224c1b5c93a86b163b16b518 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 01:10:15 -0800 Subject: [PATCH 07/44] travis: test node 5 --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 185b24bc44..607be5b904 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,7 @@ language: node_js node_js: - - '4.2' + - 'node' + - '4' - '0.12' sudo: false env: From 9328dc9186bf51729db64d204367b667e8e3f83d Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 02:08:41 -0800 Subject: [PATCH 08/44] 0.63.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4bffb001e3..2f9f2272e5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "webtorrent", "description": "Streaming torrent client", - "version": "0.62.3", + "version": "0.63.0", "author": { "name": "Feross Aboukhadijeh", "email": "feross@feross.org", From cfca533063b6ffcf6fd231949762314c8bd73d5e Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 02:10:01 -0800 Subject: [PATCH 09/44] build --- webtorrent.min.js | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/webtorrent.min.js b/webtorrent.min.js index 1eca01ae31..d8d0127945 100644 --- a/webtorrent.min.js +++ b/webtorrent.min.js @@ -1,12 +1,10 @@ -(function(e){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=e()}else if(typeof define==="function"&&define.amd){define([],e)}else{var t;if(typeof window!=="undefined"){t=window}else if(typeof global!=="undefined"){t=global}else if(typeof self!=="undefined"){t=self}else{t=this}t.WebTorrent=e()}})(function(){var e,t,r;return function n(e,t,r){function i(s,o){if(!t[s]){if(!e[s]){var f=typeof require=="function"&&require;if(!o&&f)return f(s,!0);if(a)return a(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var l=t[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r?r:t)},l,l.exports,n,e,t,r)}return t[s].exports}var a=typeof require=="function"&&require;for(var s=0;s=0)_();else if(c.indexOf(g)>=0)w();else if(p.indexOf(g)>=0)x();else if(d.indexOf(g)>=0)k();else v(r,new Error('Unsupported file type "'+g+'": Cannot append to DOM'));function _(){if(!h){return v(r,new Error("Video/audio streaming is not supported in your browser. You can still share "+"or download "+e.name+" (once it's fully downloaded). Use Chrome for "+"MediaSource support."))}var a=f.indexOf(g)>=0?"video":"audio";if(o.indexOf(g)>=0)l();else c();function l(){i("Use `videostream` package for "+e.name);_();u.addEventListener("error",d);u.addEventListener("playing",b);s(e,u)}function c(){i("Use MediaSource API for "+e.name);_();u.addEventListener("error",m);u.addEventListener("playing",b);e.createReadStream().pipe(new n(u,{extname:g}));if(y)u.currentTime=y}function p(){i("Use Blob URL for "+e.name);_();u.addEventListener("error",S);u.addEventListener("playing",b);e.getBlobURL(function(e,t){if(e)return S(e);u.src=t;if(y)u.currentTime=y})}function d(e){i("videostream error: fallback to MediaSource API: %o",e.message||e);u.removeEventListener("error",d);u.removeEventListener("playing",b);c()}function m(e){i("MediaSource API error: fallback to Blob URL: %o",e.message||e);u.removeEventListener("error",m);u.removeEventListener("playing",b);p()}function _(e){if(!u){u=document.createElement(a);u.controls=true;u.autoplay=true;u.play();u.addEventListener("progress",function(){y=u.currentTime});t.appendChild(u)}}}function b(){u.removeEventListener("playing",b);r(null,u)}function w(){u=document.createElement("audio");u.controls=true;u.autoplay=true;t.appendChild(u);e.getBlobURL(function(e,t){if(e)return S(e);u.addEventListener("error",S);u.addEventListener("playing",b);u.src=t;u.play()})}function x(){e.getBlobURL(function(i,n){if(i)return S(i);u=document.createElement("img");u.src=n;u.alt=e.name;t.appendChild(u);r(null,u)})}function k(){e.getBlobURL(function(e,i){if(e)return S(e);u=document.createElement("iframe");u.src=i;if(g!==".pdf")u.sandbox="allow-forms allow-scripts";t.appendChild(u);r(null,u)})}function S(t){if(u)u.remove();t.message='Error appending file "'+e.name+'" to DOM: '+t.message;i(t.message);if(r)r(t)}};function m(){}function v(e,t,i){r.nextTick(function(){if(e)e(t,i)})}}).call(this,e("_process"))},{_process:49,debug:121,mediasource:130,path:48,videostream:180}],2:[function(e,t,r){t.exports=s;var i=e("debug")("webtorrent:file-stream");var n=e("inherits");var a=e("stream");n(s,a.Readable);function s(e,t){a.Readable.call(this,t);this.destroyed=false;this._torrent=e._torrent;var r=t&&t.start||0;var i=t&&t.end||e.length-1;var n=e._torrent.pieceLength;this._startPiece=(r+e.offset)/n|0;this._endPiece=(i+e.offset)/n|0;this._piece=this._startPiece;this._offset=r+e.offset-this._startPiece*n;this._missing=i-r+1;this._reading=false;this._notifying=false;this._criticalLength=Math.min(1024*1024/n|0,2)}s.prototype._read=function(){if(this._reading)return;this._reading=true;this._notify()};s.prototype._notify=function(){var e=this;if(!e._reading||e._missing===0)return;if(!e._torrent.bitfield.get(e._piece)){return e._torrent.critical(e._piece,e._piece+e._criticalLength)}if(e._notifying)return;e._notifying=true;var t=e._piece;e._torrent.store.get(t,function(r,n){e._notifying=false;if(e.destroyed)return;if(r)return e.destroy(r);i("read %s (length %s) (err %s)",t,n.length,r&&r.message);if(e._offset){n=n.slice(e._offset);e._offset=0}if(e._missing0){return r[Math.random()*r.length|0]}else{return-1}}},{}],6:[function(e,t,r){t.exports=u;var i=e("debug")("webtorrent:server");var n=e("http");var a=e("mime");var s=e("pump");var o=e("range-parser");var f=e("url");function u(e,t){var r=n.createServer(t);var u=[];r.on("connection",function(e){e.setTimeout(36e6);u.push(e);e.on("close",function(){var t=u.indexOf(e);if(t>=0)u.splice(t,1)})});r.destroy=function(e){u.forEach(function(e){e.destroy()});r.close(e)};r.on("request",function(t,r){i("onRequest");if(t.method==="OPTIONS"&&t.headers["access-control-request-headers"]){r.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS");r.setHeader("Access-Control-Allow-Headers",t.headers["access-control-request-headers"]);r.setHeader("Access-Control-Max-Age","1728000");return r.end()}if(t.headers.origin){r.setHeader("Access-Control-Allow-Origin",t.headers.origin)}var n=f.parse(t.url).pathname;if(n==="/favicon.ico")return r.end();if(e.ready)u();else e.once("ready",u);function u(){if(n==="/"){r.setHeader("Content-Type","text/html");var f=e.files.map(function(e,t){return'
  • '+e.name+"
  • "}).join("
    ");return r.end("

    WebTorrent

      "+f+"
    ")}var u=Number(n.slice(1));if(Number.isNaN(u)||u>=e.files.length){r.statusCode=404;return r.end("404 Not Found")}var l=e.files[u];r.setHeader("Accept-Ranges","bytes");r.setHeader("Content-Type",a.lookup(l.name));r.statusCode=200;r.setHeader("transferMode.dlna.org","Streaming");r.setHeader("contentFeatures.dlna.org","DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000");var c;if(t.headers.range){r.statusCode=206;c=o(l.length,t.headers.range)[0];i("range %s",JSON.stringify(c));r.setHeader("Content-Range","bytes "+c.start+"-"+c.end+"/"+l.length);r.setHeader("Content-Length",c.end-c.start+1)}else{r.setHeader("Content-Length",l.length)}if(t.method==="HEAD")r.end();s(l.createReadStream(c),r)}});return r}},{debug:121,http:68,mime:132,pump:149,"range-parser":153,url:78}],7:[function(e,t,r){(function(r,i){t.exports=H;var n=e("addr-to-ip-port");var a=e("bitfield");var s=e("chunk-store-stream/write");var o=e("create-torrent");var f=e("debug")("webtorrent:torrent");var u=e("torrent-discovery");var l=e("events").EventEmitter;var c=e("xtend/mutable");var p=e("fs-chunk-store");var d=e("immediate-chunk-store");var h=e("inherits");var m=e("multistream");var v=e("os");var g=e("run-parallel");var y=e("parse-torrent");var _=e("path");var b=e("path-exists");var w=e("torrent-piece");var x=e("pump");var k=e("random-iterate");var S=e("re-emitter");var E=e("simple-sha1");var A=e("bittorrent-swarm");var U=e("uniq");var T=e("ut_metadata");var I=e("ut_pex");var L=e("./file");var B=e("./rarity-map");var C=e("./server");var R=128*1024;var P=3e4;var z=5e3;var O=3*w.BLOCK_LENGTH;var F=.5;var M=1;var j=1e4;var D=2;var N=_.join(b.sync("/tmp")?"/tmp":v.tmpDir(),"webtorrent");h(H,l);function H(e,t){var r=this;l.call(r);if(!f.enabled)r.setMaxListeners(0);f("new torrent");r.client=t.client;r.announce=t.announce;r.urlList=t.urlList;r.path=t.path;r._store=t.store||p;r.strategy=t.strategy||"sequential";r._rechokeNumSlots=t.uploads===false||t.uploads===0?0:+t.uploads||10;r._rechokeOptimisticWire=null;r._rechokeOptimisticTime=0;r._rechokeIntervalId=null;r.ready=false;r.destroyed=false;r.metadata=null;r.store=null;r.numBlockedPeers=0;r.files=null;r.done=false;r._amInterested=false;r._selections=[];r._critical=[];r._servers=[];if(e)r._onTorrentId(e)}Object.defineProperty(H.prototype,"timeRemaining",{get:function(){if(this.swarm.downloadSpeed()===0)return Infinity;else return(this.length-this.downloaded)/this.swarm.downloadSpeed()*1e3}});Object.defineProperty(H.prototype,"downloaded",{get:function(){var e=0;for(var t=0,r=this.pieces.length;tt||e<0||t>=n.pieces.length){throw new Error("invalid selection ",e,":",t)}r=Number(r)||0;f("select %s-%s (priority %s)",e,t,r);n._selections.push({from:e,to:t,offset:0,priority:r,notify:i||W});n._selections.sort(function(e,t){return t.priority-e.priority});n._updateSelections()};H.prototype.deselect=function(e,t,r){var i=this;r=Number(r)||0;f("deselect %s-%s (priority %s)",e,t,r);for(var n=0;n2*(t.swarm.numConns-t.swarm.numPeers)&&e.amInterested){e.destroy()}else{r=setTimeout(i,z);if(r.unref)r.unref()}}var n=0;function a(){if(e.peerPieces.length!==t.pieces.length)return;for(;nR){return e.destroy()}if(t.pieces[r])return;t.store.get(r,{offset:i,length:n},a)});e.bitfield(t.bitfield);e.interested();r=setTimeout(i,z);if(r.unref)r.unref();e.isSeeder=false;a()};H.prototype._updateSelections=function(){var e=this;if(!e.swarm||e.destroyed)return;if(!e.metadata)return e.once("metadata",e._updateSelections.bind(e));r.nextTick(e._gcSelections.bind(e));e._updateInterest();e._update()};H.prototype._gcSelections=function(){var e=this;for(var t=0;t=r)return;var i=q(e,M);f(false)||f(true);function n(t,r,i,n){return function(a){return a>=t&&a<=r&&!(a in i)&&e.peerPieces.get(a)&&(!n||n(a))}}function a(){if(e.requests.length)return;var r=t._selections.length;while(r--){var i=t._selections[r];var a;if(t.strategy==="rarest"){var s=i.from+i.offset;var o=i.to;var f=o-s+1;var u={};var l=0;var c=n(s,o,u);while(l=i.from+i.offset;--a){if(!e.peerPieces.get(a))continue;if(t._request(e,a,false))return}}}}function s(){var r=e.downloadSpeed()||1;if(r>O)return function(){return true};var i=Math.max(1,e.requests.length)*w.BLOCK_LENGTH/r;var n=10;var a=0;return function(e){if(!n||t.bitfield.get(e))return true;var s=t.pieces[e].missing;for(;a0)continue;n--;return false}return true}}function o(e){var r=e;for(var i=e;i=i)return true;var a=s();for(var f=0;f0)e._rechokeOptimisticTime-=1;else e._rechokeOptimisticWire=null;var t=[];e.swarm.wires.forEach(function(r){if(!r.isSeeder&&r!==e._rechokeOptimisticWire){t.push({wire:r,downloadSpeed:r.downloadSpeed(),uploadSpeed:r.uploadSpeed(),salt:Math.random(),isChoked:true})}});t.sort(s);var r=0;var i=0;for(;i=O)continue;if(2*u>i||u>a)continue;s=f;a=u}if(!s)return false;for(o=0;o=s)return false;var o=n.pieces[t];var u=o.reserve();if(u===-1&&i&&n._hotswap(e,t)){u=o.reserve()}if(u===-1)return false;var l=n._reservations[t];if(!l)l=n._reservations[t]=[];var c=l.indexOf(null);if(c===-1)c=l.length;l[c]=e;var p=o.chunkOffset(u);var d=o.chunkLength(u);e.request(t,p,d,function m(r,i){if(!n.ready)return n.once("ready",function(){m(r,i)});if(l[c]===e)l[c]=null;if(o!==n.pieces[t])return h();if(r){f("error getting piece %s (offset: %s length: %s) from %s: %s",t,p,d,e.remoteAddress+":"+e.remotePort,r.message);o.cancel(u);h();return}f("got piece %s (offset: %s length: %s) from %s",t,p,d,e.remoteAddress+":"+e.remotePort);if(!o.set(u,i,e))return h();var a=o.flush();E(a,function(e){if(e===n._hashes[t]){if(!n.pieces[t])return;f("piece verified %s",t);n.pieces[t]=null;n._reservations[t]=null;n.bitfield.set(t,true);n.store.put(t,a);n.swarm.wires.forEach(function(e){e.have(t)});n._checkDone()}else{n.pieces[t]=new w(o.length);n.emit("warning",new Error("Piece "+t+" failed verification"))}h()})});function h(){r.nextTick(function(){n._update()})}return true};H.prototype._checkDone=function(){var e=this;if(e.destroyed)return;e.files.forEach(function(t){if(t.done)return;for(var r=t._startPiece;r<=t._endPiece;++r){if(!e.bitfield.get(r))return}t.done=true;t.emit("done");f("file done: "+t.name)});if(e.files.every(function(e){return e.done})){e.done=true;e.emit("done");f("torrent done: "+e.infoHash);if(e.discovery.tracker)e.discovery.tracker.complete()}e._gcSelections()};H.prototype.load=function(e,t){var r=this;if(!Array.isArray(e))e=[e];if(!t)t=W;var i=new m(e);var n=new s(r.store,r.pieceLength);x(i,n,function(e){if(e)return t(e);r.pieces.forEach(function(e,t){r.pieces[t]=null;r._reservations[t]=null;r.bitfield.set(t,true)});r._checkDone();t(null)})};H.prototype.createServer=function(e){var t=this;if(typeof C!=="function")return;var r=new C(t,e);t._servers.push(r);return r};H.prototype._onError=function(e){var t=this;f("torrent error: %s",e.message||e);t.emit("error",e);t.destroy()};function q(e,t){return Math.ceil(2+t*e.downloadSpeed()/w.BLOCK_LENGTH)}function G(e){return Math.random()*e|0}function W(){}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./file":3,"./rarity-map":5,"./server":6,_process:49,"addr-to-ip-port":8,bitfield:9,"bittorrent-swarm":10,"chunk-store-stream/write":90,"create-torrent":91,debug:121,events:43,"fs-chunk-store":131,"immediate-chunk-store":128,inherits:129,multistream:134,os:47,"parse-torrent":135,path:48,"path-exists":148,pump:149,"random-iterate":152,"re-emitter":154,"run-parallel":155,"simple-sha1":163,"torrent-discovery":166,"torrent-piece":167,uniq:168,ut_metadata:169,ut_pex:38,"xtend/mutable":182}],8:[function(e,t,r){var i=/^\[?([^\]]+)\]?:(\d+)$/;var n={};var a=0;t.exports=function s(e){if(a===1e5)t.exports.reset();if(!n[e]){var r=i.exec(e);if(!r)throw new Error("invalid addr: "+e);n[e]=[r[1],Number(r[2])];a+=1}return n[e]};t.exports.reset=function o(){n={};a=0}},{}],9:[function(e,t,r){(function(e){var r=typeof e!=="undefined"?e:typeof Int8Array!=="undefined"?Int8Array:function(e){var t=new Array(e);for(var r=0;r>3;if(e%8!==0)t++;return t}i.prototype.get=function(e){var t=e>>3;return t>e%8)};i.prototype.set=function(e,t){var r=e>>3;if(t||arguments.length===1){if(this.buffer.length>e%8}else if(r>e%8)}};i.prototype._grow=function(e){if(this.buffer.length=e.maxConns){return}a("drain (%s queued, %s/%s peers)",e.numQueued,e.numPeers,e.maxConns);var t=e._queue.shift();if(!t)return;a("tcp connect attempt to %s",t.addr);var r=n(t.addr);var i={host:r[0],port:r[1]};if(e._hostname)i.localAddress=e._hostname;var s=t.conn=u.connect(i);s.once("connect",function(){t.onConnect()});s.once("error",function(e){t.destroy(e)});t.setConnectTimeout();s.on("close",function(){if(e.destroyed)return;if(t.retries>=h.length){a("conn %s closed: will not re-add (max %s attempts)",t.addr,h.length);return}var r=h[t.retries];a("conn %s closed: will re-add to queue in %sms (attempt %s)",t.addr,r,t.retries+1);var i=setTimeout(function n(){var r=e._addPeer(t.addr);if(r)r.retries=t.retries+1},r);if(i.unref)i.unref()})};m.prototype._onError=function(e){var t=this;t.emit("error",e);t.destroy()};m.prototype._validAddr=function(e){var t=this;var r=n(e);var i=r[0];var a=r[1];return a>0&&a<65535&&!(i==="127.0.0.1"&&a===t._port)}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/peer":11,"./lib/tcp-pool":12,_process:49,"addr-to-ip-port":38,buffer:39,debug:121,dezalgo:19,events:43,inherits:129,net:38,speedometer:165}],11:[function(e,t,r){var i=e("debug")("bittorrent-swarm:peer");var n=e("./webconn");var a=e("bittorrent-protocol");var s=25e3;var o=25e3;r.createWebRTCPeer=function(e,t){var r=new f(e.id);r.conn=e;r.swarm=t;if(r.conn.connected){r.onConnect()}else{r.conn.once("connect",function(){r.onConnect()});r.conn.once("error",function(e){r.destroy(e)});r.setConnectTimeout()}return r};r.createIncomingTCPPeer=function(e){var t=e.remoteAddress+":"+e.remotePort;var r=new f(t);r.conn=e;r.addr=t;r.onConnect();return r};r.createOutgoingTCPPeer=function(e,t){var r=new f(e);r.addr=e;r.swarm=t;return r};r.createWebPeer=function(e,t,r){var i=new f(e);i.swarm=r;i.conn=new n(e,t);i.onConnect();return i};function f(e){var t=this;t.id=e;i("new Peer %s",e);t.addr=null;t.conn=null;t.swarm=null;t.wire=null;t.connected=false;t.destroyed=false;t.timeout=null;t.retries=0;t.sentHandshake=false}f.prototype.onConnect=function(){var e=this;if(e.destroyed)return;e.connected=true;i("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 r=e.wire=new a;r.once("end",function(){e.destroy()});r.once("close",function(){e.destroy()});r.once("finish",function(){e.destroy()});r.once("error",function(t){e.destroy(t)});r.once("handshake",function(t,r){e.onHandshake(t,r)});e.setHandshakeTimeout();t.pipe(r).pipe(t);if(e.swarm&&!e.sentHandshake)e.handshake()};f.prototype.onHandshake=function(e,t){var r=this;if(!r.swarm)return;var n=e.toString("hex");var a=t.toString("hex");if(r.swarm.destroyed)return r.destroy(new Error("swarm already destroyed"));if(n!==r.swarm.infoHashHex){return r.destroy(new Error("unexpected handshake info hash for this swarm"))}if(a===r.swarm.peerIdHex){return r.destroy(new Error("refusing to handshake with self"))}i("Peer %s got handshake %s",r.id,n);clearTimeout(r.handshakeTimeout);r.retries=0;r.wire.on("download",function(e){if(r.destroyed)return;r.swarm.downloaded+=e;r.swarm.downloadSpeed(e);r.swarm.emit("download",e)});r.wire.on("upload",function(e){if(r.destroyed)return;r.swarm.uploaded+=e;r.swarm.uploadSpeed(e);r.swarm.emit("upload",e)});if(!r.sentHandshake)r.handshake();r.swarm.wires.push(r.wire);var s=r.addr;if(!s&&r.conn.remoteAddress){s=r.conn.remoteAddress+":"+r.conn.remotePort}r.swarm.emit("wire",r.wire,s)};f.prototype.handshake=function(){var e=this;e.wire.handshake(e.swarm.infoHash,e.swarm.peerId,e.swarm.handshakeOpts);e.sentHandshake=true};f.prototype.setConnectTimeout=function(){var e=this;clearTimeout(e.connectTimeout);e.connectTimeout=setTimeout(function(){e.destroy(new Error("connect timeout"))},s);if(e.connectTimeout.unref)e.connectTimeout.unref()};f.prototype.setHandshakeTimeout=function(){var e=this;clearTimeout(e.handshakeTimeout);e.handshakeTimeout=setTimeout(function(){e.destroy(new Error("handshake timeout"))},o);if(e.handshakeTimeout.unref)e.handshakeTimeout.unref()};f.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;t.connected=false;i("destroy %s (error: %s)",t.id,e&&(e.message||e));clearTimeout(t.connectTimeout);clearTimeout(t.handshakeTimeout);var r=t.swarm;var n=t.conn;var a=t.wire;t.conn=null;t.swarm=null;t.wire=null;if(r&&a){var s=r.wires.indexOf(a);if(s>=0)r.wires.splice(s,1)}if(n)n.destroy();if(a)a.destroy();if(r)r.removePeer(t.id)}},{"./webconn":13,"bittorrent-protocol":14,debug:121}],12:[function(e,t,r){(function(r){t.exports=f;var i=e("debug")("bittorrent-swarm:tcp-pool");var n=e("dezalgo");var a=e("net");var s=e("./peer");var o={};function f(e,t){var r=this;r.port=e;r.listening=false;r.swarms={};i("new TCPPool (port: %s, hostname: %s)",e,t);r.pendingConns=[];r.server=a.createServer();r.server.on("connection",function(e){r._onConnection(e)});r.server.on("error",function(e){r._onError(e)});r.server.on("listening",function(){r._onListening()});r.server.listen(r.port,t)}f.addSwarm=function(e){var t=o[e._port];if(!t)t=o[e._port]=new f(e._port,e._hostname);t.addSwarm(e);return t};f.removeSwarm=function(e,t){var i=o[e._port];if(!i)return t();i.removeSwarm(e);var n=0;for(var a in i.swarms){var s=i.swarms[a];if(s)n+=1}if(n===0)i.destroy(t);else r.nextTick(t)};f.getDefaultListenPort=function(e){for(var t in o){var r=o[t];if(r&&!r.swarms[e])return r.port}return 0};f.prototype.addSwarm=function(e){var t=this;if(t.swarms[e.infoHashHex]){r.nextTick(function(){e._onError(new Error("There is already a swarm with info hash "+e.infoHashHex+" "+"listening on port "+e._port))});return}t.swarms[e.infoHashHex]=e;if(t.listening){r.nextTick(function(){e._onListening(t.port)})}i("add swarm %s to tcp pool %s",e.infoHashHex,t.port)};f.prototype.removeSwarm=function(e){var t=this;i("remove swarm %s from tcp pool %s",e.infoHashHex,t.port);t.swarms[e.infoHashHex]=null};f.prototype.destroy=function(e){var t=this;if(e)e=n(e);i("destroy tcp pool %s",t.port);t.listening=false;t.pendingConns.forEach(function(e){e.destroy()});o[t.port]=null;try{t.server.close(e)}catch(r){if(e)e(null)}};f.prototype._onListening=function(){var e=this;var t=e.server.address()||{port:0};var r=t.port;i("tcp pool listening on %s",r);if(r!==e.port){o[e.port]=null;e.port=r;o[e.port]=e}e.listening=true;for(var n in e.swarms){var a=e.swarms[n];if(a)a._onListening(e.port)}};f.prototype._onConnection=function(e){var t=this;t.pendingConns.push(e);e.once("close",r);function r(){t.pendingConns.splice(t.pendingConns.indexOf(e))}var i=s.createIncomingTCPPeer(e);i.wire.once("handshake",function(n,a){var s=n.toString("hex");r();e.removeListener("close",r);var o=t.swarms[s];if(o){i.swarm=o;o._addIncomingPeer(i);i.onHandshake(n,a)}else{var f=new Error("Unexpected info hash "+s+" from incoming peer "+i.id+": destroying peer");i.destroy(f)}})};f.prototype._onError=function(e){var t=this;t.destroy();for(var r in t.swarms){var i=t.swarms[r];if(i){t.removeSwarm(i);i._onError(e)}}}}).call(this,e("_process"))},{"./peer":11,_process:49,debug:121,dezalgo:19,net:38}],13:[function(e,t,r){(function(r){t.exports=f;var i=e("bitfield");var n=e("debug")("bittorrent-swarm:webconn");var a=e("simple-get");var s=e("inherits");var o=e("bittorrent-protocol");s(f,o);function f(e,t){var a=this;o.call(this);a.url=e;a.parsedTorrent=t;a.setKeepAlive(true);a.on("handshake",function(t,n){a.handshake(t,new r(20).fill(e));var s=a.parsedTorrent.pieces.length;var o=new i(s);for(var f=0;f<=s;f++){o.set(f,true)}a.bitfield(o)});a.on("choke",function(){n("choke")});a.on("unchoke",function(){n("unchoke")});a.once("interested",function(){n("interested");a.unchoke()});a.on("uninterested",function(){n("uninterested")});a.on("bitfield",function(){n("bitfield")});a.on("request",function(e,t,r,i){n("request pieceIndex=%d offset=%d length=%d",e,t,r);a.httpRequest(e,t,r,i)})}f.prototype.httpRequest=function(e,t,r,i){var s=this;var o=e*s.parsedTorrent.pieceLength;var f=o+t;var u=f+r-1;n("Requesting pieceIndex=%d offset=%d length=%d start=%d end=%d",e,t,r,f,u);var l={url:s.url,method:"GET",headers:{"user-agent":"WebTorrent (http://webtorrent.io)",range:"bytes="+f+"-"+u}};a.concat(l,function(e,t,r){if(e)return i(e);if(r.statusCode<200||r.statusCode>=300){return i(new Error("Unexpected HTTP status code "+r.statusCode))}n("Got data of length %d",t.length);i(null,t)})}}).call(this,e("buffer").Buffer)},{bitfield:9,"bittorrent-protocol":14,buffer:39,debug:121,inherits:129,"simple-get":160}],14:[function(e,t,r){(function(r){t.exports=w;var i=e("bencode");var n=e("bitfield");var a=e("debug")("bittorrent-protocol");var s=e("xtend");var o=e("hat");var f=e("inherits");var u=e("speedometer");var l=e("stream");var c=4e5;var p=new r("BitTorrent protocol");var d=new r([0,0,0,0]);var h=new r([0,0,0,1,0]);var m=new r([0,0,0,1,1]);var v=new r([0,0,0,1,2]);var g=new r([0,0,0,1,3]);var y=[0,0,0,0,0,0,0,0];var _=[0,0,0,3,9,0,0];function b(e,t,r,i){this.piece=e;this.offset=t;this.length=r;this.callback=i}f(w,l.Duplex);function w(){if(!(this instanceof w))return new w;l.Duplex.call(this);this._debugId=o(32);this._debug("new wire");this.amChoking=true;this.amInterested=false;this.peerChoking=true;this.peerInterested=false;this.peerPieces=new n(0,{grow:c});this.peerExtensions={};this.requests=[];this.peerRequests=[];this.extendedMapping={};this.peerExtendedMapping={};this.extendedHandshake={};this.peerExtendedHandshake={};this._ext={};this._nextExt=1;this.uploaded=0;this.downloaded=0;this.uploadSpeed=u();this.downloadSpeed=u();this._keepAliveInterval=null;this._timeout=null;this._timeoutMs=0;this.destroyed=false;this._finished=false;this._buffer=[];this._bufferSize=0;this._parser=null;this._parserSize=0;this.on("finish",this._onfinish);this._parseHandshake()}w.prototype.setKeepAlive=function(e){this._debug("setKeepAlive %s",e);clearInterval(this._keepAliveInterval);if(e===false)return;this._keepAliveInterval=setInterval(this.keepAlive.bind(this),6e4)};w.prototype.setTimeout=function(e,t){this._debug("setTimeout ms=%d unref=%s",e,t);this._clearTimeout();this._timeoutMs=e;this._timeoutUnref=!!t;this._updateTimeout()};w.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=true;this._debug("destroy");this.emit("close");this.end()};w.prototype.end=function(){this._debug("end");this._onUninterested();this._onChoke();l.Duplex.prototype.end.apply(this,arguments)};w.prototype.use=function(e){var t=e.prototype.name;if(!t){throw new Error('Extension class requires a "name" property on the prototype')}this._debug("use extension.name=%s",t);var r=this._nextExt;var i=new e(this);function n(){}if(typeof i.onHandshake!=="function"){i.onHandshake=n}if(typeof i.onExtendedHandshake!=="function"){i.onExtendedHandshake=n}if(typeof i.onMessage!=="function"){i.onMessage=n}this.extendedMapping[r]=t;this._ext[t]=i;this[t]=i;this._nextExt+=1};w.prototype.keepAlive=function(){this._debug("keep-alive");this._push(d)};w.prototype.handshake=function(e,t,i){if(typeof e==="string")e=new r(e,"hex");if(typeof t==="string")t=new r(t,"hex");if(e.length!==20||t.length!==20){throw new Error("infoHash and peerId MUST have length 20")}this._debug("handshake i=%s p=%s exts=%o",e.toString("hex"),t.toString("hex"),i);var n=new r(y);n[5]|=16;if(i&&i.dht)n[7]|=1;this._push(r.concat([p,n,e,t]));this._handshakeSent=true;if(this.peerExtensions.extended){this._sendExtendedHandshake()}};w.prototype._sendExtendedHandshake=function(){var e=s(this.extendedHandshake);e.m={};for(var t in this.extendedMapping){var r=this.extendedMapping[t];e.m[r]=Number(t)}this.extended(0,i.encode(e))};w.prototype.choke=function(){if(this.amChoking)return;this.amChoking=true;this._debug("choke");this.peerRequests.splice(0,this.peerRequests.length);this._push(h)};w.prototype.unchoke=function(){if(!this.amChoking)return;this.amChoking=false;this._debug("unchoke");this._push(m)};w.prototype.interested=function(){if(this.amInterested)return;this.amInterested=true;this._debug("interested");this._push(v)};w.prototype.uninterested=function(){if(!this.amInterested)return;this.amInterested=false;this._debug("uninterested");this._push(g)};w.prototype.have=function(e){this._debug("have %d",e);this._message(4,[e],null)};w.prototype.bitfield=function(e){this._debug("bitfield");if(!r.isBuffer(e))e=e.buffer;this._message(5,[],e)};w.prototype.request=function(e,t,r,i){if(!i)i=function(){};if(this._finished)return i(new Error("wire is closed"));if(this.peerChoking)return i(new Error("peer is choking"));this._debug("request index=%d offset=%d length=%d",e,t,r);this.requests.push(new b(e,t,r,i));this._updateTimeout();this._message(6,[e,t,r],null)};w.prototype.piece=function(e,t,r){this._debug("piece index=%d offset=%d",e,t);this.uploaded+=r.length;this.uploadSpeed(r.length);this.emit("upload",r.length);this._message(7,[e,t],r)};w.prototype.cancel=function(e,t,r){this._debug("cancel index=%d offset=%d length=%d",e,t,r);this._callback(x(this.requests,e,t,r),new Error("request was cancelled"),null);this._message(8,[e,t,r],null)};w.prototype.port=function(e){this._debug("port %d",e);var t=new r(_);t.writeUInt16BE(e,5);this._push(t)};w.prototype.extended=function(e,t){this._debug("extended ext=%s",e);if(typeof e==="string"&&this.peerExtendedMapping[e]){e=this.peerExtendedMapping[e]}if(typeof e==="number"){var n=new r([e]);var a=r.isBuffer(t)?t:i.encode(t);this._message(20,[],r.concat([n,a]))}else{throw new Error("Unrecognized extension: "+e)}};w.prototype._onKeepAlive=function(){this._debug("got keep-alive");this.emit("keep-alive")};w.prototype._onHandshake=function(e,t,r){this._debug("got handshake i=%s p=%s exts=%o",e.toString("hex"),t.toString("hex"),r);this.peerId=t;this.peerExtensions=r;this.emit("handshake",e,t,r);var i;for(i in this._ext){this._ext[i].onHandshake(e,t,r)}if(r.extended&&this._handshakeSent){this._sendExtendedHandshake()}};w.prototype._onChoke=function(){this.peerChoking=true;this._debug("got choke");this.emit("choke");while(this.requests.length){this._callback(this.requests.shift(),new Error("peer is choking"),null)}};w.prototype._onUnchoke=function(){this.peerChoking=false;this._debug("got unchoke");this.emit("unchoke")};w.prototype._onInterested=function(){this.peerInterested=true;this._debug("got interested");this.emit("interested")};w.prototype._onUninterested=function(){this.peerInterested=false;this._debug("got uninterested");this.emit("uninterested")};w.prototype._onHave=function(e){if(this.peerPieces.get(e))return;this._debug("got have %d",e);this.peerPieces.set(e,true);this.emit("have",e)};w.prototype._onBitField=function(e){this.peerPieces=new n(e);this._debug("got bitfield");this.emit("bitfield",this.peerPieces)};w.prototype._onRequest=function(e,t,r){if(this.amChoking)return;this._debug("got request index=%d offset=%d length=%d",e,t,r);var i=function(i,a){if(n!==x(this.peerRequests,e,t,r))return;if(i)return;this.piece(e,t,a)}.bind(this);var n=new b(e,t,r,i);this.peerRequests.push(n);this.emit("request",e,t,r,i)};w.prototype._onPiece=function(e,t,r){this._debug("got piece index=%d offset=%d",e,t);this._callback(x(this.requests,e,t,r.length),null,r);this.downloaded+=r.length;this.downloadSpeed(r.length);this.emit("download",r.length);this.emit("piece",e,t,r)};w.prototype._onCancel=function(e,t,r){this._debug("got cancel index=%d offset=%d length=%d",e,t,r);x(this.peerRequests,e,t,r);this.emit("cancel",e,t,r)};w.prototype._onPort=function(e){this._debug("got port %d",e);this.emit("port",e)};w.prototype._onExtended=function(e,t){if(e===0){var r;try{r=i.decode(t)}catch(n){this._debug("ignoring invalid extended handshake: %s",n.message||n)}if(!r)return;this.peerExtendedHandshake=r;var a;if(typeof r.m==="object"){for(a in r.m){this.peerExtendedMapping[a]=Number(r.m[a].toString())}}for(a in this._ext){if(this.peerExtendedMapping[a]){this._ext[a].onExtendedHandshake(this.peerExtendedHandshake)}}this._debug("got extended handshake");this.emit("extended","handshake",this.peerExtendedHandshake)}else{if(this.extendedMapping[e]){e=this.extendedMapping[e];if(this._ext[e]){this._ext[e].onMessage(t)}}this._debug("got extended message ext=%s",e);this.emit("extended",e,t)}};w.prototype._onTimeout=function(){this._debug("request timed out");this._callback(this.requests.shift(),new Error("request has timed out"),null);this.emit("timeout")};w.prototype._push=function(e){if(this._finished)return;return this.push(e)};w.prototype._write=function(e,t,i){this._bufferSize+=e.length;this._buffer.push(e);while(this._bufferSize>=this._parserSize){var n=this._buffer.length===1?this._buffer[0]:r.concat(this._buffer);this._bufferSize-=this._parserSize;this._buffer=this._bufferSize?[n.slice(this._parserSize)]:[];this._parser(n.slice(0,this._parserSize))}i(null)};w.prototype._read=function(){};w.prototype._callback=function(e,t,r){if(!e)return;this._clearTimeout();if(!this.peerChoking&&!this._finished)this._updateTimeout();e.callback(t,r)};w.prototype._clearTimeout=function(){if(!this._timeout)return;clearTimeout(this._timeout);this._timeout=null};w.prototype._updateTimeout=function(){if(!this._timeoutMs||!this.requests.length||this._timeout)return;this._timeout=setTimeout(this._onTimeout.bind(this),this._timeoutMs);if(this._timeoutUnref&&this._timeout.unref)this._timeout.unref()};w.prototype._parse=function(e,t){this._parserSize=e;this._parser=t};w.prototype._message=function(e,t,i){var n=i?i.length:0;var a=new r(5+4*t.length);a.writeUInt32BE(a.length+n-4,0);a[4]=e;for(var s=0;s0){this._parse(t,this._onmessage)}else{this._onKeepAlive();this._parse(4,this._onmessagelength)}};w.prototype._onmessage=function(e){this._parse(4,this._onmessagelength);switch(e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:this._debug("got unknown message");return this.emit("unknownmessage",e)}};w.prototype._parseHandshake=function(){this._parse(1,function(e){var t=e.readUInt8(0);this._parse(t+48,function(e){var r=e.slice(0,t);if(r.toString()!=="BitTorrent protocol"){this._debug("Error: wire not speaking BitTorrent protocol (%s)",r.toString());this.end();return}e=e.slice(t);this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(e[7]&1),extended:!!(e[5]&16)});this._parse(4,this._onmessagelength)}.bind(this))}.bind(this))};w.prototype._onfinish=function(){this._finished=true;this.push(null);while(this.read()){}clearInterval(this._keepAliveInterval);this._parse(Number.MAX_VALUE,function(){});this.peerRequests=[];while(this.requests.length){this._callback(this.requests.shift(),new Error("wire was closed"),null)}};w.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._debugId+"] "+e[0];a.apply(null,e)};function x(e,t,r,i){for(var n=0;no){for(var t=0,r=i.length-s;ti._maxBufferedAmount){i._debug("start backpressure: bufferedAmount %d",i._channel.bufferedAmount);i._cb=r}else{r(null)}}else{i._debug("write before connect");i._chunk=e;i._cb=r}};c.prototype._createOffer=function(){var e=this;if(e.destroyed)return;e._pc.createOffer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,p,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.offerConstraints)};c.prototype._createAnswer=function(){var e=this;if(e.destroyed)return;e._pc.createAnswer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,p,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.answerConstraints)};c.prototype._onIceConnectionStateChange=function(){var e=this;if(e.destroyed)return;var t=e._pc.iceGatheringState;var r=e._pc.iceConnectionState;e._debug("iceConnectionStateChange %s %s",t,r);e.emit("iceConnectionStateChange",t,r);if(r==="connected"||r==="completed"){clearTimeout(e._reconnectTimeout);e._pcReady=true;e._maybeReady()}if(r==="disconnected"){if(e.reconnectTimer){clearTimeout(e._reconnectTimeout);e._reconnectTimeout=setTimeout(function(){e._destroy()},e.reconnectTimer)}else{e._destroy()}}if(r==="closed"){e._destroy()}};c.prototype._maybeReady=function(){var e=this;e._debug("maybeReady pc %s channel %s",e._pcReady,e._channelReady);if(e.connected||e._connecting||!e._pcReady||!e._channelReady)return;e._connecting=true;if(typeof window!=="undefined"&&!!window.mozRTCPeerConnection){e._pc.getStats(null,function(e){var r=[];e.forEach(function(e){r.push(e)});t(r)},e._onError.bind(e))}else{e._pc.getStats(function(e){var r=[];e.result().forEach(function(e){var t={};e.names().forEach(function(r){t[r]=e.stat(r)});t.id=e.id;t.type=e.type;t.timestamp=e.timestamp;r.push(t)});t(r)})}function t(t){t.forEach(function(t){if(t.type==="remotecandidate"){e.remoteAddress=t.ipAddress;e.remotePort=Number(t.portNumber);e.remoteFamily="IPv4";e._debug("connect remote: %s:%s (%s)",e.remoteAddress,e.remotePort,e.remoteFamily)}else if(t.type==="localcandidate"&&t.candidateType==="host"){e.localAddress=t.ipAddress;e.localPort=Number(t.portNumber);e._debug("connect local: %s:%s",e.localAddress,e.localPort)}});e._connecting=false;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(r){return e._onError(r)}e._chunk=null;e._debug('sent chunk from "write before connect"');var i=e._cb;e._cb=null;i(null)}e._interval=setInterval(function(){if(!e._cb||!e._channel||e._channel.bufferedAmount>e._maxBufferedAmount)return;e._debug("ending backpressure: bufferedAmount %d",e._channel.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref();e._debug("connect");e.emit("connect")}};c.prototype._onSignalingStateChange=function(){var e=this;if(e.destroyed)return;e._debug("signalingStateChange %s",e._pc.signalingState);e.emit("signalingStateChange",e._pc.signalingState)};c.prototype._onIceCandidate=function(e){var t=this;if(t.destroyed)return;if(e.candidate&&t.trickle){t.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}})}else if(!e.candidate){t._iceComplete=true;t.emit("_iceComplete")}};c.prototype._onChannelMessage=function(e){var t=this;if(t.destroyed)return;var r=e.data;t._debug("read: %d bytes",r.byteLength||r.length);if(r instanceof ArrayBuffer){r=l(new Uint8Array(r));t.push(r)}else{try{r=JSON.parse(r)}catch(i){}t.emit("data",r)}};c.prototype._onChannelOpen=function(){var e=this;if(e.connected||e.destroyed)return;e._debug("on channel open");e._channelReady=true;e._maybeReady()};c.prototype._onChannelClose=function(){var e=this;if(e.destroyed)return;e._debug("on channel close");e._destroy()};c.prototype._onAddStream=function(e){var t=this;if(t.destroyed)return;t._debug("on add stream");t.emit("stream",e.stream)};c.prototype._onError=function(e){var t=this;if(t.destroyed)return;t._debug("error %s",e.message||e);t._destroy(e)};c.prototype._debug=function(){var e=this;var t=[].slice.call(arguments);var r=e.channelName&&e.channelName.substring(0,7);t[0]="["+r+"] "+t[0];i.apply(null,t)};function p(){}}).call(this,{isBuffer:e("/Users/feross/code/webtorrent/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})},{"/Users/feross/code/webtorrent/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":45,debug:121,"get-browser-rtc":31,hat:127,inherits:129,"is-typedarray":32,once:29,stream:67,"typedarray-to-buffer":33}],31:[function(e,t,r){t.exports=function i(){if(typeof window==="undefined")return null;var e={RTCPeerConnection:window.mozRTCPeerConnection||window.RTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.mozRTCSessionDescription||window.RTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.mozRTCIceCandidate||window.RTCIceCandidate||window.webkitRTCIceCandidate};if(!e.RTCPeerConnection)return null;return e}},{}],32:[function(e,t,r){t.exports=a;a.strict=s;a.loose=o;var i=Object.prototype.toString;var n={"[object Int8Array]":true,"[object Int16Array]":true,"[object Int32Array]":true,"[object Uint8Array]":true,"[object Uint8ClampedArray]":true,"[object Uint16Array]":true,"[object Uint32Array]":true,"[object Float32Array]":true,"[object Float64Array]":true};function a(e){return s(e)||o(e)}function s(e){return e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array}function o(e){return n[i.call(e)]}},{}],33:[function(e,t,r){(function(r){var i=e("is-typedarray").strict;t.exports=function(e){var t=r.TYPED_ARRAY_SUPPORT?r._augment:function(e){return new r(e)};if(e instanceof Uint8Array){return t(e)}else if(e instanceof ArrayBuffer){return t(new Uint8Array(e))}else if(i(e)){return t(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}else{return new r(e)}}}).call(this,e("buffer").Buffer)},{buffer:39,"is-typedarray":32}],34:[function(e,t,r){(function(r){t.exports=l;var i=e("debug")("simple-websocket");var n=e("inherits");var a=e("is-typedarray");var s=e("stream");var o=e("typedarray-to-buffer");var f=e("ws");var u=typeof window!=="undefined"?window.WebSocket:f;n(l,s.Duplex);function l(e,t){var r=this;if(!(r instanceof l))return new l(e,t);if(!t)t={};i("new websocket: %s %o",e,t);t.allowHalfOpen=false;if(t.highWaterMark==null)t.highWaterMark=1024*1024;s.Duplex.call(r,t);r.url=e;r.connected=false;r.destroyed=false;r._maxBufferedAmount=t.highWaterMark;r._chunk=null;r._cb=null;r._interval=null;r._ws=new u(r.url);r._ws.binaryType="arraybuffer";r._ws.onopen=r._onOpen.bind(r);r._ws.onmessage=r._onMessage.bind(r);r._ws.onclose=r._onClose.bind(r);r._ws.onerror=function(){r._onError(new Error("connection error to "+r.url))};r.on("finish",function(){if(r.connected){setTimeout(function(){r._destroy()},100)}else{r.once("connect",function(){setTimeout(function(){r._destroy()},100)})}})}l.prototype.send=function(e){var t=this;if(!a.strict(e)&&!(e instanceof ArrayBuffer)&&!r.isBuffer(e)&&typeof e!=="string"&&(typeof Blob==="undefined"||!(e instanceof Blob))){e=JSON.stringify(e)}var n=e.length||e.byteLength||e.size;t._ws.send(e);i("write: %d bytes",n)};l.prototype.destroy=function(e){var t=this;t._destroy(null,e)};l.prototype._destroy=function(e,t){var r=this;if(r.destroyed)return;if(t)r.once("close",t);i("destroy (error: %s)",e&&e.message);this.readable=this.writable=false;if(!r._readableState.ended)r.push(null);if(!r._writableState.finished)r.end();r.connected=false;r.destroyed=true;clearInterval(r._interval);r._interval=null;r._chunk=null;r._cb=null;if(r._ws){var n=r._ws;var a=function(){n.onclose=null;r.emit("close")};if(n.readyState===u.CLOSED){a()}else{try{n.onclose=a;n.close()}catch(e){a()}}n.onopen=null;n.onmessage=null;n.onerror=null}r._ws=null;if(e)r.emit("error",e)};l.prototype._read=function(){};l.prototype._write=function(e,t,r){var n=this;if(n.destroyed)return r(new Error("cannot write after socket is destroyed"));if(n.connected){try{n.send(e)}catch(a){return n._onError(a)}if(typeof f!=="function"&&n._ws.bufferedAmount>n._maxBufferedAmount){i("start backpressure: bufferedAmount %d",n._ws.bufferedAmount);n._cb=r}else{r(null)}}else{i("write before connect");n._chunk=e;n._cb=r}};l.prototype._onMessage=function(e){var t=this;if(t.destroyed)return;var n=e.data;i("read: %d bytes",n.byteLength||n.length);if(n instanceof ArrayBuffer){n=o(new Uint8Array(n));t.push(n)}else if(r.isBuffer(n)){t.push(n)}else{try{n=JSON.parse(n)}catch(a){}t.emit("data",n)}};l.prototype._onOpen=function(){var e=this;if(e.connected||e.destroyed)return;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(t){return e._onError(t)}e._chunk=null;i('sent chunk from "write before connect"');var r=e._cb;e._cb=null;r(null)}if(typeof f!=="function"){e._interval=setInterval(function(){if(!e._cb||!e._ws||e._ws.bufferedAmount>e._maxBufferedAmount){return}i("ending backpressure: bufferedAmount %d",e._ws.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref()}i("connect");e.emit("connect")};l.prototype._onClose=function(){var e=this;if(e.destroyed)return;i("on close");e._destroy()};l.prototype._onError=function(e){var t=this;if(t.destroyed)return;i("error: %s",e.message||e);t._destroy(e)}}).call(this,{isBuffer:e("/Users/feross/code/webtorrent/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js")})},{"/Users/feross/code/webtorrent/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":45,debug:121,inherits:129,"is-typedarray":35,stream:67,"typedarray-to-buffer":36,ws:38}],35:[function(e,t,r){arguments[4][32][0].apply(r,arguments)},{dup:32}],36:[function(e,t,r){arguments[4][33][0].apply(r,arguments)},{buffer:39,dup:33,"is-typedarray":35}],37:[function(e,t,r){},{}],38:[function(e,t,r){arguments[4][37][0].apply(r,arguments)},{dup:37}],39:[function(e,t,r){(function(t){var i=e("base64-js");var n=e("ieee754");var a=e("is-array");r.Buffer=f;r.SlowBuffer=b;r.INSPECT_MAX_BYTES=50;f.poolSize=8192;var s={};f.TYPED_ARRAY_SUPPORT=t.TYPED_ARRAY_SUPPORT!==undefined?t.TYPED_ARRAY_SUPPORT:function(){function e(){}try{var t=new Uint8Array(1);t.foo=function(){return 42};t.constructor=e;return t.foo()===42&&t.constructor===e&&typeof t.subarray==="function"&&t.subarray(1,1).byteLength===0}catch(r){return false}}();function o(){return f.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function f(e){if(!(this instanceof f)){if(arguments.length>1)return new f(e,arguments[1]);return new f(e)}this.length=0;this.parent=undefined;if(typeof e==="number"){return u(this,e)}if(typeof e==="string"){return l(this,e,arguments.length>1?arguments[1]:"utf8")}return c(this,e)}function u(e,t){e=y(e,t<0?0:_(t)|0);if(!f.TYPED_ARRAY_SUPPORT){for(var r=0;r>>1;if(r)e.parent=s;return e}function _(e){if(e>=o()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+o().toString(16)+" bytes")}return e|0}function b(e,t){if(!(this instanceof b))return new b(e,t);var r=new f(e,t);delete r.parent;return r}f.isBuffer=function ee(e){return!!(e!=null&&e._isBuffer)};f.compare=function te(e,t){if(!f.isBuffer(e)||!f.isBuffer(t)){throw new TypeError("Arguments must be Buffers")}if(e===t)return 0;var r=e.length;var i=t.length;var n=0;var a=Math.min(r,i);while(n>>1;case"base64":return J(e).length;default:if(i)return K(e).length;t=(""+t).toLowerCase();i=true}}}f.byteLength=w;f.prototype.length=undefined;f.prototype.parent=undefined;function x(e,t,r){var i=false;t=t|0;r=r===undefined||r===Infinity?this.length:r|0;if(!e)e="utf8";if(t<0)t=0;if(r>this.length)r=this.length;if(r<=t)return"";while(true){switch(e){case"hex":return z(this,t,r);case"utf8":case"utf-8":return L(this,t,r);case"ascii":return R(this,t,r);case"binary":return P(this,t,r);case"base64":return I(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase();i=true}}}f.prototype.toString=function ne(){var e=this.length|0;if(e===0)return"";if(arguments.length===0)return L(this,0,e);return x.apply(this,arguments)};f.prototype.equals=function ae(e){if(!f.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return true;return f.compare(this,e)===0};f.prototype.inspect=function se(){var e="";var t=r.INSPECT_MAX_BYTES;if(this.length>0){e=this.toString("hex",0,t).match(/.{2}/g).join(" ");if(this.length>t)e+=" ... "}return""};f.prototype.compare=function oe(e){if(!f.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return 0;return f.compare(this,e)};f.prototype.indexOf=function fe(e,t){if(t>2147483647)t=2147483647;else if(t<-2147483648)t=-2147483648;t>>=0;if(this.length===0)return-1;if(t>=this.length)return-1;if(t<0)t=Math.max(this.length+t,0);if(typeof e==="string"){if(e.length===0)return-1;return String.prototype.indexOf.call(this,e,t)}if(f.isBuffer(e)){return r(this,e,t)}if(typeof e==="number"){if(f.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,e,t)}return r(this,[e],t)}function r(e,t,r){var i=-1;for(var n=0;r+nn){i=n}}var a=t.length;if(a%2!==0)throw new Error("Invalid hex string");if(i>a/2){i=a/2}for(var s=0;sa)r=a;if(e.length>0&&(r<0||t<0)||t>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!i)i="utf8";var s=false;for(;;){switch(i){case"hex":return k(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":return E(this,e,t,r);case"binary":return A(this,e,t,r);case"base64":return U(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase();s=true}}};f.prototype.toJSON=function pe(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function I(e,t,r){if(t===0&&r===e.length){return i.fromByteArray(e)}else{return i.fromByteArray(e.slice(t,r))}}function L(e,t,r){r=Math.min(e.length,r);var i=[];var n=t;while(n239?4:a>223?3:a>191?2:1;if(n+o<=r){var f,u,l,c;switch(o){case 1:if(a<128){s=a}break;case 2:f=e[n+1];if((f&192)===128){c=(a&31)<<6|f&63;if(c>127){s=c}}break;case 3:f=e[n+1];u=e[n+2];if((f&192)===128&&(u&192)===128){c=(a&15)<<12|(f&63)<<6|u&63;if(c>2047&&(c<55296||c>57343)){s=c}}break;case 4:f=e[n+1];u=e[n+2];l=e[n+3];if((f&192)===128&&(u&192)===128&&(l&192)===128){c=(a&15)<<18|(f&63)<<12|(u&63)<<6|l&63;if(c>65535&&c<1114112){s=c}}}}if(s===null){s=65533;o=1}else if(s>65535){s-=65536;i.push(s>>>10&1023|55296);s=56320|s&1023}i.push(s);n+=o}return C(i)}var B=4096;function C(e){var t=e.length;if(t<=B){return String.fromCharCode.apply(String,e)}var r="";var i=0;while(ii)r=i;var n="";for(var a=t;ar){e=r}if(t<0){t+=r;if(t<0)t=0}else if(t>r){t=r}if(tr)throw new RangeError("Trying to access beyond buffer length")}f.prototype.readUIntLE=function he(e,t,r){e=e|0;t=t|0;if(!r)F(e,t,this.length);var i=this[e];var n=1;var a=0;while(++a0&&(n*=256)){i+=this[e+--t]*n}return i};f.prototype.readUInt8=function ve(e,t){if(!t)F(e,1,this.length);return this[e]};f.prototype.readUInt16LE=function ge(e,t){if(!t)F(e,2,this.length);return this[e]|this[e+1]<<8};f.prototype.readUInt16BE=function ye(e,t){if(!t)F(e,2,this.length);return this[e]<<8|this[e+1]};f.prototype.readUInt32LE=function _e(e,t){if(!t)F(e,4,this.length);return(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};f.prototype.readUInt32BE=function be(e,t){if(!t)F(e,4,this.length);return this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};f.prototype.readIntLE=function we(e,t,r){e=e|0;t=t|0;if(!r)F(e,t,this.length);var i=this[e];var n=1;var a=0;while(++a=n)i-=Math.pow(2,8*t);return i};f.prototype.readIntBE=function xe(e,t,r){e=e|0;t=t|0;if(!r)F(e,t,this.length);var i=t;var n=1;var a=this[e+--i];while(i>0&&(n*=256)){a+=this[e+--i]*n}n*=128;if(a>=n)a-=Math.pow(2,8*t);return a};f.prototype.readInt8=function ke(e,t){if(!t)F(e,1,this.length);if(!(this[e]&128))return this[e];return(255-this[e]+1)*-1};f.prototype.readInt16LE=function Se(e,t){if(!t)F(e,2,this.length);var r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};f.prototype.readInt16BE=function Ee(e,t){if(!t)F(e,2,this.length);var r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};f.prototype.readInt32LE=function Ae(e,t){if(!t)F(e,4,this.length);return this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};f.prototype.readInt32BE=function Ue(e,t){if(!t)F(e,4,this.length);return this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};f.prototype.readFloatLE=function Te(e,t){if(!t)F(e,4,this.length);return n.read(this,e,true,23,4)};f.prototype.readFloatBE=function Ie(e,t){if(!t)F(e,4,this.length);return n.read(this,e,false,23,4)};f.prototype.readDoubleLE=function Le(e,t){if(!t)F(e,8,this.length);return n.read(this,e,true,52,8)};f.prototype.readDoubleBE=function Be(e,t){if(!t)F(e,8,this.length);return n.read(this,e,false,52,8)};function M(e,t,r,i,n,a){if(!f.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>n||te.length)throw new RangeError("index out of range")}f.prototype.writeUIntLE=function Ce(e,t,r,i){e=+e;t=t|0;r=r|0;if(!i)M(this,e,t,r,Math.pow(2,8*r),0);var n=1;var a=0;this[t]=e&255;while(++a=0&&(a*=256)){this[t+n]=e/a&255}return t+r};f.prototype.writeUInt8=function Pe(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,1,255,0);if(!f.TYPED_ARRAY_SUPPORT)e=Math.floor(e);this[t]=e;return t+1};function j(e,t,r,i){if(t<0)t=65535+t+1;for(var n=0,a=Math.min(e.length-r,2);n>>(i?n:1-n)*8}}f.prototype.writeUInt16LE=function ze(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,2,65535,0);if(f.TYPED_ARRAY_SUPPORT){this[t]=e;this[t+1]=e>>>8}else{j(this,e,t,true)}return t+2};f.prototype.writeUInt16BE=function Oe(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,2,65535,0);if(f.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e}else{j(this,e,t,false)}return t+2};function D(e,t,r,i){if(t<0)t=4294967295+t+1;for(var n=0,a=Math.min(e.length-r,4);n>>(i?n:3-n)*8&255}}f.prototype.writeUInt32LE=function Fe(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,4,4294967295,0);if(f.TYPED_ARRAY_SUPPORT){this[t+3]=e>>>24;this[t+2]=e>>>16;this[t+1]=e>>>8;this[t]=e}else{D(this,e,t,true)}return t+4; -};f.prototype.writeUInt32BE=function Me(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,4,4294967295,0);if(f.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e}else{D(this,e,t,false)}return t+4};f.prototype.writeIntLE=function je(e,t,r,i){e=+e;t=t|0;if(!i){var n=Math.pow(2,8*r-1);M(this,e,t,r,n-1,-n)}var a=0;var s=1;var o=e<0?1:0;this[t]=e&255;while(++a>0)-o&255}return t+r};f.prototype.writeIntBE=function De(e,t,r,i){e=+e;t=t|0;if(!i){var n=Math.pow(2,8*r-1);M(this,e,t,r,n-1,-n)}var a=r-1;var s=1;var o=e<0?1:0;this[t+a]=e&255;while(--a>=0&&(s*=256)){this[t+a]=(e/s>>0)-o&255}return t+r};f.prototype.writeInt8=function Ne(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,1,127,-128);if(!f.TYPED_ARRAY_SUPPORT)e=Math.floor(e);if(e<0)e=255+e+1;this[t]=e;return t+1};f.prototype.writeInt16LE=function He(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,2,32767,-32768);if(f.TYPED_ARRAY_SUPPORT){this[t]=e;this[t+1]=e>>>8}else{j(this,e,t,true)}return t+2};f.prototype.writeInt16BE=function qe(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,2,32767,-32768);if(f.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e}else{j(this,e,t,false)}return t+2};f.prototype.writeInt32LE=function Ge(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,4,2147483647,-2147483648);if(f.TYPED_ARRAY_SUPPORT){this[t]=e;this[t+1]=e>>>8;this[t+2]=e>>>16;this[t+3]=e>>>24}else{D(this,e,t,true)}return t+4};f.prototype.writeInt32BE=function We(e,t,r){e=+e;t=t|0;if(!r)M(this,e,t,4,2147483647,-2147483648);if(e<0)e=4294967295+e+1;if(f.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e}else{D(this,e,t,false)}return t+4};function N(e,t,r,i,n,a){if(t>n||te.length)throw new RangeError("index out of range");if(r<0)throw new RangeError("index out of range")}function H(e,t,r,i,a){if(!a){N(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38)}n.write(e,t,r,i,23,4);return r+4}f.prototype.writeFloatLE=function Ve(e,t,r){return H(this,e,t,true,r)};f.prototype.writeFloatBE=function Ye(e,t,r){return H(this,e,t,false,r)};function q(e,t,r,i,a){if(!a){N(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308)}n.write(e,t,r,i,52,8);return r+8}f.prototype.writeDoubleLE=function $e(e,t,r){return q(this,e,t,true,r)};f.prototype.writeDoubleBE=function Ke(e,t,r){return q(this,e,t,false,r)};f.prototype.copy=function Ze(e,t,r,i){if(!r)r=0;if(!i&&i!==0)i=this.length;if(t>=e.length)t=e.length;if(!t)t=0;if(i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");if(i>this.length)i=this.length;if(e.length-t=0;a--){e[a+t]=this[a+r]}}else if(n<1e3||!f.TYPED_ARRAY_SUPPORT){for(a=0;a=this.length)throw new RangeError("start out of bounds");if(r<0||r>this.length)throw new RangeError("end out of bounds");var i;if(typeof e==="number"){for(i=t;i55295&&r<57344){if(!n){if(r>56319){if((t-=3)>-1)a.push(239,191,189);continue}else if(s+1===i){if((t-=3)>-1)a.push(239,191,189);continue}n=r;continue}if(r<56320){if((t-=3)>-1)a.push(239,191,189);n=r;continue}r=n-55296<<10|r-56320|65536}else if(n){if((t-=3)>-1)a.push(239,191,189)}n=null;if(r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else{throw new Error("Invalid code point")}}return a}function Z(e){var t=[];for(var r=0;r>8;n=r%256;a.push(n);a.push(i)}return a}function J(e){return i.toByteArray(V(e))}function Q(e,t,r,i){for(var n=0;n=t.length||n>=e.length)break;t[n+r]=e[n]}return n}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":40,ieee754:41,"is-array":42}],40:[function(e,t,r){var i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(e){"use strict";var t=typeof Uint8Array!=="undefined"?Uint8Array:Array;var r="+".charCodeAt(0);var n="/".charCodeAt(0);var a="0".charCodeAt(0);var s="a".charCodeAt(0);var o="A".charCodeAt(0);var f="-".charCodeAt(0);var u="_".charCodeAt(0);function l(e){var t=e.charCodeAt(0);if(t===r||t===f)return 62;if(t===n||t===u)return 63;if(t0){throw new Error("Invalid string. Length must be a multiple of 4")}var f=e.length;s="="===e.charAt(f-2)?2:"="===e.charAt(f-1)?1:0;o=new t(e.length*3/4-s);n=s>0?e.length-4:e.length;var u=0;function c(e){o[u++]=e}for(r=0,i=0;r>16);c((a&65280)>>8);c(a&255)}if(s===2){a=l(e.charAt(r))<<2|l(e.charAt(r+1))>>4;c(a&255)}else if(s===1){a=l(e.charAt(r))<<10|l(e.charAt(r+1))<<4|l(e.charAt(r+2))>>2;c(a>>8&255);c(a&255)}return o}function p(e){var t,r=e.length%3,n="",a,s;function o(e){return i.charAt(e)}function f(e){return o(e>>18&63)+o(e>>12&63)+o(e>>6&63)+o(e&63)}for(t=0,s=e.length-r;t>2);n+=o(a<<4&63);n+="==";break;case 2:a=(e[e.length-2]<<8)+e[e.length-1];n+=o(a>>10);n+=o(a>>4&63);n+=o(a<<2&63);n+="=";break}return n}e.toByteArray=c;e.fromByteArray=p})(typeof r==="undefined"?this.base64js={}:r)},{}],41:[function(e,t,r){r.read=function(e,t,r,i,n){var a,s;var o=n*8-i-1;var f=(1<>1;var l=-7;var c=r?n-1:0;var p=r?-1:1;var d=e[t+c];c+=p;a=d&(1<<-l)-1;d>>=-l;l+=o;for(;l>0;a=a*256+e[t+c],c+=p,l-=8){}s=a&(1<<-l)-1;a>>=-l;l+=i;for(;l>0;s=s*256+e[t+c],c+=p,l-=8){}if(a===0){a=1-u}else if(a===f){return s?NaN:(d?-1:1)*Infinity}else{s=s+Math.pow(2,i);a=a-u}return(d?-1:1)*s*Math.pow(2,a-i)};r.write=function(e,t,r,i,n,a){var s,o,f;var u=a*8-n-1;var l=(1<>1;var p=n===23?Math.pow(2,-24)-Math.pow(2,-77):0;var d=i?0:a-1;var h=i?1:-1;var m=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){o=isNaN(t)?1:0;s=l}else{s=Math.floor(Math.log(t)/Math.LN2);if(t*(f=Math.pow(2,-s))<1){s--;f*=2}if(s+c>=1){t+=p/f}else{t+=p*Math.pow(2,1-c)}if(t*f>=2){s++;f/=2}if(s+c>=l){o=0;s=l}else if(s+c>=1){o=(t*f-1)*Math.pow(2,n);s=s+c}else{o=t*Math.pow(2,c-1)*Math.pow(2,n);s=0}}for(;n>=8;e[r+d]=o&255,d+=h,o/=256,n-=8){}s=s<0;e[r+d]=s&255,d+=h,s/=256,u-=8){}e[r+d-h]|=m*128}},{}],42:[function(e,t,r){var i=Array.isArray;var n=Object.prototype.toString;t.exports=i||function(e){return!!e&&"[object Array]"==n.call(e)}},{}],43:[function(e,t,r){function i(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}t.exports=i;i.EventEmitter=i;i.prototype._events=undefined;i.prototype._maxListeners=undefined;i.defaultMaxListeners=10;i.prototype.setMaxListeners=function(e){if(!a(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");this._maxListeners=e;return this};i.prototype.emit=function(e){var t,r,i,a,f,u;if(!this._events)this._events={};if(e==="error"){if(!this._events.error||s(this._events.error)&&!this._events.error.length){t=arguments[1];if(t instanceof Error){throw t}throw TypeError('Uncaught, unspecified "error" event.')}}r=this._events[e];if(o(r))return false;if(n(r)){switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:i=arguments.length;a=new Array(i-1);for(f=1;f0&&this._events[e].length>r){this._events[e].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[e].length);if(typeof console.trace==="function"){console.trace()}}}return this};i.prototype.on=i.prototype.addListener;i.prototype.once=function(e,t){if(!n(t))throw TypeError("listener must be a function");var r=false;function i(){this.removeListener(e,i);if(!r){r=true;t.apply(this,arguments)}}i.listener=t;this.on(e,i);return this};i.prototype.removeListener=function(e,t){var r,i,a,o;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;r=this._events[e];a=r.length;i=-1;if(r===t||n(r.listener)&&r.listener===t){delete this._events[e];if(this._events.removeListener)this.emit("removeListener",e,t)}else if(s(r)){for(o=a;o-->0;){if(r[o]===t||r[o].listener&&r[o].listener===t){i=o;break}}if(i<0)return this;if(r.length===1){r.length=0;delete this._events[e]}else{r.splice(i,1)}if(this._events.removeListener)this.emit("removeListener",e,t)}return this};i.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[e])delete this._events[e];return this}if(arguments.length===0){for(t in this._events){if(t==="removeListener")continue;this.removeAllListeners(t)}this.removeAllListeners("removeListener");this._events={};return this}r=this._events[e];if(n(r)){this.removeListener(e,r)}else{while(r.length)this.removeListener(e,r[r.length-1])}delete this._events[e];return this};i.prototype.listeners=function(e){var t;if(!this._events||!this._events[e])t=[];else if(n(this._events[e]))t=[this._events[e]];else t=this._events[e].slice();return t};i.listenerCount=function(e,t){var r;if(!e._events||!e._events[t])r=0;else if(n(e._events[t]))r=1;else r=e._events[t].length;return r};function n(e){return typeof e==="function"}function a(e){return typeof e==="number"}function s(e){return typeof e==="object"&&e!==null}function o(e){return e===void 0}},{}],44:[function(e,t,r){var i=e("http");var n=t.exports;for(var a in i){if(i.hasOwnProperty(a))n[a]=i[a]}n.request=function(e,t){if(!e)e={};e.scheme="https";e.protocol="https:";return i.request.call(this,e,t)}},{http:68}],45:[function(e,t,r){t.exports=function(e){return!!(e!=null&&(e._isBuffer||e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)))}},{}],46:[function(e,t,r){t.exports=Array.isArray||function(e){return Object.prototype.toString.call(e)=="[object Array]"}},{}],47:[function(e,t,r){r.endianness=function(){return"LE"};r.hostname=function(){if(typeof location!=="undefined"){return location.hostname}else return""};r.loadavg=function(){return[]};r.uptime=function(){return 0};r.freemem=function(){return Number.MAX_VALUE};r.totalmem=function(){return Number.MAX_VALUE};r.cpus=function(){return[]};r.type=function(){return"Browser"};r.release=function(){if(typeof navigator!=="undefined"){return navigator.appVersion}return""};r.networkInterfaces=r.getNetworkInterfaces=function(){return{}};r.arch=function(){return"javascript"};r.platform=function(){return"browser"};r.tmpdir=r.tmpDir=function(){return"/tmp"};r.EOL="\n"},{}],48:[function(e,t,r){(function(e){function t(e,t){var r=0;for(var i=e.length-1;i>=0;i--){var n=e[i];if(n==="."){e.splice(i,1)}else if(n===".."){e.splice(i,1);r++}else if(r){e.splice(i,1);r--}}if(t){for(;r--;r){e.unshift("..")}}return e}var i=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var n=function(e){return i.exec(e).slice(1)};r.resolve=function(){var r="",i=false;for(var n=arguments.length-1;n>=-1&&!i;n--){var s=n>=0?arguments[n]:e.cwd();if(typeof s!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!s){continue}r=s+"/"+r;i=s.charAt(0)==="/"}r=t(a(r.split("/"),function(e){return!!e}),!i).join("/");return(i?"/":"")+r||"."};r.normalize=function(e){var i=r.isAbsolute(e),n=s(e,-1)==="/";e=t(a(e.split("/"),function(e){return!!e}),!i).join("/");if(!e&&!i){e="."}if(e&&n){e+="/"}return(i?"/":"")+e};r.isAbsolute=function(e){return e.charAt(0)==="/"};r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(a(e,function(e,t){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))};r.relative=function(e,t){e=r.resolve(e).substr(1);t=r.resolve(t).substr(1);function i(e){var t=0;for(;t=0;r--){if(e[r]!=="")break}if(t>r)return[];return e.slice(t,r-t+1)}var n=i(e.split("/"));var a=i(t.split("/"));var s=Math.min(n.length,a.length);var o=s;for(var f=0;f1){for(var r=1;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},x=l-c,k=Math.floor,S=String.fromCharCode,E;function A(e){throw RangeError(w[e])}function U(e,t){var r=e.length;var i=[];while(r--){i[r]=t(e[r])}return i}function T(e,t){var r=e.split("@");var i="";if(r.length>1){i=r[0]+"@";e=r[1]}e=e.replace(b,".");var n=e.split(".");var a=U(n,t).join(".");return i+a}function I(e){var t=[],r=0,i=e.length,n,a;while(r=55296&&n<=56319&&r65535){e-=65536;t+=S(e>>>10&1023|55296);e=56320|e&1023}t+=S(e);return t}).join("")}function B(e){if(e-48<10){return e-22}if(e-65<26){return e-65}if(e-97<26){return e-97}return l}function C(e,t){return e+22+75*(e<26)-((t!=0)<<5)}function R(e,t,r){var i=0;e=r?k(e/h):e>>1;e+=k(e/t);for(;e>x*p>>1;i+=l){e=k(e/x)}return k(i+(x+1)*e/(e+d))}function P(e){var t=[],r=e.length,i,n=0,a=v,s=m,o,f,d,h,y,_,b,w,x;o=e.lastIndexOf(g);if(o<0){o=0}for(f=0;f=128){A("not-basic")}t.push(e.charCodeAt(f))}for(d=o>0?o+1:0;d=r){A("invalid-input")}b=B(e.charCodeAt(d++));if(b>=l||b>k((u-n)/y)){A("overflow")}n+=b*y;w=_<=s?c:_>=s+p?p:_-s;if(bk(u/x)){A("overflow")}y*=x}i=t.length+1;s=R(n-h,i,h==0);if(k(n/i)>u-a){A("overflow")}a+=k(n/i);n%=i;t.splice(n++,0,a)}return L(t)}function z(e){var t,r,i,n,a,s,o,f,d,h,y,_=[],b,w,x,E;e=I(e);b=e.length;t=v;r=0;a=m;for(s=0;s=t&&yk((u-r)/w)){A("overflow")}r+=(o-t)*w;t=o;for(s=0;su){A("overflow")}if(y==t){for(f=r,d=l;;d+=l){h=d<=a?c:d>=a+p?p:d-a;if(f0&&u>f){u=f}for(var l=0;l=0){d=c.substr(0,p);h=c.substr(p+1)}else{d=c;h=""}m=decodeURIComponent(d);v=decodeURIComponent(h);if(!i(s,m)){s[m]=v}else if(n(s[m])){s[m].push(v)}else{s[m]=[s[m],v]}}return s};var n=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}},{}],52:[function(e,t,r){"use strict";var i=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,o){t=t||"&";r=r||"=";if(e===null){e=undefined}if(typeof e==="object"){return a(s(e),function(s){var o=encodeURIComponent(i(s))+r;if(n(e[s])){return a(e[s],function(e){return o+encodeURIComponent(i(e))}).join(t)}else{return o+encodeURIComponent(i(e[s]))}}).join(t)}if(!o)return"";return encodeURIComponent(i(o))+r+encodeURIComponent(i(e))};var n=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};function a(e,t){if(e.map)return e.map(t);var r=[];for(var i=0;i0){if(t.ended&&!n){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&n){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{if(t.decoder&&!n&&!i)r=t.decoder.write(r);if(!n)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(n)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)b(e)}x(e,t)}}else if(!n){t.reading=false}return h(t)}function h(e){return!e.ended&&(e.needReadable||e.length=m){e=m}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function g(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(e===null||isNaN(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=v(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else{return t.length}}return e}p.prototype.read=function(e){u("read",e);var t=this._readableState;var r=e;if(typeof e!=="number"||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){u("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)L(this);else b(this);return null}e=g(e,t);if(e===0&&t.ended){if(t.length===0)L(this);return null}var i=t.needReadable;u("need readable",i);if(t.length===0||t.length-e0)n=I(e,t);else n=null;if(n===null){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)L(this);if(n!==null)this.emit("data",n);return n};function y(e,t){var r=null;if(!a.isBuffer(t)&&typeof t!=="string"&&t!==null&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function _(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;b(e)}function b(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)i(w,e);else w(e)}}function w(e){u("emit readable");e.emit("readable");T(e)}function x(e,t){if(!t.readingMore){t.readingMore=true;i(k,e,t)}}function k(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=i){if(n)o=r.join("");else o=a.concat(r,i);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;i(B,t,e)}}function B(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function C(e,t){for(var r=0,i=e.length;r-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e};function d(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=new n(t,r)}return t}function h(e,t,r,i,a){r=d(t,r,i);if(n.isBuffer(r))i="buffer";var s=t.objectMode?1:r.length;t.length+=s;var o=t.lengthe._pos){var s=r.substr(e._pos);if(e._charset==="x-user-defined"){var o=new n(s.length);for(var f=0;fe._pos){e.push(new n(new Uint8Array(l.result.slice(e._pos))));e._pos=l.result.byteLength}};l.onload=function(){e.push(null)};l.readAsArrayBuffer(r);break}if(e._xhr.readyState===u.DONE&&e._mode!=="ms-stream"){e.push(null)}}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{"./capability":69,_process:49,buffer:39,foreach:73,inherits:129,stream:67}],72:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Time-out",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Request Entity Too Large",414:"Request-URI Too Large",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Time-out",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],73:[function(e,t,r){var i=Object.prototype.hasOwnProperty;var n=Object.prototype.toString;t.exports=function a(e,t,r){if(n.call(t)!=="[object Function]"){throw new TypeError("iterator must be a function")}var a=e.length;if(a===+a){for(var s=0;s0&&!i.call(e,0)){for(var h=0;h0){for(var m=0;m=0&&i.call(e.callee)==="[object Function]"}return r}},{}],77:[function(e,t,r){var i=e("buffer").Buffer;var n=i.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function a(e){if(e&&!n(e)){throw new Error("Unknown encoding: "+e)}}var s=r.StringDecoder=function(e){this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,"");a(e);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=f;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=u;break;default:this.write=o;return}this.charBuffer=new i(6);this.charReceived=0;this.charLength=0};s.prototype.write=function(e){var t="";while(this.charLength){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;e.copy(this.charBuffer,this.charReceived,0,r);this.charReceived+=r;if(this.charReceived=55296&&i<=56319){this.charLength+=this.surrogateSize;t="";continue}this.charReceived=this.charLength=0;if(e.length===0){return t}break}this.detectIncompleteChar(e);var n=e.length;if(this.charLength){e.copy(this.charBuffer,0,e.length-this.charReceived,n);n-=this.charReceived}t+=e.toString(this.encoding,0,n);var n=t.length-1;var i=t.charCodeAt(n);if(i>=55296&&i<=56319){var a=this.surrogateSize;this.charLength+=a;this.charReceived+=a;this.charBuffer.copy(this.charBuffer,a,0,a);e.copy(this.charBuffer,0,0,a);return t.substring(0,n)}return t};s.prototype.detectIncompleteChar=function(e){var t=e.length>=3?3:e.length;for(;t>0;t--){var r=e[e.length-t];if(t==1&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t};s.prototype.end=function(e){var t="";if(e&&e.length)t=this.write(e);if(this.charReceived){var r=this.charReceived;var i=this.charBuffer;var n=this.encoding;t+=i.slice(0,r).toString(n)}return t};function o(e){return e.toString(this.encoding)}function f(e){this.charReceived=e.length%2;this.charLength=this.charReceived?2:0}function u(e){this.charReceived=e.length%3;this.charLength=this.charReceived?3:0}},{buffer:39}],78:[function(e,t,r){var i=e("punycode");r.parse=_;r.resolve=w;r.resolveObject=x;r.format=b;r.Url=n;function n(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,o=["<",">",'"',"`"," ","\r","\n"," "],f=["{","}","|","\\","^","`"].concat(o),u=["'"].concat(f),l=["%","/","?",";","#"].concat(u),c=["/","?","#"],p=255,d=/^[a-z0-9A-Z_-]{0,63}$/,h=/^([a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:true,"javascript:":true},v={javascript:true,"javascript:":true},g={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},y=e("querystring");function _(e,t,r){if(e&&S(e)&&e instanceof n)return e;var i=new n;i.parse(e,t,r);return i}n.prototype.parse=function(e,t,r){if(!k(e)){throw new TypeError("Parameter 'url' must be a string, not "+typeof e)}var n=e;n=n.trim();var s=a.exec(n);if(s){s=s[0];var o=s.toLowerCase();this.protocol=o;n=n.substr(s.length)}if(r||s||n.match(/^\/\/[^@\/]+@[^@\/]+/)){var f=n.substr(0,2)==="//";if(f&&!(s&&v[s])){n=n.substr(2);this.slashes=true}}if(!v[s]&&(f||s&&!g[s])){var _=-1;for(var b=0;b127){I+="x"}else{I+=T[L]}}if(!I.match(d)){var C=A.slice(0,b);var R=A.slice(b+1);var P=T.match(h);if(P){C.push(P[1]);R.unshift(P[2])}if(R.length){n="/"+R.join(".")+n}this.hostname=C.join(".");break}}}}if(this.hostname.length>p){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!E){var z=this.hostname.split(".");var O=[];for(var b=0;b0?r.host.split("@"):false;if(d){r.auth=d.shift();r.host=r.hostname=d.shift()}}r.search=e.search;r.query=e.query;if(!E(r.pathname)||!E(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.href=r.format();return r}if(!c.length){r.pathname=null;if(r.search){r.path="/"+r.search}else{r.path=null}r.href=r.format();return r}var h=c.slice(-1)[0];var m=(r.host||e.host)&&(h==="."||h==="..")||h==="";var y=0;for(var _=c.length;_>=0;_--){h=c[_];if(h=="."){c.splice(_,1)}else if(h===".."){c.splice(_,1);y++}else if(y){c.splice(_,1);y--}}if(!u&&!l){for(;y--;y){c.unshift("..")}}if(u&&c[0]!==""&&(!c[0]||c[0].charAt(0)!=="/")){c.unshift("")}if(m&&c.join("/").substr(-1)!=="/"){c.push("")}var b=c[0]===""||c[0]&&c[0].charAt(0)==="/";if(p){r.hostname=r.host=b?"":c.length?c.shift():"";var d=r.host&&r.host.indexOf("@")>0?r.host.split("@"):false;if(d){r.auth=d.shift();r.host=r.hostname=d.shift()}}u=u||r.host&&c.length;if(u&&!b){c.unshift("")}if(!c.length){r.pathname=null;r.path=null}else{r.pathname=c.join("/")}if(!E(r.pathname)||!E(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.auth=e.auth||r.auth;r.slashes=r.slashes||e.slashes;r.href=r.format();return r};n.prototype.parseHost=function(){var e=this.host;var t=s.exec(e);if(t){t=t[0];if(t!==":"){this.port=t.substr(1)}e=e.substr(0,e.length-t.length)}if(e)this.hostname=e};function k(e){return typeof e==="string"}function S(e){return typeof e==="object"&&e!==null}function E(e){return e===null}function A(e){return e==null}},{punycode:50,querystring:53}],79:[function(e,t,r){(function(r){var i=e("inherits");var n=e("readable-stream").Transform;var a=e("defined");t.exports=s;i(s,n);function s(e,t){if(!(this instanceof s))return new s(e,t);n.call(this);if(!t)t={};if(typeof e==="object"){t=e;e=t.size}this.size=e||512;if(t.nopad)this._zeroPadding=false;else this._zeroPadding=a(t.zeroPadding,true);this._buffered=[];this._bufferedBytes=0}s.prototype._transform=function(e,t,i){this._bufferedBytes+=e.length;this._buffered.push(e);while(this._bufferedBytes>=this.size){var n=r.concat(this._buffered);this._bufferedBytes-=this.size;this.push(n.slice(0,this.size));this._buffered=[n.slice(this.size,n.length)]}i()};s.prototype._flush=function(){if(this._bufferedBytes&&this._zeroPadding){var e=new r(this.size-this._bufferedBytes);e.fill(0);this._buffered.push(e);this.push(r.concat(this._buffered));this._buffered=null}else if(this._bufferedBytes){this.push(r.concat(this._buffered));this._buffered=null}this.push(null)}}).call(this,e("buffer").Buffer)},{buffer:39,defined:80,inherits:129,"readable-stream":89}],80:[function(e,t,r){t.exports=function(){for(var e=0;e0){if(t.ended&&!n){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&n){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{if(t.decoder&&!n&&!i)r=t.decoder.write(r);if(!n)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(n)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)_(e)}w(e,t)}}else if(!n){t.reading=false}return d(t)}function d(e){return!e.ended&&(e.needReadable||e.length=h){e=h}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function v(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(isNaN(e)||o.isNull(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=m(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else return t.length}return e}c.prototype.read=function(e){u("read",e);var t=this._readableState;var r=e;if(!o.isNumber(e)||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){u("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)T(this);else _(this);return null}e=v(e,t);if(e===0&&t.ended){if(t.length===0)T(this);return null}var i=t.needReadable;u("need readable",i);if(t.length===0||t.length-e0)n=U(e,t);else n=null;if(o.isNull(n)){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)T(this);if(!o.isNull(n))this.emit("data",n);return n};function g(e,t){var r=null;if(!o.isBuffer(t)&&!o.isString(t)&&!o.isNullOrUndefined(t)&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function y(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;_(e)}function _(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)r.nextTick(function(){b(e)});else b(e)}}function b(e){u("emit readable");e.emit("readable");A(e)}function w(e,t){if(!t.readingMore){t.readingMore=true;r.nextTick(function(){x(e,t)})}}function x(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=i){if(a)o=r.join("");else o=n.concat(r,i);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;r.nextTick(function(){if(!t.endEmitted&&t.length===0){t.endEmitted=true;e.readable=false;e.emit("end")}})}}function I(e,t){for(var r=0,i=e.length;r1){var r=[];for(var i=0;i1||a;w(e,f,r);return}else{throw new Error("invalid input type")}if(!e.name)throw new Error("missing requied `name` property on input");s.path=e.name.split(o.sep);r(null,s)}}),function(e,t){if(e)return r(e);t=l(t);r(null,t,a)})}}function w(e,t,r){k(e,x,function(i,n){if(i)return r(i);if(Array.isArray(n))n=l(n);else n=[n];e=o.normalize(e);if(t){e=e.slice(0,e.lastIndexOf(o.sep)+1)}if(e[e.length-1]!==o.sep)e+=o.sep;n.forEach(function(t){t.getStream=R(t.path);t.path=t.path.replace(e,"").split(o.sep)});r(null,n)})}function x(e,t){t=m(t);c.stat(e,function(r,i){if(r)return t(r);var n={length:i.size,path:e};t(null,n)})}function k(e,t,r){c.readdir(e,function(i,n){if(i&&i.code==="ENOTDIR"){t(e,r)}else if(i){r(i)}else{v(n.filter(S).filter(d.not).map(function(r){return function(i){k(o.join(e,r),t,i)}}),r)}})}function S(e){return e[0]!=="."}function E(e,t,r){r=m(r);var n=[];var s=0;var o=e.map(function(e){return e.getStream});var f=0;var u=0;var l=false;var c=new h(o);var p=new a(t,{zeroPadding:false});c.on("error",y);c.pipe(p).on("data",d).on("end",v).on("error",y);function d(e){s+=e.length;var t=u;g(e,function(e){n[t]=e;f-=1;b()});f+=1;u+=1}function v(){l=true;b()}function y(e){_();r(e)}function _(){c.removeListener("error",y);p.removeListener("data",d);p.removeListener("end",v);p.removeListener("error",y)}function b(){if(l&&f===0){_();r(null,new i(n.join(""),"hex"),s)}}}function A(e,i,a){var o=i.announceList;if(!o){if(typeof i.announce==="string")o=[[i.announce]];else if(Array.isArray(i.announce)){o=i.announce.map(function(e){return[e]})}}if(!o)o=[];if(r.WEBTORRENT_ANNOUNCE){if(typeof r.WEBTORRENT_ANNOUNCE==="string"){o.push([[r.WEBTORRENT_ANNOUNCE]])}else if(Array.isArray(r.WEBTORRENT_ANNOUNCE)){o=o.concat(r.WEBTORRENT_ANNOUNCE.map(function(e){return[e]}))}}if(o.length===0){o=o.concat(t.exports.announceList)}if(typeof i.urlList==="string")i.urlList=[i.urlList];var f={info:{name:i.name},announce:o[0][0],"announce-list":o,"creation date":Number(i.creationDate)||Date.now(),encoding:"UTF-8"};if(i.comment!==undefined)f.comment=i.comment;if(i.createdBy!==undefined)f["created by"]=i.createdBy;if(i.private!==undefined)f.info.private=Number(i.private);if(i.sslCert!==undefined)f.info["ssl-cert"]=i.sslCert;if(i.urlList!==undefined)f["url-list"]=i.urlList;var u=i.pieceLength||s(e.reduce(U,0));f.info["piece length"]=u;E(e,u,function(t,r,s){if(t)return a(t);f.info.pieces=r;e.forEach(function(e){delete e.getStream});if(i.singleFileTorrent){f.info.length=s}else{f.info.files=e}a(null,n.encode(f))})}function U(e,t){return e+t.length}function T(e){return typeof Blob!=="undefined"&&e instanceof Blob}function I(e){return typeof FileList==="function"&&e instanceof FileList}function L(e){return typeof e==="object"&&typeof e.pipe==="function"}function B(e){return function(){return new u(e)}}function C(e){return function(){var t=new y.PassThrough;t.end(e);return t}}function R(e){return function(){return c.createReadStream(e)}}function P(e,t){return function(){var r=new y.Transform;r._transform=function(e,r,i){t.length+=e.length;this.push(e);i()};e.pipe(r);return r}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{bencode:92,"block-stream2":96,buffer:39,dezalgo:107,"filestream/read":113,flatten:114,fs:37,"is-file":115,junk:116,multistream:134,once:118,path:48,"piece-length":119,"run-parallel":155,"simple-sha1":163,stream:67}],92:[function(e,t,r){arguments[4][15][0].apply(r,arguments)},{"./lib/decode":93,"./lib/encode":95,dup:15}],93:[function(e,t,r){arguments[4][16][0].apply(r,arguments)},{"./dict":94,buffer:39,dup:16}],94:[function(e,t,r){arguments[4][17][0].apply(r,arguments)},{dup:17}],95:[function(e,t,r){arguments[4][18][0].apply(r,arguments)},{buffer:39,dup:18}],96:[function(e,t,r){arguments[4][79][0].apply(r,arguments)},{buffer:39,defined:97,dup:79,inherits:129,"readable-stream":106}],97:[function(e,t,r){arguments[4][80][0].apply(r,arguments)},{dup:80}],98:[function(e,t,r){arguments[4][81][0].apply(r,arguments)},{"./_stream_readable":100,"./_stream_writable":102,_process:49,"core-util-is":103,dup:81,inherits:129}],99:[function(e,t,r){arguments[4][82][0].apply(r,arguments)},{"./_stream_transform":101,"core-util-is":103,dup:82,inherits:129}],100:[function(e,t,r){arguments[4][83][0].apply(r,arguments)},{"./_stream_duplex":98,_process:49,buffer:39,"core-util-is":103,dup:83,events:43,inherits:129,isarray:104,stream:67,"string_decoder/":105,util:38}],101:[function(e,t,r){arguments[4][84][0].apply(r,arguments)},{"./_stream_duplex":98,"core-util-is":103,dup:84,inherits:129}],102:[function(e,t,r){arguments[4][85][0].apply(r,arguments)},{"./_stream_duplex":98,_process:49,buffer:39,"core-util-is":103,dup:85,inherits:129,stream:67}],103:[function(e,t,r){arguments[4][60][0].apply(r,arguments)},{"/Users/feross/code/webtorrent/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js":45,dup:60}],104:[function(e,t,r){arguments[4][46][0].apply(r,arguments)},{dup:46}],105:[function(e,t,r){arguments[4][77][0].apply(r,arguments)},{buffer:39,dup:77}],106:[function(e,t,r){arguments[4][89][0].apply(r,arguments)},{"./lib/_stream_duplex.js":98,"./lib/_stream_passthrough.js":99,"./lib/_stream_readable.js":100,"./lib/_stream_transform.js":101,"./lib/_stream_writable.js":102,dup:89,stream:67}],107:[function(e,t,r){arguments[4][19][0].apply(r,arguments)},{asap:108,dup:19,wrappy:110}],108:[function(e,t,r){arguments[4][20][0].apply(r,arguments)},{"./raw":109,dup:20}],109:[function(e,t,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],110:[function(e,t,r){arguments[4][22][0].apply(r,arguments)},{dup:22}],111:[function(e,t,r){arguments[4][33][0].apply(r,arguments)},{buffer:39,dup:33,"is-typedarray":112}],112:[function(e,t,r){arguments[4][32][0].apply(r,arguments)},{dup:32}],113:[function(e,t,r){var i=e("stream").Readable;var n=e("inherits");var a=/^.*\.(\w+)$/;var s=e("typedarray-to-buffer");function o(e,t){var r=this;if(!(this instanceof o)){return new o(e,t)}t=t||{};i.call(this,t);this._offset=0;this._ready=false;this._file=e;this._size=e.size;this._chunkSize=t.chunkSize||Math.max(this._size/1e3,200*1024);this.reader=new FileReader;this._generateHeaderBlocks(e,t,function(e,t){if(e){return r.emit("error",e)}if(Array.isArray(t)){t.forEach(function(e){r.push(e)})}r._ready=true;r.emit("_ready")})}n(o,i);t.exports=o;o.prototype._generateHeaderBlocks=function(e,t,r){r(null,[])};o.prototype._read=function(){if(!this._ready){this.once("_ready",this._read.bind(this));return}var e=this;var t=this.reader;var r=this._offset;var i=this._offset+this._chunkSize;if(i>this._size)i=this._size;if(r===this._size){this.destroy();this.push(null); -return}t.onload=function(){e._offset=i;e.push(s(t.result))};t.onerror=function(){e.emit("error",t.error)};t.readAsArrayBuffer(this._file.slice(r,i))};o.prototype.destroy=function(){this._file=null;if(this.reader){this.reader.onload=null;this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}},{inherits:129,stream:67,"typedarray-to-buffer":111}],114:[function(e,t,r){t.exports=function i(e,t){t=typeof t=="number"?t:Infinity;return r(e,1);function r(e,i){return e.reduce(function(e,n){if(Array.isArray(n)&&i=r){break}r=i;n=t[a]}return n}},{}],121:[function(e,t,r){r=t.exports=e("./debug");r.log=a;r.formatArgs=n;r.save=s;r.load=o;r.useColors=i;r.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:f();r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function i(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}r.formatters.j=function(e){return JSON.stringify(e)};function n(){var e=arguments;var t=this.useColors;e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+r.humanize(this.diff);if(!t)return e;var i="color: "+this.color;e=[e[0],i,"color: inherit"].concat(Array.prototype.slice.call(e,1));var n=0;var a=0;e[0].replace(/%[a-z%]/g,function(e){if("%%"===e)return;n++;if("%c"===e){a=n}});e.splice(a,0,i);return e}function a(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function s(e){try{if(null==e){r.storage.removeItem("debug")}else{r.storage.debug=e}}catch(t){}}function o(){var e;try{e=r.storage.debug}catch(t){}return e}r.enable(o());function f(){try{return window.localStorage}catch(e){}}},{"./debug":122}],122:[function(e,t,r){r=t.exports=s;r.coerce=l;r.disable=f;r.enable=o;r.enabled=u;r.humanize=e("ms");r.names=[];r.skips=[];r.formatters={};var i=0;var n;function a(){return r.colors[i++%r.colors.length]}function s(e){function t(){}t.enabled=false;function i(){var e=i;var t=+new Date;var s=t-(n||t);e.diff=s;e.prev=n;e.curr=t;n=t;if(null==e.useColors)e.useColors=r.useColors();if(null==e.color&&e.useColors)e.color=a();var o=Array.prototype.slice.call(arguments);o[0]=r.coerce(o[0]);if("string"!==typeof o[0]){o=["%o"].concat(o)}var f=0;o[0]=o[0].replace(/%([a-z%])/g,function(t,i){if(t==="%%")return t;f++;var n=r.formatters[i];if("function"===typeof n){var a=o[f];t=n.call(e,a);o.splice(f,1);f--}return t});if("function"===typeof r.formatArgs){o=r.formatArgs.apply(e,o)}var u=i.log||r.log||console.log.bind(console);u.apply(e,o)}i.enabled=true;var s=r.enabled(e)?i:t;s.namespace=e;return s}function o(e){r.save(e);var t=(e||"").split(/[\s,]+/);var i=t.length;for(var n=0;n1e4)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);var f=(t[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return r*o;case"days":case"day":case"d":return r*s;case"hours":case"hour":case"hrs":case"hr":case"h":return r*a;case"minutes":case"minute":case"mins":case"min":case"m":return r*n;case"seconds":case"second":case"secs":case"sec":case"s":return r*i;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r}}function u(e){if(e>=s)return Math.round(e/s)+"d";if(e>=a)return Math.round(e/a)+"h";if(e>=n)return Math.round(e/n)+"m";if(e>=i)return Math.round(e/i)+"s";return e+"ms"}function l(e){return c(e,s,"day")||c(e,a,"hour")||c(e,n,"minute")||c(e,i,"second")||e+" ms"}function c(e,t,r){if(e=Math.pow(2,e)){return i(e,t)}else return s};i.rack=function(e,t,r){var n=function(n){var s=0;do{if(s++>10){if(r)e+=r;else throw new Error("too many ID collisions, use more bits")}var o=i(e,t)}while(Object.hasOwnProperty.call(a,o));a[o]=n;return o};var a=n.hats={};n.get=function(e){return n.hats[e]};n.set=function(e,t){n.hats[e]=t;return n};n.bits=e||128;n.base=t||16;return n}},{}],128:[function(e,t,r){(function(e){t.exports=r;function r(e){if(!(this instanceof r))return new r(e);this.store=e;if(!this.store||!this.store.get||!this.store.put){throw new Error("First argument must be abstract-chunk-store compliant")}this.mem=[]}r.prototype.put=function(e,t,r){var i=this;i.mem[e]=t;i.store.put(e,t,function(t){i.mem[e]=null;if(r)r(t)})};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);var n=t&&t.offset||0;var a=t&&t.length&&n+t.length;var s=this.mem[e];if(s)return i(r,null,t?s.slice(n,a):s);this.store.get(e,t,r)};r.prototype.close=function(e){this.store.close(e)};r.prototype.destroy=function(e){this.store.destroy(e)};function i(t,r,i){e.nextTick(function(){if(t)t(r,i)})}}).call(this,e("_process"))},{_process:49}],129:[function(e,t,r){if(typeof Object.create==="function"){t.exports=function i(e,t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}else{t.exports=function n(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype;e.prototype=new r;e.prototype.constructor=e}}},{}],130:[function(e,t,r){t.exports=s;var i=e("inherits");var n=e("stream");var a=typeof window!=="undefined"&&window.MediaSource;i(s,n.Writable);function s(e,t){var r=this;if(!(r instanceof s))return new s(e,t);n.Writable.call(r,t);if(!a)throw new Error("web browser lacks MediaSource support");if(!t)t={};r._elem=e;r._mediaSource=new a;r._sourceBuffer=null;r._cb=null;r._type=t.type||o(t.extname);if(!r._type)throw new Error("missing `opts.type` or `opts.extname` options");r._elem.src=window.URL.createObjectURL(r._mediaSource);r._mediaSource.addEventListener("sourceopen",function(){if(a.isTypeSupported(r._type)){r._sourceBuffer=r._mediaSource.addSourceBuffer(r._type);r._sourceBuffer.addEventListener("updateend",r._flow.bind(r));r._flow()}else{r._mediaSource.endOfStream("decode")}});r.on("finish",function(){r._mediaSource.endOfStream()})}s.prototype._write=function(e,t,r){var i=this;if(!i._sourceBuffer){i._cb=function(n){if(n)return r(n);i._write(e,t,r)};return}if(i._sourceBuffer.updating){return r(new Error("Cannot append buffer while source buffer updating"))}i._sourceBuffer.appendBuffer(e);i._cb=r};s.prototype._flow=function(){var e=this;if(e._cb){e._cb(null)}};function o(e){if(!e)return null;if(e[0]!==".")e="."+e;return{".m4a":'audio/mp4; codecs="mp4a.40.5"',".m4v":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".mp3":"audio/mpeg",".mp4":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".webm":'video/webm; codecs="vorbis, vp8"'}[e]}},{inherits:129,stream:67}],131:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(!(this instanceof r))return new r(e,t);if(!t)t={};this.chunkLength=Number(e);if(!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[];this.closed=false;this.length=Number(t.length)||Infinity;if(this.length!==Infinity){this.lastChunkLength=this.length%this.chunkLength||this.chunkLength;this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1}}r.prototype.put=function(e,t,r){if(this.closed)return i(r,new Error("Storage is closed"));var n=e===this.lastChunkIndex;if(n&&t.length!==this.lastChunkLength){return i(r,new Error("Last chunk length must be "+this.lastChunkLength))}if(!n&&t.length!==this.chunkLength){return i(r,new Error("Chunk length must be "+this.chunkLength))}this.chunks[e]=t;i(r,null)};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);if(this.closed)return i(r,new Error("Storage is closed"));var n=this.chunks[e];if(!n)return i(r,new Error("Chunk not found"));if(!t)return i(r,null,n);var a=t.offset||0;var s=t.length||n.length-a;i(r,null,n.slice(a,s+a))};r.prototype.close=r.prototype.destroy=function(e){if(this.closed)return i(e,new Error("Storage is closed"));this.closed=true;this.chunks=null;i(e,null)};function i(t,r,i){e.nextTick(function(){if(t)t(r,i)})}}).call(this,e("_process"))},{_process:49}],132:[function(e,t,r){(function(r){var i=e("path");var n=e("fs");function a(){this.types=Object.create(null);this.extensions=Object.create(null)}a.prototype.define=function(e){for(var t in e){var i=e[t];for(var n=0;n=0?n.split("&"):[];s.forEach(function(e){var r=e.split("=");if(r.length!==2)return;var i=r[0];var n=r[1];if(i==="dn")n=decodeURIComponent(n).replace(/\+/g," ");if(i==="tr"||i==="xs"||i==="as"||i==="ws"){n=decodeURIComponent(n)}if(i==="kt")n=decodeURIComponent(n).split("+");if(t[i]){if(Array.isArray(t[i])){t[i].push(n)}else{var a=t[i];t[i]=[a,n]}}else{t[i]=n}});var o;if(t.xt){var f=Array.isArray(t.xt)?t.xt:[t.xt];f.forEach(function(e){if(o=e.match(/^urn:btih:(.{40})/)){t.infoHash=new r(o[1],"hex").toString("hex")}else if(o=e.match(/^urn:btih:(.{32})/)){var n=i.decode(o[1]);t.infoHash=new r(n,"binary").toString("hex")}})}if(t.dn)t.name=t.dn;if(t.kt)t.keywords=t.kt;if(typeof t.tr==="string")t.announce=[t.tr];else if(Array.isArray(t.tr))t.announce=t.tr;else t.announce=[];a(t.announce);t.urlList=[];if(typeof t.as==="string"||Array.isArray(t.as)){t.urlList=t.urlList.concat(t.as)}if(typeof t.ws==="string"||Array.isArray(t.ws)){t.urlList=t.urlList.concat(t.ws)}return t}function o(e){e=n(e);if(e.infoHash)e.xt="urn:btih:"+e.infoHash;if(e.name)e.dn=e.name;if(e.keywords)e.kt=e.keywords;if(e.announce)e.tr=e.announce;if(e.urlList){e.ws=e.urlList;delete e.as}var t="magnet:?";Object.keys(e).filter(function(e){return e.length===2}).forEach(function(r,i){var n=Array.isArray(e[r])?e[r]:[e[r]];n.forEach(function(e,n){if((i>0||n>0)&&(r!=="kt"||n===0))t+="&";if(r==="dn")e=encodeURIComponent(e).replace(/%20/g,"+");if(r==="tr"||r==="xs"||r==="as"||r==="ws"){e=encodeURIComponent(e)}if(r==="kt")e=encodeURIComponent(e);if(r==="kt"&&n>0)t+="+"+e;else t+=r+"="+e})});return t}}).call(this,e("buffer").Buffer)},{buffer:39,"thirty-two":141,uniq:168,xtend:181}],141:[function(e,t,r){var i=e("./thirty-two");r.encode=i.encode;r.decode=i.decode},{"./thirty-two":142}],142:[function(e,t,r){(function(e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";var i=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,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,255,255,255,255,255,255,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,255,255,255,255,255];function n(e){var t=Math.floor(e.length/5);return e.length%5==0?t:t+1}r.encode=function(r){var i=0;var a=0;var s=0;var o=0;var f=new e(n(r)*8);if(!e.isBuffer(r)){r=new e(r)}while(i3){o=u&255>>s;s=(s+5)%8;o=o<>8-s;i++}else{o=u>>8-(s+5)&31;s=(s+5)%8;if(s==0)i++}f[a]=t.charCodeAt(o);a++}for(i=a;i>>r;o[s]=a;s++;a=255&n<<8-r}}else{throw new Error("Invalid input - it is not base32 encoded string")}}return o.slice(0,s)}}).call(this,e("buffer").Buffer)},{buffer:39}],143:[function(e,t,r){(function(r){t.exports=o;t.exports.decode=o;t.exports.encode=f;var i=e("bencode");var n=e("path");var a=e("simple-sha1");var s=e("uniq");function o(e){if(r.isBuffer(e)){e=i.decode(e)}c(e.info,"info");c(e.info["name.utf-8"]||e.info.name,"info.name");c(e.info["piece length"],"info['piece length']");c(e.info.pieces,"info.pieces");if(e.info.files){e.info.files.forEach(function(e){c(typeof e.length==="number","info.files[0].length");c(e["path.utf-8"]||e.path,"info.files[0].path")})}else{c(typeof e.info.length==="number","info.length")}var t={};t.info=e.info;t.infoBuffer=i.encode(e.info);t.infoHash=a.sync(t.infoBuffer);t.name=(e.info["name.utf-8"]||e.info.name).toString();if(e.info.private!==undefined)t.private=!!e.info.private;if(e["creation date"])t.created=new Date(e["creation date"]*1e3);if(e["created by"])t.createdBy=e["created by"].toString();if(r.isBuffer(e.comment))t.comment=e.comment.toString();t.announce=[];if(e["announce-list"]&&e["announce-list"].length){e["announce-list"].forEach(function(e){e.forEach(function(e){t.announce.push(e.toString())})})}else if(e.announce){t.announce.push(e.announce.toString())}s(t.announce);if(r.isBuffer(e["url-list"])){e["url-list"]=e["url-list"].length>0?[e["url-list"]]:[]}t.urlList=(e["url-list"]||[]).map(function(e){return e.toString()});var o=e.info.files||[e.info];t.files=o.map(function(e,r){var i=[].concat(t.name,e["path.utf-8"]||e.path||[]).map(function(e){return e.toString()});return{path:n.join.apply(null,[n.sep].concat(i)).slice(1),name:i[i.length-1],length:e.length,offset:o.slice(0,r).reduce(u,0)}});t.length=o.reduce(u,0);var f=t.files[t.files.length-1];t.pieceLength=e.info["piece length"];t.lastPieceLength=(f.offset+f.length)%t.pieceLength||t.pieceLength;t.pieces=l(e.info.pieces);return t}function f(e){var t={info:e.info};t["announce-list"]=e.announce.map(function(e){if(!t.announce)t.announce=e;e=new r(e,"utf8");return[e]});if(e.created){t["creation date"]=e.created.getTime()/1e3|0}if(e.urlList){t["url-list"]=e.urlList}return i.encode(t)}function u(e,t){return e+t.length}function l(e){var t=[];for(var r=0;r0;return l(n,s,o,function(e){if(!r)r=e;if(e)i.forEach(c);if(s)return;i.forEach(c);t(r)})});return e.reduce(p)};t.exports=d},{"end-of-stream":124,fs:37,once:151}],150:[function(e,t,r){arguments[4][22][0].apply(r,arguments)},{dup:22}],151:[function(e,t,r){arguments[4][29][0].apply(r,arguments)},{dup:29,wrappy:150}],152:[function(e,t,r){var i=function(e){var t=0;return function(){if(t===e.length)return null;var r=e.length-t;var i=Math.random()*r|0;var n=e[t+i];var a=e[t];e[t]=n;e[t+i]=a;t++;return n}};t.exports=i},{}],153:[function(e,t,r){t.exports=function(e,t){var r=true;var i=t.indexOf("=");if(-1==i)return-2;var n=t.slice(i+1).split(",").map(function(t){var t=t.split("-"),i=parseInt(t[0],10),n=parseInt(t[1],10);if(isNaN(i)){i=e-n;n=e-1}else if(isNaN(n)){n=e-1}if(n>e-1)n=e-1;if(isNaN(i)||isNaN(n)||i>n||i<0)r=false;return{start:i,end:n}});n.type=t.slice(0,i);return r?n:-1}},{}],154:[function(e,t,r){t.exports=n;t.exports.filter=a;var i=e("events").EventEmitter;function n(e,t,r){if(!Array.isArray(r))r=[r];var i=[];r.forEach(function(r){var n=function(){var e=[].slice.call(arguments);e.unshift(r);t.emit.apply(t,e)};i.push(n);e.on(r,n)});return function n(){r.forEach(function(t,r){e.removeListener(t,i[r])})}}function a(e,t){var r=new i;n(e,r,t);return r}},{events:43}],155:[function(e,t,r){var i=e("dezalgo");t.exports=function(e,t){if(t)t=i(t);var r,n,a;if(Array.isArray(e)){r=[];n=e.length}else{a=Object.keys(e);r={};n=a.length}function s(e,i,a){r[e]=a;if(--n===0||i){if(t)t(i,r);t=null}}if(!n){if(t)t(null,r);t=null}else if(a){a.forEach(function(t){e[t](s.bind(undefined,t))})}else{e.forEach(function(e,t){e(s.bind(undefined,t))})}}},{dezalgo:156}],156:[function(e,t,r){arguments[4][19][0].apply(r,arguments)},{asap:157,dup:19,wrappy:159}],157:[function(e,t,r){arguments[4][20][0].apply(r,arguments)},{"./raw":158,dup:20}],158:[function(e,t,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],159:[function(e,t,r){arguments[4][22][0].apply(r,arguments)},{dup:22}],160:[function(e,t,r){(function(r){t.exports=u;var i=e("xtend");var n=e("http");var a=e("https");var s=e("once");var o=e("unzip-response");var f=e("url");function u(e,t){e=typeof e==="string"?{url:e}:i(e);t=s(t);if(e.url)l(e);if(e.headers==null)e.headers={};if(e.maxRedirects==null)e.maxRedirects=10;var r=e.body;e.body=undefined;if(r&&!e.method)e.method="POST";var f=Object.keys(e.headers).some(function(e){return e.toLowerCase()==="accept-encoding"});if(!f)e.headers["accept-encoding"]="gzip, deflate";var c=e.protocol==="https:"?a:n;var p=c.request(e,function(r){if(r.statusCode>=300&&r.statusCode<400&&"location"in r.headers){e.url=r.headers.location;l(e);r.resume();e.maxRedirects-=1;if(e.maxRedirects>0)u(e,t);else t(new Error("too many redirects"));return}t(null,typeof o==="function"?o(r):r)});p.on("error",t);p.end(r);return p}t.exports.concat=function(e,t){return u(e,function(e,i){if(e)return t(e);var n=[];i.on("data",function(e){n.push(e)});i.on("end",function(){t(null,r.concat(n),i)})})};["get","post","put","patch","head","delete"].forEach(function(e){t.exports[e]=function(t,r){if(typeof t==="string")t={url:t};t.method=e.toUpperCase();return u(t,r)}});function l(e){var t=f.parse(e.url);if(t.hostname)e.hostname=t.hostname;if(t.port)e.port=t.port;if(t.protocol)e.protocol=t.protocol;e.path=t.path;delete e.url}}).call(this,e("buffer").Buffer)},{buffer:39,http:68,https:44,once:162,"unzip-response":38,url:78,xtend:181}],161:[function(e,t,r){arguments[4][22][0].apply(r,arguments)},{dup:22}],162:[function(e,t,r){arguments[4][29][0].apply(r,arguments)},{dup:29,wrappy:161}],163:[function(e,t,r){var i=e("rusha");var n=new i;var a=window.crypto||window.msCrypto||{};var s=a.subtle||a.webkitSubtle;var o=n.digest.bind(n);try{s.digest({name:"sha-1"},new Uint8Array).catch(function(){s=false})}catch(f){s=false}function u(e,t){if(!s){setTimeout(t,0,o(e));return}if(typeof e==="string"){e=l(e)}s.digest({name:"sha-1"},e).then(function r(e){t(c(new Uint8Array(e)))},function i(r){t(o(e))})}function l(e){var t=e.length;var r=new Uint8Array(t);for(var i=0;i>>4).toString(16));r.push((n&15).toString(16))}return r.join("")}t.exports=u;t.exports.sync=o},{rusha:164}],164:[function(e,t,r){(function(e){(function(){var r={getDataType:function(t){if(typeof t==="string"){return"string"}if(t instanceof Array){return"array"}if(typeof e!=="undefined"&&e.Buffer&&e.Buffer.isBuffer(t)){return"buffer"}if(t instanceof ArrayBuffer){return"arraybuffer"}if(t.buffer instanceof ArrayBuffer){return"view"}if(t instanceof Blob){return"blob"}throw new Error("Unsupported data type.")}};function i(e){"use strict";var t={fill:0};var a=function(e){for(e+=9;e%64>0;e+=1);return e};var s=function(e,t){for(var r=t>>2;r>2]|=128<<24-(t%4<<3);e[((t>>2)+2&~15)+14]=r>>29;e[((t>>2)+2&~15)+15]=r<<3};var f=function(e,t,r,i,n){var a=this,s,o=n%4,f=i%4,u=i-f;if(u>0){switch(o){case 0:e[n+3|0]=a.charCodeAt(r);case 1:e[n+2|0]=a.charCodeAt(r+1);case 2:e[n+1|0]=a.charCodeAt(r+2);case 3:e[n|0]=a.charCodeAt(r+3)}}for(s=o;s>2]=a.charCodeAt(r+s)<<24|a.charCodeAt(r+s+1)<<16|a.charCodeAt(r+s+2)<<8|a.charCodeAt(r+s+3)}switch(f){case 3:e[n+u+1|0]=a.charCodeAt(r+u+2);case 2:e[n+u+2|0]=a.charCodeAt(r+u+1);case 1:e[n+u+3|0]=a.charCodeAt(r+u)}};var u=function(e,t,r,i,n){var a=this,s,o=n%4,f=i%4,u=i-f;if(u>0){switch(o){case 0:e[n+3|0]=a[r];case 1:e[n+2|0]=a[r+1];case 2:e[n+1|0]=a[r+2];case 3:e[n|0]=a[r+3]}}for(s=4-o;s>2]=a[r+s]<<24|a[r+s+1]<<16|a[r+s+2]<<8|a[r+s+3]}switch(f){case 3:e[n+u+1|0]=a[r+u+2];case 2:e[n+u+2|0]=a[r+u+1];case 1:e[n+u+3|0]=a[r+u]}};var l=function(e,t,r,i,a){var s=this,o,f=a%4,u=i%4,l=i-u;var c=new Uint8Array(n.readAsArrayBuffer(s.slice(r,r+i)));if(l>0){switch(f){case 0:e[a+3|0]=c[0];case 1:e[a+2|0]=c[1];case 2:e[a+1|0]=c[2];case 3:e[a|0]=c[3]}}for(o=4-f;o>2]=c[o]<<24|c[o+1]<<16|c[o+2]<<8|c[o+3]}switch(u){case 3:e[a+l+1|0]=c[l+2];case 2:e[a+l+2|0]=c[l+1];case 1:e[a+l+3|0]=c[l]}};var c=function(e){switch(r.getDataType(e)){case"string":return f.bind(e);case"array":return u.bind(e);case"buffer":return u.bind(e);case"arraybuffer":return u.bind(new Uint8Array(e));case"view":return u.bind(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));case"blob":return l.bind(e)}};var p=function(e,t){switch(r.getDataType(e)){case"string":return e.slice(t);case"array":return e.slice(t);case"buffer":return e.slice(t);case"arraybuffer":return e.slice(t);case"view":return e.buffer.slice(t)}};var d=function(e){var t,r,i="0123456789abcdef",n=[],a=new Uint8Array(e);for(t=0;t>4&15)+i.charAt(r>>0&15)}return n.join("")};var h=function(e){var t;if(e<=65536)return 65536;if(e<16777216){for(t=1;t0){throw new Error("Chunk size must be a multiple of 128 bit")}t.maxChunkLen=e;t.padMaxChunkLen=a(e);t.heap=new ArrayBuffer(h(t.padMaxChunkLen+320+20));t.h32=new Int32Array(t.heap);t.h8=new Int8Array(t.heap);t.core=new i._core({Int32Array:Int32Array,DataView:DataView},{},t.heap);t.buffer=null};m(e||64*1024);var v=function(e,t){var r=new Int32Array(e,t+320,5);r[0]=1732584193;r[1]=-271733879;r[2]=-1732584194;r[3]=271733878;r[4]=-1009589776};var g=function(e,r){var i=a(e);var n=new Int32Array(t.heap,0,i>>2);s(n,e);o(n,e,r);return i};var y=function(e,r,i){c(e)(t.h8,t.h32,r,i,0)};var _=function(e,r,i,n,a){var s=i;if(a){s=g(i,n)}y(e,r,i);t.core.hash(s,t.padMaxChunkLen)};var b=function(e,t){var r=new Int32Array(e,t+320,5);var i=new Int32Array(5);var n=new DataView(i.buffer);n.setInt32(0,r[0],false);n.setInt32(4,r[1],false);n.setInt32(8,r[2],false);n.setInt32(12,r[3],false);n.setInt32(16,r[4],false);return i};var w=this.rawDigest=function(e){var r=e.byteLength||e.length||e.size||0;v(t.heap,t.padMaxChunkLen);var i=0,n=t.maxChunkLen,a;for(i=0;r>i+n;i+=n){_(e,i,n,r,false)}_(e,i,r-i,r,true);return b(t.heap,t.padMaxChunkLen)};this.digest=this.digestFromString=this.digestFromBuffer=this.digestFromArrayBuffer=function(e){return d(w(e).buffer)}}i._core=function s(e,t,r){"use asm";var i=new e.Int32Array(r);function n(e,t){e=e|0;t=t|0;var r=0,n=0,a=0,s=0,o=0,f=0,u=0,l=0,c=0,p=0,d=0,h=0,m=0,v=0;a=i[t+320>>2]|0;o=i[t+324>>2]|0;u=i[t+328>>2]|0;c=i[t+332>>2]|0;d=i[t+336>>2]|0;for(r=0;(r|0)<(e|0);r=r+64|0){s=a;f=o;l=u;p=c;h=d;for(n=0;(n|0)<64;n=n+4|0){v=i[r+n>>2]|0;m=((a<<5|a>>>27)+(o&u|~o&c)|0)+((v+d|0)+1518500249|0)|0;d=c;c=u;u=o<<30|o>>>2;o=a;a=m;i[e+n>>2]=v}for(n=e+64|0;(n|0)<(e+80|0);n=n+4|0){v=(i[n-12>>2]^i[n-32>>2]^i[n-56>>2]^i[n-64>>2])<<1|(i[n-12>>2]^i[n-32>>2]^i[n-56>>2]^i[n-64>>2])>>>31;m=((a<<5|a>>>27)+(o&u|~o&c)|0)+((v+d|0)+1518500249|0)|0;d=c;c=u;u=o<<30|o>>>2;o=a;a=m;i[n>>2]=v}for(n=e+80|0;(n|0)<(e+160|0);n=n+4|0){v=(i[n-12>>2]^i[n-32>>2]^i[n-56>>2]^i[n-64>>2])<<1|(i[n-12>>2]^i[n-32>>2]^i[n-56>>2]^i[n-64>>2])>>>31;m=((a<<5|a>>>27)+(o^u^c)|0)+((v+d|0)+1859775393|0)|0;d=c;c=u;u=o<<30|o>>>2;o=a;a=m;i[n>>2]=v}for(n=e+160|0;(n|0)<(e+240|0);n=n+4|0){v=(i[n-12>>2]^i[n-32>>2]^i[n-56>>2]^i[n-64>>2])<<1|(i[n-12>>2]^i[n-32>>2]^i[n-56>>2]^i[n-64>>2])>>>31;m=((a<<5|a>>>27)+(o&u|o&c|u&c)|0)+((v+d|0)-1894007588|0)|0;d=c;c=u;u=o<<30|o>>>2;o=a;a=m;i[n>>2]=v}for(n=e+240|0;(n|0)<(e+320|0);n=n+4|0){v=(i[n-12>>2]^i[n-32>>2]^i[n-56>>2]^i[n-64>>2])<<1|(i[n-12>>2]^i[n-32>>2]^i[n-56>>2]^i[n-64>>2])>>>31;m=((a<<5|a>>>27)+(o^u^c)|0)+((v+d|0)-899497514|0)|0;d=c;c=u;u=o<<30|o>>>2;o=a;a=m;i[n>>2]=v}a=a+s|0;o=o+f|0;u=u+l|0;c=c+p|0;d=d+h|0}i[t+320>>2]=a;i[t+324>>2]=o;i[t+328>>2]=u;i[t+332>>2]=c;i[t+336>>2]=d}return{hash:n}};if(typeof t!=="undefined"){t.exports=i}else if(typeof window!=="undefined"){window.Rusha=i}if(typeof FileReaderSync!=="undefined"){var n=new FileReaderSync,a=new i(4*1024*1024);self.onmessage=function o(e){var t,r=e.data.data;try{t=a.digest(r);self.postMessage({id:e.data.id,hash:t})}catch(i){self.postMessage({id:e.data.id,error:i.name})}}}})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],165:[function(e,t,r){var i=1;var n=65535;var a=4;var s=function(){i=i+1&n};var o=setInterval(s,1e3/a|0);if(o.unref)o.unref();t.exports=function(e){ -var t=a*(e||5);var r=[0];var s=1;var o=i-1&n;return function(e){var f=i-o&n;if(f>t)f=t;o=i;while(f--){if(s===t)s=0;r[s]=r[s===0?t-1:s-1];s++}if(e)r[s-1]+=e;var u=r[s-1];var l=r.lengthf){return this.emit("warning",new Error("Peer gave maliciously large metadata size"))}this._metadataSize=e.metadata_size;this._numPieces=Math.ceil(this._metadataSize/l);this._remainingRejects=this._numPieces*2;if(this._fetching){this._requestPieces()}};t.prototype.onMessage=function(e){var t,r;try{var n=e.toString();var a=n.indexOf("ee")+2;t=i.decode(n.substring(0,a));r=e.slice(a)}catch(s){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,r,t.total_size);break;case 2:this._onReject(t.piece);break}};t.prototype.fetch=function(){if(this._metadataComplete){return}this._fetching=true;if(this._metadataSize){this._requestPieces()}};t.prototype.cancel=function(){this._fetching=false};t.prototype.setMetadata=function(e){if(this._metadataComplete)return true;try{var t=i.decode(e).info;if(t){e=i.encode(t)}}catch(r){}if(this._infoHashHex&&this._infoHashHex!==o.sync(e)){return false}this.cancel();this.metadata=e;this._metadataComplete=true;this._metadataSize=this.metadata.length;this._wire.extendedHandshake.metadata_size=this._metadataSize;this.emit("metadata",i.encode({info:i.decode(this.metadata)}));return true};t.prototype._send=function(e,t){var n=i.encode(e);if(r.isBuffer(t)){n=r.concat([n,t])}this._wire.extended("ut_metadata",n)};t.prototype._request=function(e){this._send({msg_type:0,piece:e})};t.prototype._data=function(e,t,r){var i={msg_type:1,piece:e};if(typeof r==="number"){i.total_size=r}this._send(i,t)};t.prototype._reject=function(e){this._send({msg_type:2,piece:e})};t.prototype._onRequest=function(e){if(!this._metadataComplete){this._reject(e);return}var t=e*l;var r=t+l;if(r>this._metadataSize){r=this._metadataSize}var i=this.metadata.slice(t,r);this._data(e,i,this._metadataSize)};t.prototype._onData=function(e,t,r){if(t.length>l){return}t.copy(this.metadata,e*l);this._bitfield.set(e);this._checkDone()};t.prototype._onReject=function(e){if(this._remainingRejects>0&&this._fetching){this._request(e);this._remainingRejects-=1}else{this.emit("warning",new Error('Peer sent "reject" too much'))}};t.prototype._requestPieces=function(){this.metadata=new r(this._metadataSize);for(var e=0;e0){this._requestPieces()}else{this.emit("warning",new Error("Peer sent invalid metadata"))}};return t}}).call(this,e("buffer").Buffer)},{bencode:170,bitfield:9,buffer:39,events:43,inherits:129,"simple-sha1":163}],170:[function(e,t,r){arguments[4][15][0].apply(r,arguments)},{"./lib/decode":171,"./lib/encode":173,dup:15}],171:[function(e,t,r){arguments[4][16][0].apply(r,arguments)},{"./dict":172,buffer:39,dup:16}],172:[function(e,t,r){arguments[4][17][0].apply(r,arguments)},{dup:17}],173:[function(e,t,r){arguments[4][18][0].apply(r,arguments)},{buffer:39,dup:18}],174:[function(e,t,r){var i=function(e,t,r){this._byteOffset=t||0;if(e instanceof ArrayBuffer){this.buffer=e}else if(typeof e=="object"){this.dataView=e;if(t){this._byteOffset+=t}}else{this.buffer=new ArrayBuffer(e||0)}this.position=0;this.endianness=r==null?i.LITTLE_ENDIAN:r};t.exports=i;i.prototype={};i.prototype.save=function(e){var t=new Blob([this.buffer]);var r=window.webkitURL||window.URL;if(r&&r.createObjectURL){var i=r.createObjectURL(t);var n=document.createElement("a");n.setAttribute("href",i);n.setAttribute("download",e);n.click();r.revokeObjectURL(i)}else{throw"DataStream.save: Can't create object URL."}};i.BIG_ENDIAN=false;i.LITTLE_ENDIAN=true;i.prototype._dynamicSize=true;Object.defineProperty(i.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(e){if(!e){this._trimAlloc()}this._dynamicSize=e}});i.prototype._byteLength=0;Object.defineProperty(i.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}});Object.defineProperty(i.prototype,"buffer",{get:function(){this._trimAlloc();return this._buffer},set:function(e){this._buffer=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(i.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(i.prototype,"dataView",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset;this._buffer=e.buffer;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._byteOffset+e.byteLength}});i.prototype._realloc=function(e){if(!this._dynamicSize){return}var t=this._byteOffset+this.position+e;var r=this._buffer.byteLength;if(t<=r){if(t>this._byteLength){this._byteLength=t}return}if(r<1){r=1}while(t>r){r*=2}var i=new ArrayBuffer(r);var n=new Uint8Array(this._buffer);var a=new Uint8Array(i,0,n.length);a.set(n);this.buffer=i;this._byteLength=t};i.prototype._trimAlloc=function(){if(this._byteLength==this._buffer.byteLength){return}var e=new ArrayBuffer(this._byteLength);var t=new Uint8Array(e);var r=new Uint8Array(this._buffer,0,t.length);t.set(r);this.buffer=e};i.prototype.shift=function(e){var t=new ArrayBuffer(this._byteLength-e);var r=new Uint8Array(t);var i=new Uint8Array(this._buffer,e,r.length);r.set(i);this.buffer=t;this.position-=e};i.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t};i.prototype.isEof=function(){return this.position>=this._byteLength};i.prototype.mapInt32Array=function(e,t){this._realloc(e*4);var r=new Int32Array(this._buffer,this.byteOffset+this.position,e);i.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};i.prototype.mapInt16Array=function(e,t){this._realloc(e*2);var r=new Int16Array(this._buffer,this.byteOffset+this.position,e);i.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};i.prototype.mapInt8Array=function(e){this._realloc(e*1);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};i.prototype.mapUint32Array=function(e,t){this._realloc(e*4);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,e);i.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};i.prototype.mapUint16Array=function(e,t){this._realloc(e*2);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,e);i.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};i.prototype.mapUint8Array=function(e){this._realloc(e*1);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};i.prototype.mapFloat64Array=function(e,t){this._realloc(e*8);var r=new Float64Array(this._buffer,this.byteOffset+this.position,e);i.arrayToNative(r,t==null?this.endianness:t);this.position+=e*8;return r};i.prototype.mapFloat32Array=function(e,t){this._realloc(e*4);var r=new Float32Array(this._buffer,this.byteOffset+this.position,e);i.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};i.prototype.readInt32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Int32Array(e);i.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);i.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};i.prototype.readInt16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Int16Array(e);i.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);i.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};i.prototype.readInt8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Int8Array(e);i.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};i.prototype.readUint32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Uint32Array(e);i.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);i.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};i.prototype.readUint16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Uint16Array(e);i.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);i.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};i.prototype.readUint8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Uint8Array(e);i.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};i.prototype.readFloat64Array=function(e,t){e=e==null?this.byteLength-this.position/8:e;var r=new Float64Array(e);i.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);i.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};i.prototype.readFloat32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Float32Array(e);i.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);i.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};i.prototype.writeInt32Array=function(e,t){this._realloc(e.length*4);if(e instanceof Int32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0){i.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength);this.mapInt32Array(e.length,t)}else{for(var r=0;r0;i.memcpy=function(e,t,r,i,n){var a=new Uint8Array(e,t,n);var s=new Uint8Array(r,i,n);a.set(s)};i.arrayToNative=function(e,t){if(t==this.endianness){return e}else{return this.flipArrayEndianness(e)}};i.nativeToEndian=function(e,t){if(this.endianness==t){return e}else{return this.flipArrayEndianness(e)}};i.flipArrayEndianness=function(e){var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(var r=0;rn;i--,n++){var a=t[n];t[n]=t[i];t[i]=a}}return e};i.prototype.failurePosition=0;i.prototype.readStruct=function(e){var t={},r,i,n;var a=this.position;for(var s=0;s>16);this.writeUint8((e&65280)>>8);this.writeUint8(e&255)};i.prototype.adjustUint32=function(e,t){var r=this.position;this.seek(e);this.writeUint32(t);this.seek(r)}},{}],175:[function(e,t,r){var n=e("./DataStream");var a=e("./descriptor");var s=e("./log");var o={ERR_NOT_ENOUGH_DATA:0,OK:1,boxCodes:["mdat","avcC","hvcC","ftyp","payl","vmhd","smhd","hmhd","dref","elst"],fullBoxCodes:["mvhd","tkhd","mdhd","hdlr","smhd","hmhd","nhmd","url ","urn ","ctts","cslg","stco","co64","stsc","stss","stsz","stz2","stts","stsh","mehd","trex","mfhd","tfhd","trun","tfdt","esds","subs","txtC"],containerBoxCodes:[["moov",["trak"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl"],["mvex",["trex"]],["moof",["traf"]],["traf",["trun"]],["vttc"],["tref"]],sampleEntryCodes:[{prefix:"Visual",types:["mp4v","avc1","avc2","avc3","avc4","avcp","drac","encv","mjp2","mvc1","mvc2","resv","s263","svc1","vc-1","hvc1","hev1"]},{prefix:"Audio",types:["mp4a","ac-3","alac","dra1","dtsc","dtse",,"dtsh","dtsl","ec-3","enca","g719","g726","m4ae","mlpa","raw ","samr","sawb","sawp","sevc","sqcp","ssmv","twos"]},{prefix:"Hint",types:["fdp ","m2ts","pm2t","prtp","rm2t","rrtp","rsrp","rtp ","sm2t","srtp"]},{prefix:"Metadata",types:["metx","mett","urim"]},{prefix:"Subtitle",types:["stpp","wvtt","sbtt","tx3g","stxt"]}],trackReferenceTypes:["scal"],initialize:function(){var e,t;var r;o.FullBox.prototype=new o.Box;o.ContainerBox.prototype=new o.Box;o.stsdBox.prototype=new o.FullBox;o.SampleEntry.prototype=new o.FullBox;o.TrackReferenceTypeBox.prototype=new o.Box;r=o.boxCodes.length;for(e=0;ee.byteLength){e.seek(i);s.w("BoxParser",'Not enough data in stream to parse the entire "'+f+'" box');return{code:o.ERR_NOT_ENOUGH_DATA,type:f,size:a,hdr_size:n}}if(o[f+"Box"]){r=new o[f+"Box"](a-n)}else{if(t){r=new o.SampleEntry(f,a-n)}else{r=new o.Box(f,a-n)}}r.hdr_size=n;r.start=i;r.fileStart=i+e.buffer.fileStart;r.parse(e);e.seek(i+a);return{code:o.OK,box:r,size:a}}};t.exports=o;o.initialize();o.Box.prototype.parse=function(e){ -if(this.type!="mdat"){this.data=e.readUint8Array(this.size)}else{e.seek(this.start+this.size+this.hdr_size)}};o.FullBox.prototype.parseFullHeader=function(e){this.version=e.readUint8();this.flags=e.readUint24();this.size-=4};o.ContainerBox.prototype.parse=function(e){var t;var r;var i;i=e.position;while(e.position=4){this.compatible_brands[t]=e.readString(4);this.size-=4;t++}};o.mvhdBox.prototype.parse=function(e){this.flags=0;this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.rate=e.readUint32();this.volume=e.readUint16()>>8;e.readUint16();e.readUint32Array(2);this.matrix=e.readUint32Array(9);e.readUint32Array(6);this.next_track_id=e.readUint32()};o.TKHD_FLAG_ENABLED=1;o.TKHD_FLAG_IN_MOVIE=2;o.TKHD_FLAG_IN_PREVIEW=4;o.tkhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint32()}e.readUint32Array(2);this.layer=e.readInt16();this.alternate_group=e.readInt16();this.volume=e.readInt16()>>8;e.readUint16();this.matrix=e.readInt32Array(9);this.width=e.readUint32();this.height=e.readUint32()};o.mdhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.language=e.readUint16();var t=[];t[0]=this.language>>10&31;t[1]=this.language>>5&31;t[2]=this.language&31;this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96);e.readUint16()};o.hdlrBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version===0){e.readUint32();this.handler=e.readString(4);e.readUint32Array(3);this.name=e.readCString()}else{this.data=e.readUint8Array(size)}};o.stsdBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);r=e.readUint32();for(i=1;i<=r;i++){t=o.parseOneBox(e,true);this.entries.push(t.box)}};o.avcCBox.prototype.parse=function(e){var t;var r;var i;this.configurationVersion=e.readUint8();this.AVCProfileIndication=e.readUint8();this.profile_compatibility=e.readUint8();this.AVCLevelIndication=e.readUint8();this.lengthSizeMinusOne=e.readUint8()&3;r=e.readUint8()&31;this.size-=6;this.SPS=new Array(r);for(t=0;t0){this.ext=e.readUint8Array(this.size)}};o.hvcCBox.prototype.parse=function(e){var t;var r;var i;var n;this.configurationVersion=e.readUint8();n=e.readUint8();this.general_profile_space=n>>6;this.general_tier_flag=(n&32)>>5;this.general_profile_idc=n&31;this.general_profile_compatibility=e.readUint32();this.general_constraint_indicator=e.readUint8Array(6);this.general_level_idc=e.readUint8();this.min_spatial_segmentation_idc=e.readUint16()&4095;this.parallelismType=e.readUint8()&3;this.chromaFormat=e.readUint8()&3;this.bitDepthLumaMinus8=e.readUint8()&7;this.bitDepthChromaMinus8=e.readUint8()&7;this.avgFrameRate=e.readUint16();n=e.readUint8();this.constantFrameRate=n>>6;this.numTemporalLayers=(n&13)>>3;this.temporalIdNested=(n&4)>>2;this.lengthSizeMinusOne=n&3;this.nalu_arrays=[];numOfArrays=e.readUint8();for(t=0;t>7;a.nalu_type=n&63;numNalus=e.readUint16();for(j=0;j>=1}t+=f(i,0);t+=".";if(this.hvcC.general_tier_flag===0){t+="L"}else{t+="H"}t+=this.hvcC.general_level_idc;var n=false;var a="";for(e=5;e>=0;e--){if(this.hvcC.general_constraint_indicator[e]||n){a="."+f(this.hvcC.general_constraint_indicator[e],0)+a;n=true}}t+=a}return t};o.mp4aBox.prototype.getCodec=function(){var e=o.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var t=this.esds.esd.getOTI();var r=this.esds.esd.getAudioConfig();return e+"."+f(t)+(r?"."+r:"")}else{return e}};o.esdsBox.prototype.parse=function(e){this.parseFullHeader(e);this.data=e.readUint8Array(this.size);this.size=0;var t=new a;this.esd=t.parseOneDescriptor(new n(this.data.buffer,0,n.BIG_ENDIAN))};o.txtCBox.prototype.parse=function(e){this.parseFullHeader(e);this.config=e.readCString()};o.cttsBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);t=e.readUint32();this.sample_counts=[];this.sample_offsets=[];if(this.version===0){for(r=0;rt&&this.flags&o.TFHD_FLAG_BASE_DATA_OFFSET){this.base_data_offset=e.readUint64();t+=8}else{this.base_data_offset=0}if(this.size>t&&this.flags&o.TFHD_FLAG_SAMPLE_DESC){this.default_sample_description_index=e.readUint32();t+=4}else{this.default_sample_description_index=0}if(this.size>t&&this.flags&o.TFHD_FLAG_SAMPLE_DUR){this.default_sample_duration=e.readUint32();t+=4}else{this.default_sample_duration=0}if(this.size>t&&this.flags&o.TFHD_FLAG_SAMPLE_SIZE){this.default_sample_size=e.readUint32();t+=4}else{this.default_sample_size=0}if(this.size>t&&this.flags&o.TFHD_FLAG_SAMPLE_FLAGS){this.default_sample_flags=e.readUint32();t+=4}else{this.default_sample_flags=0}};o.TRUN_FLAGS_DATA_OFFSET=1;o.TRUN_FLAGS_FIRST_FLAG=4;o.TRUN_FLAGS_DURATION=256;o.TRUN_FLAGS_SIZE=512;o.TRUN_FLAGS_FLAGS=1024;o.TRUN_FLAGS_CTS_OFFSET=2048;o.trunBox.prototype.parse=function(e){var t=0;this.parseFullHeader(e);this.sample_count=e.readUint32();t+=4;if(this.size>t&&this.flags&o.TRUN_FLAGS_DATA_OFFSET){this.data_offset=e.readInt32();t+=4}else{this.data_offset=0}if(this.size>t&&this.flags&o.TRUN_FLAGS_FIRST_FLAG){this.first_sample_flags=e.readUint32();t+=4}else{this.first_sample_flags=0}this.sample_duration=[];this.sample_size=[];this.sample_flags=[];this.sample_composition_time_offset=[];if(this.size>t){for(var r=0;r0){for(r=0;rn.MAX_SIZE){this.size+=8}s.d("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.position+(t||""));if(this.size>n.MAX_SIZE){e.writeUint32(1)}else{this.sizePosition=e.position;e.writeUint32(this.size)}e.writeString(this.type,null,4);if(this.size>n.MAX_SIZE){e.writeUint64(this.size)}};o.FullBox.prototype.writeHeader=function(e){this.size+=4;o.Box.prototype.writeHeader.call(this,e," v="+this.version+" f="+this.flags);e.writeUint8(this.version);e.writeUint24(this.flags)};o.Box.prototype.write=function(e){if(this.type==="mdat"){if(this.data){this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}}else{this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}};o.ContainerBox.prototype.write=function(e){this.size=0;this.writeHeader(e);for(var t=0;t>3}else{return null}};o.DecoderConfigDescriptor=function(e){o.Descriptor.call(this,t,e)};o.DecoderConfigDescriptor.prototype=new o.Descriptor;o.DecoderConfigDescriptor.prototype.parse=function(e){this.oti=e.readUint8();this.streamType=e.readUint8();this.bufferSize=e.readUint24();this.maxBitrate=e.readUint32();this.avgBitrate=e.readUint32();this.size-=13;this.parseRemainingDescriptors(e)};o.DecoderSpecificInfo=function(e){o.Descriptor.call(this,r,e)};o.DecoderSpecificInfo.prototype=new o.Descriptor;o.SLConfigDescriptor=function(e){o.Descriptor.call(this,n,e)};o.SLConfigDescriptor.prototype=new o.Descriptor;return this};t.exports=n},{"./log":178}],177:[function(e,t,r){var i=e("./box");var n=e("./DataStream");var a=e("./log");var s=function(e){this.stream=e;this.boxes=[];this.mdats=[];this.moofs=[];this.isProgressive=false;this.lastMoofIndex=0;this.lastBoxStartPosition=0;this.parsingMdat=null;this.moovStartFound=false;this.samplesDataSize=0;this.nextParsePosition=0};t.exports=s;s.prototype.mergeNextBuffer=function(){var e;if(this.stream.bufferIndex+1"+this.stream.buffer.byteLength+")");return true}else{return false}}else{return false}};s.prototype.parse=function(){var e;var t;var r;a.d("ISOFile","Starting parsing with buffer #"+this.stream.bufferIndex+" (fileStart: "+this.stream.buffer.fileStart+" - Length: "+this.stream.buffer.byteLength+") from position "+this.lastBoxStartPosition+" ("+(this.stream.buffer.fileStart+this.lastBoxStartPosition)+" in the file)");this.stream.seek(this.lastBoxStartPosition);while(true){if(this.parsingMdat!==null){r=this.parsingMdat;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){a.d("ISOFile","Found 'mdat' end in buffer #"+this.stream.bufferIndex);this.parsingMdat=null;continue}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex);return}}else{this.lastBoxStartPosition=this.stream.position;t=i.parseOneBox(this.stream);if(t.code===i.ERR_NOT_ENOUGH_DATA){if(t.type==="mdat"){r=new i[t.type+"Box"](t.size-t.hdr_size);this.parsingMdat=r;this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+this.stream.position;r.hdr_size=t.hdr_size;this.stream.buffer.usedBytes+=t.hdr_size;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){this.parsingMdat=null;continue}else{if(!this.moovStartFound){ -this.nextParsePosition=r.fileStart+r.size+r.hdr_size}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex)}return}}else{if(t.type==="moov"){this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}}else if(t.type==="free"){e=this.reposition(false,this.stream.buffer.fileStart+this.stream.position+t.size);if(e){continue}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size;return}}merged=this.mergeNextBuffer();if(merged){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength;continue}else{if(!t.type){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{if(this.moovStartFound){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size}}return}}}else{r=t.box;this.boxes.push(r);switch(r.type){case"mdat":this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+r.start;break;case"moof":this.moofs.push(r);break;case"moov":this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}default:if(this[r.type]!==undefined){a.w("ISOFile","Duplicate Box of type: "+r.type+", overriding previous occurrence")}this[r.type]=r;break}if(r.type==="mdat"){this.stream.buffer.usedBytes+=r.hdr_size}else{this.stream.buffer.usedBytes+=t.size}}}}};s.prototype.reposition=function(e,t){var r;r=this.findPosition(e,t);if(r!==-1){this.stream.buffer=this.stream.nextBuffers[r];this.stream.bufferIndex=r;this.stream.position=t-this.stream.buffer.fileStart;a.d("ISOFile","Repositioning parser at buffer position: "+this.stream.position);return true}else{return false}};s.prototype.findPosition=function(e,t){var r;var i=null;var n=-1;if(e===true){r=0}else{r=this.stream.bufferIndex}while(r=t){a.d("ISOFile","Found position in existing buffer #"+n);return n}else{return-1}}else{return-1}};s.prototype.findEndContiguousBuf=function(e){var t;var r;var i;r=this.stream.nextBuffers[e];if(this.stream.nextBuffers.length>e+1){for(t=e+1;t-1){this.moov.boxes.splice(r,1)}this.moov.mvex=null}this.moov.mvex=new i.mvexBox;this.moov.boxes.push(this.moov.mvex);this.moov.mvex.mehd=new i.mehdBox;this.moov.mvex.boxes.push(this.moov.mvex.mehd);this.moov.mvex.mehd.fragment_duration=this.initial_duration;for(t=0;t0?this.moov.traks[t].samples[0].duration:0;s.default_sample_size=0;s.default_sample_flags=1<<16}this.moov.write(e)};s.prototype.resetTables=function(){var e;var t,r,i,n,a,s,o,f;this.initial_duration=this.moov.mvhd.duration;this.moov.mvhd.duration=0;for(e=0;eg){y++;if(g<0){g=0}g+=o.sample_counts[y]}if(t>0){i.samples[t-1].duration=o.sample_deltas[y];k.dts=i.samples[t-1].dts+i.samples[t-1].duration}else{k.dts=0}if(f){if(t>_){b++;_+=f.sample_counts[b]}k.cts=i.samples[t].dts+f.sample_offsets[b]}else{k.cts=k.dts}if(u){if(t==u.sample_numbers[w]-1){k.is_rap=true;w++}else{k.is_rap=false}}else{k.is_rap=true}if(c){if(c.samples[subs_entry_index].sample_delta+last_subs_sample_index==t){k.subsamples=c.samples[subs_entry_index].subsamples;last_subs_sample_index+=c.samples[subs_entry_index].sample_delta}}}if(t>0)i.samples[t-1].duration=i.mdia.mdhd.duration-i.samples[t-1].dts}};s.prototype.updateSampleLists=function(){var e,t,r;var n,a,s,o;var f;var u,l,c,p,d;var h;while(this.lastMoofIndex0){h.dts=p.samples[p.samples.length-2].dts+p.samples[p.samples.length-2].duration}else{if(c.tfdt){h.dts=c.tfdt.baseMediaDecodeTime}else{h.dts=0}p.first_traf_merged=true}h.cts=h.dts;if(m.flags&i.TRUN_FLAGS_CTS_OFFSET){h.cts=h.dts+m.sample_composition_time_offset[r]}sample_flags=o;if(m.flags&i.TRUN_FLAGS_FLAGS){sample_flags=m.sample_flags[r]}else if(r===0&&m.flags&i.TRUN_FLAGS_FIRST_FLAG){sample_flags=m.first_sample_flags}h.is_rap=sample_flags>>16&1?false:true;var v=c.tfhd.flags&i.TFHD_FLAG_BASE_DATA_OFFSET?true:false;var g=c.tfhd.flags&i.TFHD_FLAG_DEFAULT_BASE_IS_MOOF?true:false;var y=m.flags&i.TRUN_FLAGS_DATA_OFFSET?true:false;var _=0;if(!v){if(!g){if(t===0){_=l.fileStart}else{_=f}}else{_=l.fileStart}}else{_=c.tfhd.base_data_offset}if(t===0&&r===0){if(y){h.offset=_+m.data_offset}else{h.offset=_}}else{h.offset=f}f=h.offset+h.size}}if(c.subs){var b=c.first_sample_index;for(t=0;t0){t+=","}t+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return t};s.prototype.getTrexById=function(e){var t;if(!this.originalMvex)return null;for(t=0;t=r.fileStart&&s.offset+s.alreadyRead=s){console.debug("["+i.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},i:function(t,r){if(n>=s){console.info("["+i.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},w:function(t,n){if(r>=s){console.warn("["+i.getDurationString(new Date-e,1e3)+"]","["+t+"]",n)}},e:function(r,n){if(t>=s){console.error("["+i.getDurationString(new Date-e,1e3)+"]","["+r+"]",n)}}};return o}();t.exports=i;i.getDurationString=function(e,t){function r(e,t){var r=""+e;var i=r.split(".");while(i[0].length0){var r="";for(var n=0;n0)r+=",";r+="["+i.getDurationString(e.start(n))+","+i.getDurationString(e.end(n))+"]"}return r}else{return"(empty)"}}},{}],179:[function(e,t,r){var n=e("./box");var a=e("./DataStream");var s=e("./isofile");var o=e("./log");var f=function(){this.inputStream=null;this.nextBuffers=[];this.inputIsoFile=null;this.onMoovStart=null;this.moovStartSent=false;this.onReady=null;this.readySent=false;this.onSegment=null;this.onSamples=null;this.onError=null;this.sampleListBuilt=false;this.fragmentedTracks=[];this.extractedTracks=[];this.isFragmentationStarted=false;this.nextMoofNumber=0};t.exports=f;f.prototype.setSegmentOptions=function(e,t,r){var i=this.inputIsoFile.getTrackById(e);if(i){var n={};this.fragmentedTracks.push(n);n.id=e;n.user=t;n.trak=i;i.nextSample=0;n.segmentStream=null;n.nb_samples=1e3;n.rapAlignement=true;if(r){if(r.nbSamples)n.nb_samples=r.nbSamples;if(r.rapAlignement)n.rapAlignement=r.rapAlignement}}};f.prototype.unsetSegmentOptions=function(e){var t=-1;for(var r=0;r-1){this.fragmentedTracks.splice(t,1)}};f.prototype.setExtractionOptions=function(e,t,r){var i=this.inputIsoFile.getTrackById(e);if(i){var n={};this.extractedTracks.push(n);n.id=e;n.user=t;n.trak=i;i.nextSample=0;n.nb_samples=1e3;n.samples=[];if(r){if(r.nbSamples)n.nb_samples=r.nbSamples}}};f.prototype.unsetExtractionOptions=function(e){var t=-1;for(var r=0;r-1){this.extractedTracks.splice(t,1)}};f.prototype.createSingleSampleMoof=function(e){var t=new n.moofBox;var r=new n.mfhdBox;r.sequence_number=this.nextMoofNumber;this.nextMoofNumber++;t.boxes.push(r);var i=new n.trafBox;t.boxes.push(i);var a=new n.tfhdBox;i.boxes.push(a);a.track_id=e.track_id;a.flags=n.TFHD_FLAG_DEFAULT_BASE_IS_MOOF;var s=new n.tfdtBox;i.boxes.push(s);s.baseMediaDecodeTime=e.dts;var o=new n.trunBox;i.boxes.push(o);t.trun=o;o.flags=n.TRUN_FLAGS_DATA_OFFSET|n.TRUN_FLAGS_DURATION|n.TRUN_FLAGS_SIZE|n.TRUN_FLAGS_FLAGS|n.TRUN_FLAGS_CTS_OFFSET;o.data_offset=0;o.first_sample_flags=0;o.sample_count=1;o.sample_duration=[];o.sample_duration[0]=e.duration;o.sample_size=[];o.sample_size[0]=e.size;o.sample_flags=[];o.sample_flags[0]=0;o.sample_composition_time_offset=[];o.sample_composition_time_offset[0]=e.cts-e.dts;return t};f.prototype.createFragment=function(e,t,r,i){var s=this.inputIsoFile.getTrackById(t);var f=this.inputIsoFile.getSample(s,r);if(f==null){if(this.nextSeekPosition){this.nextSeekPosition=Math.min(s.samples[r].offset,this.nextSeekPosition)}else{this.nextSeekPosition=s.samples[r].offset}return null}var u=i||new a;u.endianness=a.BIG_ENDIAN;var l=this.createSingleSampleMoof(f);l.write(u);l.trun.data_offset=l.size+8;o.d("BoxWriter","Adjusting data_offset with new value "+l.trun.data_offset);u.adjustUint32(l.trun.data_offset_position,l.trun.data_offset);var c=new n.mdatBox;c.data=f.data;c.write(u);return u};ArrayBuffer.concat=function(e,t){o.d("ArrayBuffer","Trying to create a new buffer of size: "+(e.byteLength+t.byteLength));var r=new Uint8Array(e.byteLength+t.byteLength);r.set(new Uint8Array(e),0);r.set(new Uint8Array(t),e.byteLength);return r.buffer};f.prototype.reduceBuffer=function(e,t,r){var i;i=new Uint8Array(r);i.set(new Uint8Array(e,t,r));i.buffer.fileStart=e.fileStart+t;i.buffer.usedBytes=0;return i.buffer};f.prototype.insertBuffer=function(e){var t=true;for(var r=0;ri.byteLength){this.nextBuffers.splice(r,1);r--;continue}else{o.w("MP4Box","Buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+") already appended, ignoring")}}else{if(e.fileStart+e.byteLength<=i.fileStart){}else{e=this.reduceBuffer(e,0,i.fileStart-e.fileStart)}o.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.splice(r,0,e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}t=false;break}else if(e.fileStart0){e=this.reduceBuffer(e,n,a)}else{t=false;break}}}if(t){o.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.push(e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}};f.prototype.processSamples=function(){var e;var t;if(this.isFragmentationStarted&&this.onSegment!==null){for(e=0;e=t.samples.length){o.i("MP4Box","Sending fragmented data on track #"+r.id+" for samples ["+(t.nextSample-r.nb_samples)+","+(t.nextSample-1)+"]");if(this.onSegment){this.onSegment(r.id,r.user,r.segmentStream.buffer,t.nextSample)}r.segmentStream=null;if(r!==this.fragmentedTracks[e]){break}}}}}if(this.onSamples!==null){for(e=0;e=t.samples.length){o.d("MP4Box","Sending samples on track #"+n.id+" for sample "+t.nextSample);if(this.onSamples){this.onSamples(n.id,n.user,n.samples)}n.samples=[];if(n!==this.extractedTracks[e]){break}}}}}};f.prototype.appendBuffer=function(e){var t;var r;if(e===null||e===undefined){throw"Buffer must be defined and non empty"}if(e.fileStart===undefined){throw"Buffer must have a fileStart property"}if(e.byteLength===0){o.w("MP4Box","Ignoring empty buffer (fileStart: "+e.fileStart+")");return}e.usedBytes=0;this.insertBuffer(e);if(!this.inputStream){if(this.nextBuffers.length>0){r=this.nextBuffers[0];if(r.fileStart===0){this.inputStream=new a(r,0,a.BIG_ENDIAN);this.inputStream.nextBuffers=this.nextBuffers;this.inputStream.bufferIndex=0}else{o.w("MP4Box","The first buffer should have a fileStart of 0");return}}else{o.w("MP4Box","No buffer to start parsing from");return}}if(!this.inputIsoFile){this.inputIsoFile=new s(this.inputStream)}this.inputIsoFile.parse();if(this.inputIsoFile.moovStartFound&&!this.moovStartSent){this.moovStartSent=true;if(this.onMoovStart)this.onMoovStart()}if(this.inputIsoFile.moov){if(!this.sampleListBuilt){this.inputIsoFile.buildSampleLists();this.sampleListBuilt=true}this.inputIsoFile.updateSampleLists();if(this.onReady&&!this.readySent){var i=this.getInfo();this.readySent=true;this.onReady(i)}this.processSamples();if(this.nextSeekPosition){t=this.nextSeekPosition;this.nextSeekPosition=undefined}else{t=this.inputIsoFile.nextParsePosition}var n=this.inputIsoFile.findPosition(true,t);if(n!==-1){t=this.inputIsoFile.findEndContiguousBuf(n)}o.i("MP4Box","Next buffer to fetch should have a fileStart position of "+t);return t}else{if(this.inputIsoFile!==null){return this.inputIsoFile.nextParsePosition}else{return 0}}};f.prototype.getInfo=function(){var e={};var t;var r;var n;var a=new Date(4,0,1,0,0,0,0).getTime();e.duration=this.inputIsoFile.moov.mvhd.duration;e.timescale=this.inputIsoFile.moov.mvhd.timescale;e.isFragmented=this.inputIsoFile.moov.mvex!=null;if(e.isFragmented&&this.inputIsoFile.moov.mvex.mehd){e.fragment_duration=this.inputIsoFile.moov.mvex.mehd.fragment_duration}else{e.fragment_duration=0}e.isProgressive=this.inputIsoFile.isProgressive;e.hasIOD=this.inputIsoFile.moov.iods!=null;e.brands=[];e.brands.push(this.inputIsoFile.ftyp.major_brand);e.brands=e.brands.concat(this.inputIsoFile.ftyp.compatible_brands);e.created=new Date(a+this.inputIsoFile.moov.mvhd.creation_time*1e3);e.modified=new Date(a+this.inputIsoFile.moov.mvhd.modification_time*1e3);e.tracks=[];e.audioTracks=[];e.videoTracks=[];e.subtitleTracks=[];e.metadataTracks=[];e.hintTracks=[];e.otherTracks=[];for(i=0;ie*n.timescale){f=r.samples[i-1].offset;l=i-1;break}if(t&&n.is_rap){a=n.offset;s=n.cts;u=i}}if(t){r.nextSample=u;o.i("MP4Box","Seeking to RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+o.getDurationString(s,c)+" and offset: "+a);return{offset:a,time:s/c}}else{r.nextSample=l;o.i("MP4Box","Seeking to non-RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+o.getDurationString(e)+" and offset: "+a);return{offset:f,time:e}}};f.prototype.seek=function(e,t){var r=this.inputIsoFile.moov;var i;var n;var a;var s={offset:Infinity,time:Infinity};if(!this.inputIsoFile.moov){throw"Cannot seek: moov not received!"}else{for(a=0;an){break}else if(o>=0||n<=l){o=l}}var c=o-n;if(c<0)c=0;i("Buffer length: %f",c);return c<=s}var h=new MediaSource;h.addEventListener("sourceopen",function(){w(0)});t.src=window.URL.createObjectURL(h);var m=new n;m.onError=function(e){i("MP4Box error: %s",e.message);if(b){b()}if(h.readyState==="open"){p("decode")}};var v=false;var g={};m.onReady=function(e){i("MP4 info: %o",e);e.tracks.forEach(function(e){var t;if(e.video){t="video/mp4"}else if(e.audio){t="audio/mp4"}else{return}t+='; codecs="'+e.codec+'"';if(MediaSource.isTypeSupported(t)){var r=h.addSourceBuffer(t);var i={buffer:r,arrayBuffers:[],meta:e,ended:false};r.addEventListener("updateend",A.bind(null,i));m.setSegmentOptions(e.id,null,{nbSamples:e.video?1:100});g[e.id]=i}});if(Object.keys(g).length===0){p("decode");return}var t=m.initializeSegmentation();t.forEach(function(e){S(g[e.id],e.buffer);if(e.id===f){o("init-track-"+f+".mp4",[e.buffer]);u.push(e.buffer)}});v=true};m.onSegment=function(e,t,r,i){var n=g[e];S(n,r,i===n.meta.nb_samples);if(e===f&&u){u.push(r);if(i>1e3){o("track-"+f+".mp4",u);u=null}}};var y;var _=null;var b=null;function w(t){if(t===e.length){m.flush();return}if(_&&t===y){var r=_;setTimeout(function(){if(_===r)_.resume()});return}if(_){_.destroy();b()}y=t;var n={start:y,end:e.length-1};_=e.createReadStream(n);function a(e){_.pause();var t=e.toArrayBuffer();t.fileStart=y;y+=t.byteLength;var r;try{r=m.appendBuffer(t)}catch(n){i("MP4Box threw exception: %s",n.message);if(h.readyState==="open"){p("decode")}_.destroy();b();return}w(r)}_.on("data",a);function s(){b();w(y)}_.on("end",s);function o(e){i("Stream error: %s",e.message);if(h.readyState==="open"){p("network")}}_.on("error",o);b=function(){_.removeListener("data",a);_.removeListener("end",s);_.removeListener("error",o);_=null;b=null}}function x(){if(v){k(t.currentTime)}}function k(e){if(c)l();var t=m.seek(e,true);i("Seeking to time: %d",e);i("Seeked file offset: %d",t.offset);w(t.offset)}function S(e,t,r){e.arrayBuffers.push({buffer:t,ended:r||false});A(e)}function E(){Object.keys(g).forEach(function(e){var t=g[e];if(t.blocked){A(t)}})}function A(e){if(e.buffer.updating)return;e.blocked=!d(e);if(e.blocked)return;if(e.arrayBuffers.length===0)return;var t=e.arrayBuffers.shift();var r=false;try{e.buffer.appendBuffer(t.buffer);e.ended=t.ended;r=true}catch(n){i("SourceBuffer error: %s",n.message);p("decode");return}if(r){U()}}function U(){if(h.readyState!=="open"){return}var e=Object.keys(g).every(function(e){var t=g[e];return t.ended&&!t.buffer.updating});if(e){p()}}};function o(e,t){var r=new Blob(t);var i=URL.createObjectURL(r);var n=document.createElement("a");n.setAttribute("href",i);n.setAttribute("download",e);n.click()}},{debug:121,mp4box:179}],181:[function(e,t,r){t.exports=i;function i(){var e={};for(var t=0;t0)return new Array(e+(/\./.test(t)?2:1)).join(r)+t;return t+""}},{}],184:[function(e,t,r){t.exports={name:"webtorrent",description:"Streaming torrent client",version:"0.62.3",author:{name:"Feross Aboukhadijeh",email:"feross@feross.org",url:"http://feross.org/"},bin:{webtorrent:"./bin/cmd.js"},browser:{"./lib/server.js":false,"bittorrent-dht/client":false,"fs-chunk-store":"memory-chunk-store","load-ip-set":false,ut_pex:false},bugs:{url:"https://github.com/feross/webtorrent/issues"},dependencies:{"addr-to-ip-port":"^1.0.1",bitfield:"^1.0.2","bittorrent-dht":"^3.0.0","bittorrent-swarm":"^5.0.0","chunk-store-stream":"^2.0.0",clivas:"^0.2.0","create-torrent":"^3.4.0","cross-spawn-async":"^2.0.0",debug:"^2.1.0","end-of-stream":"^1.0.0",executable:"^1.1.0","fs-chunk-store":"^1.3.4",hat:"0.0.3","immediate-chunk-store":"^1.0.7",inherits:"^2.0.1",inquirer:"^0.9.0","load-ip-set":"^1.0.3",mediasource:"^1.0.0","memory-chunk-store":"^1.2.0",mime:"^1.2.11",minimist:"^1.1.0",moment:"^2.8.3",multistream:"^2.0.2","network-address":"^1.0.0","parse-torrent":"^5.1.0","path-exists":"^1.0.0","pretty-bytes":"^2.0.1",pump:"^1.0.0","random-iterate":"^1.0.1","range-parser":"^1.0.2","re-emitter":"^1.0.0","run-parallel":"^1.0.0","simple-sha1":"^2.0.0",speedometer:"^0.1.2",thunky:"^0.1.0","torrent-discovery":"^3.0.0","torrent-piece":"^1.0.0",uniq:"^1.0.1",ut_metadata:"^2.1.0",ut_pex:"^1.0.1",videostream:"^1.1.4","windows-no-runnable":"0.0.6",xtend:"^4.0.0","zero-fill":"^2.2.0"},devDependencies:{"bittorrent-tracker":"^6.0.0",brfs:"^1.2.0",browserify:"^11.0.0",finalhandler:"^0.4.0","run-auto":"^1.0.0","serve-static":"^1.9.3","simple-get":"^1.0.0",standard:"^5.1.0",tape:"^4.0.0","uglify-js":"^2.4.15",zelda:"^2.0.0",zuul:"^3.0.0"},homepage:"http://webtorrent.io",keywords:["torrent","bittorrent","bittorrent client","streaming","download","webrtc","webrtc data","webtorrent","mad science"],license:"MIT",main:"index.js",optionalDependencies:{"airplay-js":"^0.2.3",chromecasts:"^1.5.3",nodebmc:"0.0.5"},repository:{type:"git",url:"git://github.com/feross/webtorrent.git"},scripts:{build:"browserify -s WebTorrent -e ./ | uglifyjs -m > webtorrent.min.js","build-debug":"browserify -s WebTorrent -e ./ > webtorrent.debug.js",size:"npm run build && cat webtorrent.min.js | gzip | wc -c",test:"standard && node ./bin/test.js","test-browser":"zuul -- test/basic.js","test-browser-local":"zuul --local -- test/basic.js","test-node":"tape test/*.js"}}},{}],185:[function(e,t,r){(function(r,i,n){t.exports=w;var a=e("create-torrent");var s=e("debug")("webtorrent");var o=e("bittorrent-dht/client");var f=e("events").EventEmitter;var u=e("xtend");var l=e("hat");var c=e("inherits");var p=e("load-ip-set");var d=e("run-parallel");var h=e("parse-torrent");var m=e("speedometer");var v=e("zero-fill");var g=e("path");var y=e("./lib/torrent");c(w,f);var _=e("./package.json").version;var b=_.match(/([0-9]+)/g).slice(0,2).map(v(2)).join("");function w(e){var t=this;if(!(t instanceof w))return new w(e);if(!e)e={};f.call(t);if(!s.enabled)t.setMaxListeners(0);t.destroyed=false;t.torrentPort=e.torrentPort||0;t.tracker=e.tracker!==undefined?e.tracker:true;t._rtcConfig=e.rtcConfig;t._wrtc=e.wrtc||i.WRTC;t.torrents=[];t.downloadSpeed=m();t.uploadSpeed=m();t.peerId=e.peerId===undefined?new n("-WW"+b+"-"+l(48),"utf8"):typeof e.peerId==="string"?new n(e.peerId,"hex"):e.peerId;t.peerIdHex=t.peerId.toString("hex");t.nodeId=e.nodeId===undefined?new n(l(160),"hex"):typeof e.nodeId==="string"?new n(e.nodeId,"hex"):e.nodeId;t.nodeIdHex=t.nodeId.toString("hex");if(e.dht!==false&&typeof o==="function"){t.dht=new o(u({nodeId:t.nodeId},e.dht));t.dht.listen(e.dhtPort)}s("new webtorrent (peerId %s, nodeId %s)",t.peerIdHex,t.nodeIdHex);if(typeof p==="function"){p(e.blocklist,{headers:{"user-agent":"WebTorrent/"+_+" (http://webtorrent.io)"}},function(e,r){if(e)return t.error("Failed to load blocklist: "+e.message);t.blocked=r;a()})}else r.nextTick(a);function a(){if(t.destroyed)return;t.ready=true;t.emit("ready")}}Object.defineProperty(w.prototype,"ratio",{get:function(){var e=this;var t=e.torrents.reduce(function(e,t){return e+t.uploaded},0);var r=e.torrents.reduce(function(e,t){return e+t.downloaded},0)||1;return t/r}});w.prototype.get=function(e){var t=this;if(e instanceof y)return e;var r;try{r=h(e)}catch(i){}if(!r)return null;if(!r.infoHash)throw new Error("Invalid torrent identifier");for(var n=0,a=t.torrents.length;n=0)y();else if(l.indexOf(g)>=0)w();else if(c.indexOf(g)>=0)S();else if(d.indexOf(g)>=0)x();else v(r,new Error('Unsupported file type "'+g+'": Cannot append to DOM'));function y(){if(!p){return v(r,new Error("Video/audio streaming is not supported in your browser. You can still share "+"or download "+e.name+" (once it's fully downloaded). Use Chrome for "+"MediaSource support."))}var s=f.indexOf(g)>=0?"video":"audio";if(a.indexOf(g)>=0)h();else l();function h(){n("Use `videostream` package for "+e.name);y();u.addEventListener("error",d);u.addEventListener("playing",b);o(e,u)}function l(){n("Use MediaSource API for "+e.name);y();u.addEventListener("error",m);u.addEventListener("playing",b);e.createReadStream().pipe(new i(u,{extname:g}));if(_)u.currentTime=_}function c(){n("Use Blob URL for "+e.name);y();u.addEventListener("error",k);u.addEventListener("playing",b);e.getBlobURL(function(e,t){if(e)return k(e);u.src=t;if(_)u.currentTime=_})}function d(e){n("videostream error: fallback to MediaSource API: %o",e.message||e);u.removeEventListener("error",d);u.removeEventListener("playing",b);l()}function m(e){n("MediaSource API error: fallback to Blob URL: %o",e.message||e);u.removeEventListener("error",m);u.removeEventListener("playing",b);c()}function y(e){if(!u){u=document.createElement(s);u.controls=true;u.autoplay=true;u.play();u.addEventListener("progress",function(){_=u.currentTime});t.appendChild(u)}}}function b(){u.removeEventListener("playing",b);r(null,u)}function w(){u=document.createElement("audio");u.controls=true;u.autoplay=true;t.appendChild(u);e.getBlobURL(function(e,t){if(e)return k(e);u.addEventListener("error",k);u.addEventListener("playing",b);u.src=t;u.play()})}function S(){e.getBlobURL(function(n,i){if(n)return k(n);u=document.createElement("img");u.src=i;u.alt=e.name;t.appendChild(u);r(null,u)})}function x(){e.getBlobURL(function(e,n){if(e)return k(e);u=document.createElement("iframe");u.src=n;if(g!==".pdf")u.sandbox="allow-forms allow-scripts";t.appendChild(u);r(null,u)})}function k(t){if(u)u.remove();t.message='Error appending file "'+e.name+'" to DOM: '+t.message;n(t.message);if(r)r(t)}};function m(){}function v(e,t,n){r.nextTick(function(){if(e)e(t,n)})}}).call(this,e("_process"))},{_process:83,debug:42,mediasource:63,path:77,videostream:124}],2:[function(e,t,r){t.exports=o;var n=e("debug")("webtorrent:file-stream");var i=e("inherits");var s=e("stream");i(o,s.Readable);function o(e,t){s.Readable.call(this,t);this.destroyed=false;this._torrent=e._torrent;var r=t&&t.start||0;var n=t&&t.end||e.length-1;var i=e._torrent.pieceLength;this._startPiece=(r+e.offset)/i|0;this._endPiece=(n+e.offset)/i|0;this._piece=this._startPiece;this._offset=r+e.offset-this._startPiece*i;this._missing=n-r+1;this._reading=false;this._notifying=false;this._criticalLength=Math.min(1024*1024/i|0,2)}o.prototype._read=function(){if(this._reading)return;this._reading=true;this._notify()};o.prototype._notify=function(){var e=this;if(!e._reading||e._missing===0)return;if(!e._torrent.bitfield.get(e._piece)){return e._torrent.critical(e._piece,e._piece+e._criticalLength)}if(e._notifying)return;e._notifying=true;var t=e._piece;e._torrent.store.get(t,function(r,i){e._notifying=false;if(e.destroyed)return;if(r)return e.destroy(r);n("read %s (length %s) (err %s)",t,i.length,r&&r.message);if(e._offset){i=i.slice(e._offset);e._offset=0}if(e._missing0){return r[Math.random()*r.length|0]}else{return-1}}},{}],6:[function(e,t,r){(function(r,n){t.exports=H;var i=e("addr-to-ip-port");var s=e("bitfield");var o=e("chunk-store-stream/write");var a=e("create-torrent");var f=e("debug")("webtorrent:torrent");var u=e("torrent-discovery");var h=e("events").EventEmitter;var l=e("xtend/mutable");var c=e("fs-chunk-store");var d=e("immediate-chunk-store");var p=e("inherits");var m=e("multistream");var v=e("os");var g=e("run-parallel");var _=e("parse-torrent");var y=e("path");var b=e("path-exists");var w=e("torrent-piece");var S=e("pump");var x=e("random-iterate");var k=e("re-emitter");var E=e("simple-sha1");var A=e("bittorrent-swarm");var U=e("uniq");var T=e("ut_metadata");var I=e("ut_pex");var L=e("./file");var B=e("./rarity-map");var C=e("./server");var R=128*1024;var P=3e4;var F=5e3;var O=3*w.BLOCK_LENGTH;var M=.5;var D=1;var N=1e4;var z=2;var j=y.join(b.sync("/tmp")?"/tmp":v.tmpDir(),"webtorrent");p(H,h);function H(e,t){var r=this;h.call(r);if(!f.enabled)r.setMaxListeners(0);f("new torrent");r.client=t.client;r.announce=t.announce;r.urlList=t.urlList;r.path=t.path;r._store=t.store||c;r.strategy=t.strategy||"sequential";r._rechokeNumSlots=t.uploads===false||t.uploads===0?0:+t.uploads||10;r._rechokeOptimisticWire=null;r._rechokeOptimisticTime=0;r._rechokeIntervalId=null;r.ready=false;r.destroyed=false;r.metadata=null;r.store=null;r.numBlockedPeers=0;r.files=null;r.done=false;r._amInterested=false;r._selections=[];r._critical=[];r._servers=[];if(e)r._onTorrentId(e)}Object.defineProperty(H.prototype,"timeRemaining",{get:function(){if(this.swarm.downloadSpeed()===0)return Infinity;else return(this.length-this.downloaded)/this.swarm.downloadSpeed()*1e3}});Object.defineProperty(H.prototype,"downloaded",{get:function(){var e=0;for(var t=0,r=this.pieces.length;tt||e<0||t>=i.pieces.length){throw new Error("invalid selection ",e,":",t)}r=Number(r)||0;f("select %s-%s (priority %s)",e,t,r);i._selections.push({from:e,to:t,offset:0,priority:r,notify:n||W});i._selections.sort(function(e,t){return t.priority-e.priority});i._updateSelections()};H.prototype.deselect=function(e,t,r){var n=this;r=Number(r)||0;f("deselect %s-%s (priority %s)",e,t,r);for(var i=0;i2*(t.swarm.numConns-t.swarm.numPeers)&&e.amInterested){e.destroy()}else{r=setTimeout(n,F);if(r.unref)r.unref()}}var i=0;function s(){if(e.peerPieces.length!==t.pieces.length)return;for(;iR){return e.destroy()}if(t.pieces[r])return;t.store.get(r,{offset:n,length:i},s)});e.bitfield(t.bitfield);e.interested();r=setTimeout(n,F);if(r.unref)r.unref();e.isSeeder=false;s()};H.prototype._updateSelections=function(){var e=this;if(!e.swarm||e.destroyed)return;if(!e.metadata)return e.once("metadata",e._updateSelections.bind(e));r.nextTick(e._gcSelections.bind(e));e._updateInterest();e._update()};H.prototype._gcSelections=function(){var e=this;for(var t=0;t=r)return;var n=q(e,D);f(false)||f(true);function i(t,r,n,i){return function(s){return s>=t&&s<=r&&!(s in n)&&e.peerPieces.get(s)&&(!i||i(s))}}function s(){if(e.requests.length)return;var r=t._selections.length;while(r--){var n=t._selections[r];var s;if(t.strategy==="rarest"){var o=n.from+n.offset;var a=n.to;var f=a-o+1;var u={};var h=0;var l=i(o,a,u);while(h=n.from+n.offset;--s){if(!e.peerPieces.get(s))continue;if(t._request(e,s,false))return}}}}function o(){var r=e.downloadSpeed()||1;if(r>O)return function(){return true};var n=Math.max(1,e.requests.length)*w.BLOCK_LENGTH/r;var i=10;var s=0;return function(e){if(!i||t.bitfield.get(e))return true;var o=t.pieces[e].missing;for(;s0)continue;i--;return false}return true}}function a(e){var r=e;for(var n=e;n=n)return true;var s=o();for(var f=0;f0)e._rechokeOptimisticTime-=1;else e._rechokeOptimisticWire=null;var t=[];e.swarm.wires.forEach(function(r){if(!r.isSeeder&&r!==e._rechokeOptimisticWire){t.push({wire:r,downloadSpeed:r.downloadSpeed(),uploadSpeed:r.uploadSpeed(),salt:Math.random(),isChoked:true})}});t.sort(o);var r=0;var n=0;for(;n=O)continue;if(2*u>n||u>s)continue;o=f;s=u}if(!o)return false;for(a=0;a=o)return false;var a=i.pieces[t];var u=a.reserve();if(u===-1&&n&&i._hotswap(e,t)){u=a.reserve()}if(u===-1)return false;var h=i._reservations[t];if(!h)h=i._reservations[t]=[];var l=h.indexOf(null);if(l===-1)l=h.length;h[l]=e;var c=a.chunkOffset(u);var d=a.chunkLength(u);e.request(t,c,d,function m(r,n){if(!i.ready)return i.once("ready",function(){m(r,n)});if(h[l]===e)h[l]=null;if(a!==i.pieces[t])return p();if(r){f("error getting piece %s (offset: %s length: %s) from %s: %s",t,c,d,e.remoteAddress+":"+e.remotePort,r.message);a.cancel(u);p();return}f("got piece %s (offset: %s length: %s) from %s",t,c,d,e.remoteAddress+":"+e.remotePort);if(!a.set(u,n,e))return p();var s=a.flush();E(s,function(e){if(e===i._hashes[t]){if(!i.pieces[t])return;f("piece verified %s",t);i.pieces[t]=null;i._reservations[t]=null;i.bitfield.set(t,true);i.store.put(t,s);i.swarm.wires.forEach(function(e){e.have(t)});i._checkDone()}else{i.pieces[t]=new w(a.length);i.emit("warning",new Error("Piece "+t+" failed verification"))}p()})});function p(){r.nextTick(function(){i._update()})}return true};H.prototype._checkDone=function(){var e=this;if(e.destroyed)return;e.files.forEach(function(t){if(t.done)return;for(var r=t._startPiece;r<=t._endPiece;++r){if(!e.bitfield.get(r))return}t.done=true;t.emit("done");f("file done: "+t.name)});if(e.files.every(function(e){return e.done})){e.done=true;e.emit("done");f("torrent done: "+e.infoHash);if(e.discovery.tracker)e.discovery.tracker.complete()}e._gcSelections()};H.prototype.load=function(e,t){var r=this;if(!Array.isArray(e))e=[e];if(!t)t=W;var n=new m(e);var i=new o(r.store,r.pieceLength);S(n,i,function(e){if(e)return t(e);r.pieces.forEach(function(e,t){r.pieces[t]=null;r._reservations[t]=null;r.bitfield.set(t,true)});r._checkDone();t(null)})};H.prototype.createServer=function(e){var t=this;if(typeof C!=="function")return;var r=new C(t,e);t._servers.push(r);return r};H.prototype._onError=function(e){var t=this;f("torrent error: %s",e.message||e);t.emit("error",e);t.destroy()};function q(e,t){return Math.ceil(2+t*e.downloadSpeed()/w.BLOCK_LENGTH)}function G(e){return Math.random()*e|0}function W(){}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./file":3,"./rarity-map":5,"./server":34,_process:83,"addr-to-ip-port":7,bitfield:15,"bittorrent-swarm":18,"chunk-store-stream/write":38,"create-torrent":41,debug:42,events:47,"fs-chunk-store":64,"immediate-chunk-store":54,inherits:55,multistream:72,os:74,"parse-torrent":76,path:77,"path-exists":78,pump:84,"random-iterate":89,"re-emitter":90,"run-parallel":101,"simple-sha1":105,"torrent-discovery":116,"torrent-piece":117,uniq:119,ut_metadata:122,ut_pex:34,"xtend/mutable":127}],7:[function(e,t,r){var n=/^\[?([^\]]+)\]?:(\d+)$/;var i={};var s=0;t.exports=function o(e){if(s===1e5)t.exports.reset();if(!i[e]){var r=n.exec(e);if(!r)throw new Error("invalid addr: "+e);i[e]=[r[1],Number(r[2])];s+=1}return i[e]};t.exports.reset=function a(){i={};s=0}},{}],8:[function(e,t,r){"use strict";var n=e("./raw");var i=[];var s=[];var o=n.makeRequestCallFromTimer(a);function a(){if(s.length){throw s.shift()}}t.exports=f;function f(e){var t;if(i.length){t=i.pop()}else{t=new u}t.task=e;n(t)}function u(){this.task=null}u.prototype.call=function(){try{this.task.call()}catch(e){if(f.onerror){f.onerror(e)}else{s.push(e);o()}}finally{this.task=null;i[i.length]=this}}},{"./raw":9}],9:[function(e,t,r){(function(e){"use strict";t.exports=r;function r(e){if(!n.length){s();i=true}n[n.length]=e}var n=[];var i=false;var s;var o=0;var a=1024;function f(){while(oa){for(var t=0,r=n.length-o;t0){throw new Error("Invalid string. Length must be a multiple of 4")}var f=e.length;o="="===e.charAt(f-2)?2:"="===e.charAt(f-1)?1:0;a=new t(e.length*3/4-o);i=o>0?e.length-4:e.length;var u=0;function l(e){a[u++]=e}for(r=0,n=0;r>16);l((s&65280)>>8);l(s&255)}if(o===2){s=h(e.charAt(r))<<2|h(e.charAt(r+1))>>4;l(s&255)}else if(o===1){s=h(e.charAt(r))<<10|h(e.charAt(r+1))<<4|h(e.charAt(r+2))>>2;l(s>>8&255);l(s&255)}return a}function c(e){var t,r=e.length%3,i="",s,o;function a(e){return n.charAt(e)}function f(e){return a(e>>18&63)+a(e>>12&63)+a(e>>6&63)+a(e&63)}for(t=0,o=e.length-r;t>2);i+=a(s<<4&63);i+="==";break;case 2:s=(e[e.length-2]<<8)+e[e.length-1];i+=a(s>>10);i+=a(s>>4&63);i+=a(s<<2&63);i+="=";break}return i}e.toByteArray=l;e.fromByteArray=c})(typeof r==="undefined"?this.base64js={}:r)},{}],11:[function(e,t,r){t.exports={encode:e("./lib/encode"),decode:e("./lib/decode")}},{"./lib/decode":12,"./lib/encode":14}],12:[function(e,t,r){(function(r){var n=e("./dict");function i(e,t){i.position=0;i.encoding=t||null;i.data=!r.isBuffer(e)?new r(e):e;return i.next()}i.position=0;i.data=null;i.encoding=null;i.next=function(){switch(i.data[i.position]){case 100:return i.dictionary();break;case 108:return i.list();break;case 105:return i.integer();break;default:return i.bytes();break}};i.find=function(e){var t=i.position;var r=i.data.length;var n=i.data;while(t>3;if(e%8!==0)t++;return t}n.prototype.get=function(e){ +var t=e>>3;return t>e%8)};n.prototype.set=function(e,t){var r=e>>3;if(t||arguments.length===1){if(this.buffer.length>e%8}else if(r>e%8)}};n.prototype._grow=function(e){if(this.buffer.length=this._parserSize){var i=this._buffer.length===1?this._buffer[0]:r.concat(this._buffer);this._bufferSize-=this._parserSize;this._buffer=this._bufferSize?[i.slice(this._parserSize)]:[];this._parser(i.slice(0,this._parserSize))}n(null)};w.prototype._read=function(){};w.prototype._callback=function(e,t,r){if(!e)return;this._clearTimeout();if(!this.peerChoking&&!this._finished)this._updateTimeout();e.callback(t,r)};w.prototype._clearTimeout=function(){if(!this._timeout)return;clearTimeout(this._timeout);this._timeout=null};w.prototype._updateTimeout=function(){if(!this._timeoutMs||!this.requests.length||this._timeout)return;this._timeout=setTimeout(this._onTimeout.bind(this),this._timeoutMs);if(this._timeoutUnref&&this._timeout.unref)this._timeout.unref()};w.prototype._parse=function(e,t){this._parserSize=e;this._parser=t};w.prototype._message=function(e,t,n){var i=n?n.length:0;var s=new r(5+4*t.length);s.writeUInt32BE(s.length+i-4,0);s[4]=e;for(var o=0;o0){this._parse(t,this._onmessage)}else{this._onKeepAlive();this._parse(4,this._onmessagelength)}};w.prototype._onmessage=function(e){this._parse(4,this._onmessagelength);switch(e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:this._debug("got unknown message");return this.emit("unknownmessage",e)}};w.prototype._parseHandshake=function(){this._parse(1,function(e){var t=e.readUInt8(0);this._parse(t+48,function(e){var r=e.slice(0,t);if(r.toString()!=="BitTorrent protocol"){this._debug("Error: wire not speaking BitTorrent protocol (%s)",r.toString());this.end();return}e=e.slice(t);this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(e[7]&1),extended:!!(e[5]&16)});this._parse(4,this._onmessagelength)}.bind(this))}.bind(this))};w.prototype._onfinish=function(){this._finished=true;this.push(null);while(this.read()){}clearInterval(this._keepAliveInterval);this._parse(Number.MAX_VALUE,function(){});this.peerRequests=[];while(this.requests.length){this._callback(this.requests.shift(),new Error("wire was closed"),null)}};w.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._debugId+"] "+e[0];s.apply(null,e)};function S(e,t,r,n){for(var i=0;it)f=t;a=n;while(f--){if(o===t)o=0;r[o]=r[o===0?t-1:o-1];o++}if(e)r[o-1]+=e;var u=r[o-1];var h=r.length=e.maxConns){return}s("drain (%s queued, %s/%s peers)",e.numQueued,e.numPeers,e.maxConns);var t=e._queue.shift();if(!t)return;s("tcp connect attempt to %s",t.addr);var r=i(t.addr);var n={host:r[0],port:r[1]};if(e._hostname)n.localAddress=e._hostname;var o=t.conn=u.connect(n);o.once("connect",function(){t.onConnect()});o.once("error",function(e){t.destroy(e)});t.setConnectTimeout();o.on("close",function(){if(e.destroyed)return;if(t.retries>=p.length){s("conn %s closed: will not re-add (max %s attempts)",t.addr,p.length);return}var r=p[t.retries];s("conn %s closed: will re-add to queue in %sms (attempt %s)",t.addr,r,t.retries+1);var n=setTimeout(function i(){var r=e._addPeer(t.addr);if(r)r.retries=t.retries+1},r);if(n.unref)n.unref()})};m.prototype._onError=function(e){var t=this;t.emit("error",e);t.destroy()};m.prototype._validAddr=function(e){var t=this;var r=i(e);var n=r[0];var s=r[1];return s>0&&s<65535&&!(n==="127.0.0.1"&&s===t._port)}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/peer":19,"./lib/tcp-pool":20,_process:83,"addr-to-ip-port":34,buffer:36,debug:42,dezalgo:45,events:47,inherits:55,net:34,speedometer:22}],19:[function(e,t,r){var n=e("debug")("bittorrent-swarm:peer");var i=e("./webconn");var s=e("bittorrent-protocol");var o=25e3;var a=25e3;r.createWebRTCPeer=function(e,t){var r=new f(e.id);r.conn=e;r.swarm=t;if(r.conn.connected){r.onConnect()}else{r.conn.once("connect",function(){r.onConnect()});r.conn.once("error",function(e){r.destroy(e)});r.setConnectTimeout()}return r};r.createIncomingTCPPeer=function(e){var t=e.remoteAddress+":"+e.remotePort;var r=new f(t);r.conn=e;r.addr=t;r.onConnect();return r};r.createOutgoingTCPPeer=function(e,t){var r=new f(e);r.addr=e;r.swarm=t;return r};r.createWebPeer=function(e,t,r){var n=new f(e);n.swarm=r;n.conn=new i(e,t);n.onConnect();return n};function f(e){var t=this;t.id=e;n("new Peer %s",e);t.addr=null;t.conn=null;t.swarm=null;t.wire=null;t.connected=false;t.destroyed=false;t.timeout=null;t.retries=0;t.sentHandshake=false}f.prototype.onConnect=function(){var e=this;if(e.destroyed)return;e.connected=true;n("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 r=e.wire=new s;r.once("end",function(){e.destroy()});r.once("close",function(){e.destroy()});r.once("finish",function(){e.destroy()});r.once("error",function(t){e.destroy(t)});r.once("handshake",function(t,r){e.onHandshake(t,r)});e.setHandshakeTimeout();t.pipe(r).pipe(t);if(e.swarm&&!e.sentHandshake)e.handshake()};f.prototype.onHandshake=function(e,t){var r=this;if(!r.swarm)return;var i=e.toString("hex");var s=t.toString("hex");if(r.swarm.destroyed)return r.destroy(new Error("swarm already destroyed"));if(i!==r.swarm.infoHashHex){return r.destroy(new Error("unexpected handshake info hash for this swarm"))}if(s===r.swarm.peerIdHex){return r.destroy(new Error("refusing to handshake with self"))}n("Peer %s got handshake %s",r.id,i);clearTimeout(r.handshakeTimeout);r.retries=0;r.wire.on("download",function(e){if(r.destroyed)return;r.swarm.downloaded+=e;r.swarm.downloadSpeed(e);r.swarm.emit("download",e)});r.wire.on("upload",function(e){if(r.destroyed)return;r.swarm.uploaded+=e;r.swarm.uploadSpeed(e);r.swarm.emit("upload",e)});if(!r.sentHandshake)r.handshake();r.swarm.wires.push(r.wire);var o=r.addr;if(!o&&r.conn.remoteAddress){o=r.conn.remoteAddress+":"+r.conn.remotePort}r.swarm.emit("wire",r.wire,o)};f.prototype.handshake=function(){var e=this;e.wire.handshake(e.swarm.infoHash,e.swarm.peerId,e.swarm.handshakeOpts);e.sentHandshake=true};f.prototype.setConnectTimeout=function(){var e=this;clearTimeout(e.connectTimeout);e.connectTimeout=setTimeout(function(){e.destroy(new Error("connect timeout"))},o);if(e.connectTimeout.unref)e.connectTimeout.unref()};f.prototype.setHandshakeTimeout=function(){var e=this;clearTimeout(e.handshakeTimeout);e.handshakeTimeout=setTimeout(function(){e.destroy(new Error("handshake timeout"))},a);if(e.handshakeTimeout.unref)e.handshakeTimeout.unref()};f.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;t.connected=false;n("destroy %s (error: %s)",t.id,e&&(e.message||e));clearTimeout(t.connectTimeout);clearTimeout(t.handshakeTimeout);var r=t.swarm;var i=t.conn;var s=t.wire;t.conn=null;t.swarm=null;t.wire=null;if(r&&s){var o=r.wires.indexOf(s);if(o>=0)r.wires.splice(o,1)}if(i)i.destroy();if(s)s.destroy();if(r)r.removePeer(t.id)}},{"./webconn":21,"bittorrent-protocol":16,debug:42}],20:[function(e,t,r){(function(r){t.exports=f;var n=e("debug")("bittorrent-swarm:tcp-pool");var i=e("dezalgo");var s=e("net");var o=e("./peer");var a={};function f(e,t){var r=this;r.port=e;r.listening=false;r.swarms={};n("new TCPPool (port: %s, hostname: %s)",e,t);r.pendingConns=[];r.server=s.createServer();r.server.on("connection",function(e){r._onConnection(e)});r.server.on("error",function(e){r._onError(e)});r.server.on("listening",function(){r._onListening()});r.server.listen(r.port,t)}f.addSwarm=function(e){var t=a[e._port];if(!t)t=a[e._port]=new f(e._port,e._hostname);t.addSwarm(e);return t};f.removeSwarm=function(e,t){var n=a[e._port];if(!n)return t();n.removeSwarm(e);var i=0;for(var s in n.swarms){var o=n.swarms[s];if(o)i+=1}if(i===0)n.destroy(t);else r.nextTick(t)};f.getDefaultListenPort=function(e){for(var t in a){var r=a[t];if(r&&!r.swarms[e])return r.port}return 0};f.prototype.addSwarm=function(e){var t=this;if(t.swarms[e.infoHashHex]){r.nextTick(function(){e._onError(new Error("There is already a swarm with info hash "+e.infoHashHex+" "+"listening on port "+e._port))});return}t.swarms[e.infoHashHex]=e;if(t.listening){r.nextTick(function(){e._onListening(t.port)})}n("add swarm %s to tcp pool %s",e.infoHashHex,t.port)};f.prototype.removeSwarm=function(e){var t=this;n("remove swarm %s from tcp pool %s",e.infoHashHex,t.port);t.swarms[e.infoHashHex]=null};f.prototype.destroy=function(e){var t=this;if(e)e=i(e);n("destroy tcp pool %s",t.port);t.listening=false;t.pendingConns.forEach(function(e){e.destroy()});a[t.port]=null;try{t.server.close(e)}catch(r){if(e)e(null)}};f.prototype._onListening=function(){var e=this;var t=e.server.address()||{port:0};var r=t.port;n("tcp pool listening on %s",r);if(r!==e.port){a[e.port]=null;e.port=r;a[e.port]=e}e.listening=true;for(var i in e.swarms){var s=e.swarms[i];if(s)s._onListening(e.port)}};f.prototype._onConnection=function(e){var t=this;t.pendingConns.push(e);e.once("close",r);function r(){t.pendingConns.splice(t.pendingConns.indexOf(e))}var n=o.createIncomingTCPPeer(e);n.wire.once("handshake",function(i,s){var o=i.toString("hex");r();e.removeListener("close",r);var a=t.swarms[o];if(a){n.swarm=a;a._addIncomingPeer(n);n.onHandshake(i,s)}else{var f=new Error("Unexpected info hash "+o+" from incoming peer "+n.id+": destroying peer");n.destroy(f)}})};f.prototype._onError=function(e){var t=this;t.destroy();for(var r in t.swarms){var n=t.swarms[r];if(n){t.removeSwarm(n);n._onError(e)}}}}).call(this,e("_process"))},{"./peer":19,_process:83,debug:42,dezalgo:45,net:34}],21:[function(e,t,r){(function(r){t.exports=f;var n=e("bitfield");var i=e("debug")("bittorrent-swarm:webconn");var s=e("simple-get");var o=e("inherits");var a=e("bittorrent-protocol");o(f,a);function f(e,t){var s=this;a.call(this);s.url=e;s.parsedTorrent=t;s.setKeepAlive(true);s.on("handshake",function(t,i){s.handshake(t,new r(20).fill(e));var o=s.parsedTorrent.pieces.length;var a=new n(o);for(var f=0;f<=o;f++){a.set(f,true)}s.bitfield(a)});s.on("choke",function(){i("choke")});s.on("unchoke",function(){i("unchoke")});s.once("interested",function(){i("interested");s.unchoke()});s.on("uninterested",function(){i("uninterested")});s.on("bitfield",function(){i("bitfield")});s.on("request",function(e,t,r,n){i("request pieceIndex=%d offset=%d length=%d",e,t,r);s.httpRequest(e,t,r,n)})}f.prototype.httpRequest=function(e,t,r,n){var o=this;var a=e*o.parsedTorrent.pieceLength;var f=a+t;var u=f+r-1;i("Requesting pieceIndex=%d offset=%d length=%d start=%d end=%d",e,t,r,f,u);var h={url:o.url,method:"GET",headers:{"user-agent":"WebTorrent (http://webtorrent.io)",range:"bytes="+f+"-"+u}};s.concat(h,function(e,t,r){if(e)return n(e);if(r.statusCode<200||r.statusCode>=300){return n(new Error("Unexpected HTTP status code "+r.statusCode))}i("Got data of length %d",t.length);n(null,t)})}}).call(this,e("buffer").Buffer)},{bitfield:15,"bittorrent-protocol":16,buffer:36,debug:42,inherits:55,"simple-get":103}],22:[function(e,t,r){arguments[4][17][0].apply(r,arguments)},{dup:17}],23:[function(e,t,r){(function(r,n){t.exports=m;var i=e("events").EventEmitter;var s=e("debug")("bittorrent-tracker");var o=e("inherits");var a=e("once");var f=e("run-parallel");var u=e("uniq");var h=e("url");var l=e("./lib/common");var c=e("./lib/client/http-tracker");var d=e("./lib/client/udp-tracker");var p=e("./lib/client/websocket-tracker");o(m,i);function m(e,t,o,a){var f=this;if(!(f instanceof m))return new m(e,t,o,a);i.call(f);if(!a)a={};f._peerId=n.isBuffer(e)?e:new n(e,"hex");f._peerIdHex=f._peerId.toString("hex");f._peerIdBinary=f._peerId.toString("binary");f._infoHash=n.isBuffer(o.infoHash)?o.infoHash:new n(o.infoHash,"hex");f._infoHashHex=f._infoHash.toString("hex");f._infoHashBinary=f._infoHash.toString("binary");f.torrentLength=o.length;f.destroyed=false;f._port=t;f._rtcConfig=a.rtcConfig;f._wrtc=a.wrtc;s("new client %s",f._infoHashHex);var l=!!f._wrtc||typeof window!=="undefined";var v=typeof o.announce==="string"?[o.announce]:o.announce==null?[]:o.announce;v=v.map(function(e){e=e.toString();if(e[e.length-1]==="/"){e=e.substring(0,e.length-1)}return e});v=u(v);f._trackers=v.map(function(e){var t=h.parse(e).protocol;if((t==="http:"||t==="https:")&&typeof c==="function"){return new c(f,e)}else if(t==="udp:"&&typeof d==="function"){return new d(f,e)}else if((t==="ws:"||t==="wss:")&&l){return new p(f,e)}else{r.nextTick(function(){var t=new Error("unsupported tracker protocol for "+e);f.emit("warning",t)})}return null}).filter(Boolean)}m.scrape=function(e,t,r){r=a(r);var i=new n("01234567890123456789");var s=6881;var o={infoHash:Array.isArray(t)?t[0]:t,announce:[e]};var f=new m(i,s,o);f.once("error",r);var u=Array.isArray(t)?t.length:1;var h={};f.on("scrape",function(e){u-=1;h[e.infoHash]=e;if(u===0){f.destroy();var t=Object.keys(h);if(t.length===1){r(null,h[t[0]])}else{r(null,h)}}});t=Array.isArray(t)?t.map(function(e){return new n(e,"hex")}):new n(t,"hex");f.scrape({infoHash:t})};m.prototype.start=function(e){var t=this;s("send `start`");e=t._defaultAnnounceOpts(e);e.event="started";t._announce(e);t._trackers.forEach(function(e){e.setInterval()})};m.prototype.stop=function(e){var t=this;s("send `stop`");e=t._defaultAnnounceOpts(e);e.event="stopped";t._announce(e)};m.prototype.complete=function(e){var t=this;s("send `complete`");if(!e)e={};if(e.downloaded==null&&t.torrentLength!=null){e.downloaded=t.torrentLength}e=t._defaultAnnounceOpts(e);e.event="completed";t._announce(e)};m.prototype.update=function(e){var t=this;s("send `update`");e=t._defaultAnnounceOpts(e);if(e.event)delete e.event;t._announce(e)};m.prototype._announce=function(e){var t=this;t._trackers.forEach(function(t){t.announce(e)})};m.prototype.scrape=function(e){var t=this;s("send `scrape`");if(!e)e={};t._trackers.forEach(function(t){t.scrape(e)})};m.prototype.setInterval=function(e){var t=this;s("setInterval %d",e);t._trackers.forEach(function(t){t.setInterval(e)})};m.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;s("destroy");var r=t._trackers.map(function(e){return function(t){e.destroy(t)}});f(r,e);t._trackers=[]};m.prototype._defaultAnnounceOpts=function(e){var t=this;if(!e)e={};if(e.numwant==null)e.numwant=l.DEFAULT_ANNOUNCE_PEERS;if(e.uploaded==null)e.uploaded=0;if(e.downloaded==null)e.downloaded=0;if(e.left==null&&t.torrentLength!=null){e.left=t.torrentLength-e.downloaded}return e}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/client/http-tracker":34,"./lib/client/udp-tracker":34,"./lib/client/websocket-tracker":25,"./lib/common":26,_process:83,buffer:36,debug:42,events:47,inherits:55,once:73,"run-parallel":101,uniq:119,url:120}],24:[function(e,t,r){t.exports=s;var n=e("events").EventEmitter;var i=e("inherits");i(s,n);function s(e,t){var r=this;n.call(r);r.client=e;r.announceUrl=t;r.interval=null;r.destroyed=false}s.prototype.setInterval=function(e){var t=this;if(t.interval)return;if(e==null)e=t.DEFAULT_ANNOUNCE_INTERVAL;clearInterval(t.interval);if(e){var r=t.announce.bind(t,t.client._defaultAnnounceOpts());t.interval=setInterval(r,e);if(t.interval.unref)t.interval.unref()}}},{events:47,inherits:55}],25:[function(e,t,r){t.exports=d;var n=e("debug")("bittorrent-tracker:websocket-tracker");var i=e("hat");var s=e("inherits");var o=e("simple-peer");var a=e("simple-websocket");var f=e("../common");var u=e("./tracker");var h={};var l=30*1e3;var c=5*1e3;s(d,u);function d(e,t,r){var i=this;u.call(i,e,t);n("new websocket tracker %s",t);i.peers={};i.socket=null;i.reconnecting=false;i._openSocket()}d.prototype.DEFAULT_ANNOUNCE_INTERVAL=30*1e3;d.prototype.announce=function(e){var t=this;if(t.destroyed||t.reconnecting)return;if(!t.socket.connected){return t.socket.once("connect",t.announce.bind(t,e))}var r=Math.min(e.numwant,10);t._generateOffers(r,function(n){var i={numwant:r,uploaded:e.uploaded||0,downloaded:e.downloaded,event:e.event,info_hash:t.client._infoHashBinary,peer_id:t.client._peerIdBinary,offers:n};if(t._trackerId)i.trackerid=t._trackerId;t._send(i)})};d.prototype.scrape=function(e){var t=this;if(t.destroyed||t.reconnecting)return;t._onSocketError(new Error("scrape not supported "+t.announceUrl))};d.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;clearInterval(t.interval);h[t.announceUrl]=null;t.socket.removeListener("connect",t._onSocketConnectBound);t.socket.removeListener("data",t._onSocketDataBound);t.socket.removeListener("close",t._onSocketCloseBound);t.socket.removeListener("error",t._onSocketErrorBound);t._onSocketConnectBound=null;t._onSocketErrorBound=null;t._onSocketDataBound=null;t._onSocketCloseBound=null;t.socket.on("error",p);try{t.socket.destroy(e)}catch(r){if(e)e()}t.socket=null};d.prototype._openSocket=function(){var e=this;e.destroyed=false;e._onSocketConnectBound=e._onSocketConnect.bind(e);e._onSocketErrorBound=e._onSocketError.bind(e);e._onSocketDataBound=e._onSocketData.bind(e);e._onSocketCloseBound=e._onSocketClose.bind(e);e.socket=h[e.announceUrl];if(!e.socket){e.socket=h[e.announceUrl]=new a(e.announceUrl);e.socket.on("connect",e._onSocketConnectBound)}e.socket.on("data",e._onSocketDataBound);e.socket.on("close",e._onSocketCloseBound);e.socket.on("error",e._onSocketErrorBound)};d.prototype._onSocketConnect=function(){var e=this;if(e.destroyed)return;if(e.reconnecting){e.reconnecting=false;e.announce(e.client._defaultAnnounceOpts())}};d.prototype._onSocketData=function(e){var t=this;if(t.destroyed)return;if(!(typeof e==="object"&&e!==null)){return t.client.emit("warning",new Error("Invalid tracker response"))}if(e.info_hash!==t.client._infoHashBinary){n("ignoring websocket data from %s for %s (looking for %s: reused socket)",t.announceUrl,f.binaryToHex(e.info_hash),t.client._infoHashHex);return}if(e.peer_id&&e.peer_id===t.client._peerIdBinary){return}n("received %s from %s for %s",JSON.stringify(e),t.announceUrl,t.client._infoHashHex);var r=e["failure reason"];if(r)return t.client.emit("warning",new Error(r));var i=e["warning message"];if(i)t.client.emit("warning",new Error(i));var s=e.interval||e["min interval"];if(s)t.setInterval(s*1e3);var a=e["tracker id"];if(a){t._trackerId=a}if(e.complete){t.client.emit("update",{announce:t.announceUrl,complete:e.complete,incomplete:e.incomplete})}var u;if(e.offer&&e.peer_id){u=new o({trickle:false,config:t.client._rtcConfig,wrtc:t.client._wrtc});u.id=f.binaryToHex(e.peer_id);u.once("signal",function(r){var n={info_hash:t.client._infoHashBinary,peer_id:t.client._peerIdBinary, +to_peer_id:e.peer_id,answer:r,offer_id:e.offer_id};if(t._trackerId)n.trackerid=t._trackerId;t._send(n)});u.signal(e.offer);t.client.emit("peer",u)}if(e.answer&&e.peer_id){u=t.peers[f.binaryToHex(e.offer_id)];if(u){u.id=f.binaryToHex(e.peer_id);u.signal(e.answer);t.client.emit("peer",u)}else{n("got unexpected answer: "+JSON.stringify(e.answer))}}};d.prototype._onSocketClose=function(){var e=this;if(e.destroyed)return;e.destroy();e._startReconnectTimer()};d.prototype._onSocketError=function(e){var t=this;if(t.destroyed)return;t.destroy();t.client.emit("warning",e);t._startReconnectTimer()};d.prototype._startReconnectTimer=function(){var e=this;var t=Math.floor(Math.random()*l)+c;e.reconnecting=true;var r=setTimeout(function(){e._openSocket()},t);if(r.unref)r.unref();n("reconnecting socket in %s ms",t)};d.prototype._send=function(e){var t=this;if(t.destroyed)return;var r=JSON.stringify(e);n("send %s",r);t.socket.send(r)};d.prototype._generateOffers=function(e,t){var r=this;var s=[];n("generating %s offers",e);for(var a=0;a=this.size){var i=r.concat(this._buffered);this._bufferedBytes-=this.size;this.push(i.slice(0,this.size));this._buffered=[i.slice(this.size,i.length)]}n()};o.prototype._flush=function(){if(this._bufferedBytes&&this._zeroPadding){var e=new r(this.size-this._bufferedBytes);e.fill(0);this._buffered.push(e);this.push(r.concat(this._buffered));this._buffered=null}else if(this._bufferedBytes){this.push(r.concat(this._buffered));this._buffered=null}this.push(null)}}).call(this,e("buffer").Buffer)},{buffer:36,defined:44,inherits:55,"readable-stream":33}],28:[function(e,t,r){(function(r){t.exports=a;var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};var i=e("core-util-is");i.inherits=e("inherits");var s=e("./_stream_readable");var o=e("./_stream_writable");i.inherits(a,s);u(n(o.prototype),function(e){if(!a.prototype[e])a.prototype[e]=o.prototype[e]});function a(e){if(!(this instanceof a))return new a(e);s.call(this,e);o.call(this,e);if(e&&e.readable===false)this.readable=false;if(e&&e.writable===false)this.writable=false;this.allowHalfOpen=true;if(e&&e.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",f)}function f(){if(this.allowHalfOpen||this._writableState.ended)return;r.nextTick(this.end.bind(this))}function u(e,t){for(var r=0,n=e.length;r0){if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var o=new Error("stream.unshift() after end event");e.emit("error",o)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)y(e)}w(e,t)}}else if(!i){t.reading=false}return d(t)}function d(e){return!e.ended&&(e.needReadable||e.length=p){e=p}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function v(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(isNaN(e)||a.isNull(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=m(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else return t.length}return e}l.prototype.read=function(e){u("read",e);var t=this._readableState;var r=e;if(!a.isNumber(e)||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){u("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)T(this);else y(this);return null}e=v(e,t);if(e===0&&t.ended){if(t.length===0)T(this);return null}var n=t.needReadable;u("need readable",n);if(t.length===0||t.length-e0)i=U(e,t);else i=null;if(a.isNull(i)){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)T(this);if(!a.isNull(i))this.emit("data",i);return i};function g(e,t){var r=null;if(!a.isBuffer(t)&&!a.isString(t)&&!a.isNullOrUndefined(t)&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function _(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;y(e)}function y(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)r.nextTick(function(){b(e)});else b(e)}}function b(e){u("emit readable");e.emit("readable");A(e)}function w(e,t){if(!t.readingMore){t.readingMore=true;r.nextTick(function(){S(e,t)})}}function S(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(s)a=r.join("");else a=i.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;r.nextTick(function(){if(!t.endEmitted&&t.length===0){t.endEmitted=true;e.readable=false;e.emit("end")}})}}function I(e,t){for(var r=0,n=e.length;r1){var r=[];for(var n=0;n1)return new u(e,arguments[1]);return new u(e)}this.length=0;this.parent=undefined;if(typeof e==="number"){return h(this,e)}if(typeof e==="string"){return l(this,e,arguments.length>1?arguments[1]:"utf8")}return c(this,e)}function h(e,t){e=y(e,t<0?0:b(t)|0);if(!u.TYPED_ARRAY_SUPPORT){for(var r=0;r>>1;if(r)e.parent=o;return e}function b(e){if(e>=f()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+f().toString(16)+" bytes")}return e|0}function w(e,t){if(!(this instanceof w))return new w(e,t);var r=new u(e,t);delete r.parent;return r}u.isBuffer=function te(e){return!!(e!=null&&e._isBuffer)};u.compare=function re(e,t){if(!u.isBuffer(e)||!u.isBuffer(t)){throw new TypeError("Arguments must be Buffers")}if(e===t)return 0;var r=e.length;var n=t.length;var i=0;var s=Math.min(r,n);while(i>>1;case"base64":return Q(e).length;default:if(n)return X(e).length;t=(""+t).toLowerCase();n=true}}}u.byteLength=S;u.prototype.length=undefined;u.prototype.parent=undefined;function x(e,t,r){var n=false;t=t|0;r=r===undefined||r===Infinity?this.length:r|0;if(!e)e="utf8";if(t<0)t=0;if(r>this.length)r=this.length;if(r<=t)return"";while(true){switch(e){case"hex":return O(this,t,r);case"utf8":case"utf-8":return B(this,t,r);case"ascii":return P(this,t,r);case"binary":return F(this,t,r);case"base64":return L(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase();n=true}}}u.prototype.toString=function se(){var e=this.length|0;if(e===0)return"";if(arguments.length===0)return B(this,0,e);return x.apply(this,arguments)};u.prototype.equals=function oe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return true;return u.compare(this,e)===0};u.prototype.inspect=function ae(){var e="";var t=r.INSPECT_MAX_BYTES;if(this.length>0){e=this.toString("hex",0,t).match(/.{2}/g).join(" ");if(this.length>t)e+=" ... "}return""};u.prototype.compare=function fe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return 0;return u.compare(this,e)};u.prototype.indexOf=function ue(e,t){if(t>2147483647)t=2147483647;else if(t<-2147483648)t=-2147483648;t>>=0;if(this.length===0)return-1;if(t>=this.length)return-1;if(t<0)t=Math.max(this.length+t,0);if(typeof e==="string"){if(e.length===0)return-1;return String.prototype.indexOf.call(this,e,t)}if(u.isBuffer(e)){return r(this,e,t)}if(typeof e==="number"){if(u.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,e,t)}return r(this,[e],t)}function r(e,t,r){var n=-1;for(var i=0;r+ii){n=i}}var s=t.length;if(s%2!==0)throw new Error("Invalid hex string");if(n>s/2){n=s/2}for(var o=0;os)r=s;if(e.length>0&&(r<0||t<0)||t>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!n)n="utf8";var o=false;for(;;){switch(n){case"hex":return k(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":return A(this,e,t,r);case"binary":return U(this,e,t,r);case"base64":return T(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase();o=true}}};u.prototype.toJSON=function de(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function L(e,t,r){if(t===0&&r===e.length){return n.fromByteArray(e)}else{return n.fromByteArray(e.slice(t,r))}}function B(e,t,r){r=Math.min(e.length,r);var n=[];var i=t;while(i239?4:s>223?3:s>191?2:1;if(i+a<=r){var f,u,h,l;switch(a){case 1:if(s<128){o=s}break;case 2:f=e[i+1];if((f&192)===128){l=(s&31)<<6|f&63;if(l>127){o=l}}break;case 3:f=e[i+1];u=e[i+2];if((f&192)===128&&(u&192)===128){l=(s&15)<<12|(f&63)<<6|u&63;if(l>2047&&(l<55296||l>57343)){o=l}}break;case 4:f=e[i+1];u=e[i+2];h=e[i+3];if((f&192)===128&&(u&192)===128&&(h&192)===128){l=(s&15)<<18|(f&63)<<12|(u&63)<<6|h&63;if(l>65535&&l<1114112){o=l}}}}if(o===null){o=65533;a=1}else if(o>65535){o-=65536;n.push(o>>>10&1023|55296);o=56320|o&1023}n.push(o);i+=a}return R(n)}var C=4096;function R(e){var t=e.length;if(t<=C){return String.fromCharCode.apply(String,e)}var r="";var n=0;while(nn)r=n;var i="";for(var s=t;sr){e=r}if(t<0){t+=r;if(t<0)t=0}else if(t>r){t=r}if(tr)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUIntLE=function me(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s0&&(i*=256)){n+=this[e+--t]*i}return n};u.prototype.readUInt8=function ge(e,t){if(!t)D(e,1,this.length);return this[e]};u.prototype.readUInt16LE=function _e(e,t){if(!t)D(e,2,this.length);return this[e]|this[e+1]<<8};u.prototype.readUInt16BE=function ye(e,t){if(!t)D(e,2,this.length);return this[e]<<8|this[e+1]};u.prototype.readUInt32LE=function be(e,t){if(!t)D(e,4,this.length);return(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};u.prototype.readUInt32BE=function we(e,t){if(!t)D(e,4,this.length);return this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};u.prototype.readIntLE=function Se(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s=i)n-=Math.pow(2,8*t);return n};u.prototype.readIntBE=function xe(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=t;var i=1;var s=this[e+--n];while(n>0&&(i*=256)){s+=this[e+--n]*i}i*=128;if(s>=i)s-=Math.pow(2,8*t);return s};u.prototype.readInt8=function ke(e,t){if(!t)D(e,1,this.length);if(!(this[e]&128))return this[e];return(255-this[e]+1)*-1};u.prototype.readInt16LE=function Ee(e,t){if(!t)D(e,2,this.length);var r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};u.prototype.readInt16BE=function Ae(e,t){if(!t)D(e,2,this.length);var r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};u.prototype.readInt32LE=function Ue(e,t){if(!t)D(e,4,this.length);return this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};u.prototype.readInt32BE=function Te(e,t){if(!t)D(e,4,this.length);return this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};u.prototype.readFloatLE=function Ie(e,t){if(!t)D(e,4,this.length);return i.read(this,e,true,23,4)};u.prototype.readFloatBE=function Le(e,t){ +if(!t)D(e,4,this.length);return i.read(this,e,false,23,4)};u.prototype.readDoubleLE=function Be(e,t){if(!t)D(e,8,this.length);return i.read(this,e,true,52,8)};u.prototype.readDoubleBE=function Ce(e,t){if(!t)D(e,8,this.length);return i.read(this,e,false,52,8)};function N(e,t,r,n,i,s){if(!u.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>i||te.length)throw new RangeError("index out of range")}u.prototype.writeUIntLE=function Re(e,t,r,n){e=+e;t=t|0;r=r|0;if(!n)N(this,e,t,r,Math.pow(2,8*r),0);var i=1;var s=0;this[t]=e&255;while(++s=0&&(s*=256)){this[t+i]=e/s&255}return t+r};u.prototype.writeUInt8=function Fe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,1,255,0);if(!u.TYPED_ARRAY_SUPPORT)e=Math.floor(e);this[t]=e&255;return t+1};function z(e,t,r,n){if(t<0)t=65535+t+1;for(var i=0,s=Math.min(e.length-r,2);i>>(n?i:1-i)*8}}u.prototype.writeUInt16LE=function Oe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8}else{z(this,e,t,true)}return t+2};u.prototype.writeUInt16BE=function Me(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e&255}else{z(this,e,t,false)}return t+2};function j(e,t,r,n){if(t<0)t=4294967295+t+1;for(var i=0,s=Math.min(e.length-r,4);i>>(n?i:3-i)*8&255}}u.prototype.writeUInt32LE=function De(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[t+3]=e>>>24;this[t+2]=e>>>16;this[t+1]=e>>>8;this[t]=e&255}else{j(this,e,t,true)}return t+4};u.prototype.writeUInt32BE=function Ne(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e&255}else{j(this,e,t,false)}return t+4};u.prototype.writeIntLE=function ze(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=0;var o=1;var a=e<0?1:0;this[t]=e&255;while(++s>0)-a&255}return t+r};u.prototype.writeIntBE=function je(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=r-1;var o=1;var a=e<0?1:0;this[t+s]=e&255;while(--s>=0&&(o*=256)){this[t+s]=(e/o>>0)-a&255}return t+r};u.prototype.writeInt8=function He(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,1,127,-128);if(!u.TYPED_ARRAY_SUPPORT)e=Math.floor(e);if(e<0)e=255+e+1;this[t]=e&255;return t+1};u.prototype.writeInt16LE=function qe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8}else{z(this,e,t,true)}return t+2};u.prototype.writeInt16BE=function Ge(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e&255}else{z(this,e,t,false)}return t+2};u.prototype.writeInt32LE=function We(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,2147483647,-2147483648);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8;this[t+2]=e>>>16;this[t+3]=e>>>24}else{j(this,e,t,true)}return t+4};u.prototype.writeInt32BE=function Ye(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,2147483647,-2147483648);if(e<0)e=4294967295+e+1;if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e&255}else{j(this,e,t,false)}return t+4};function H(e,t,r,n,i,s){if(t>i||te.length)throw new RangeError("index out of range");if(r<0)throw new RangeError("index out of range")}function q(e,t,r,n,s){if(!s){H(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38)}i.write(e,t,r,n,23,4);return r+4}u.prototype.writeFloatLE=function Ve(e,t,r){return q(this,e,t,true,r)};u.prototype.writeFloatBE=function Ke(e,t,r){return q(this,e,t,false,r)};function G(e,t,r,n,s){if(!s){H(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308)}i.write(e,t,r,n,52,8);return r+8}u.prototype.writeDoubleLE=function $e(e,t,r){return G(this,e,t,true,r)};u.prototype.writeDoubleBE=function Xe(e,t,r){return G(this,e,t,false,r)};u.prototype.copy=function Ze(e,t,r,n){if(!r)r=0;if(!n&&n!==0)n=this.length;if(t>=e.length)t=e.length;if(!t)t=0;if(n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");if(n>this.length)n=this.length;if(e.length-t=0;s--){e[s+t]=this[s+r]}}else if(i<1e3||!u.TYPED_ARRAY_SUPPORT){for(s=0;s=this.length)throw new RangeError("start out of bounds");if(r<0||r>this.length)throw new RangeError("end out of bounds");var n;if(typeof e==="number"){for(n=t;n55295&&r<57344){if(!i){if(r>56319){if((t-=3)>-1)s.push(239,191,189);continue}else if(o+1===n){if((t-=3)>-1)s.push(239,191,189);continue}i=r;continue}if(r<56320){if((t-=3)>-1)s.push(239,191,189);i=r;continue}r=(i-55296<<10|r-56320)+65536}else if(i){if((t-=3)>-1)s.push(239,191,189)}i=null;if(r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else{throw new Error("Invalid code point")}}return s}function Z(e){var t=[];for(var r=0;r>8;i=r%256;s.push(i);s.push(n)}return s}function Q(e){return n.toByteArray(V(e))}function ee(e,t,r,n){for(var i=0;i=t.length||i>=e.length)break;t[i+r]=e[i]}return i}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":10,ieee754:53,"is-array":56}],37:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Time-out",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Request Entity Too Large",414:"Request-URI Too Large",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Time-out",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],38:[function(e,t,r){t.exports=o;var n=e("block-stream2");var i=e("inherits");var s=e("stream");i(o,s.Writable);function o(e,t,r){var i=this;if(!(i instanceof o)){return new o(e,t,r)}s.Writable.call(i,r);if(!r)r={};if(!e||!e.put||!e.get){throw new Error("First argument must be an abstract-chunk-store compliant store")}t=Number(t);if(!t)throw new Error("Second argument must be a chunk length");i._blockstream=new n(t,{zeroPadding:false});i._blockstream.on("data",f).on("error",function(e){i.destroy(e)});var a=0;function f(t){if(i.destroyed)return;e.put(a,t);a+=1}i.on("finish",function(){this._blockstream.end()})}o.prototype._write=function(e,t,r){this._blockstream.write(e,t,r)};o.prototype.destroy=function(e){if(this.destroyed)return;this.destroyed=true;if(e)this.emit("error",e);this.emit("close")}},{"block-stream2":27,inherits:55,stream:108}],39:[function(e,t,r){t.exports=function(e,t){var r=Infinity;var n=0;var i=null;t.sort(function(e,t){return e-t});for(var s=0,o=t.length;s=r){break}r=n;i=t[s]}return i}},{}],40:[function(e,t,r){(function(e){function t(e){if(Array.isArray){return Array.isArray(e)}return v(e)==="[object Array]"}r.isArray=t;function n(e){return typeof e==="boolean"}r.isBoolean=n;function i(e){return e===null}r.isNull=i;function s(e){return e==null}r.isNullOrUndefined=s;function o(e){return typeof e==="number"}r.isNumber=o;function a(e){return typeof e==="string"}r.isString=a;function f(e){return typeof e==="symbol"}r.isSymbol=f;function u(e){return e===void 0}r.isUndefined=u;function h(e){return v(e)==="[object RegExp]"}r.isRegExp=h;function l(e){return typeof e==="object"&&e!==null}r.isObject=l;function c(e){return v(e)==="[object Date]"}r.isDate=c;function d(e){return v(e)==="[object Error]"||e instanceof Error}r.isError=d;function p(e){return typeof e==="function"}r.isFunction=p;function m(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}r.isPrimitive=m;r.isBuffer=e.isBuffer;function v(e){return Object.prototype.toString.call(e)}}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":57}],41:[function(e,t,r){(function(r,n){t.exports=y;t.exports.announceList=[["udp://tracker.openbittorrent.com:80"],["udp://tracker.internetwarriors.net:1337"],["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://exodus.desync.com:6969"],["wss://tracker.webtorrent.io"]];t.exports.parseInput=b;var i=e("bencode");var s=e("block-stream2");var o=e("piece-length");var a=e("path");var f=e("dezalgo");var u=e("filestream/read");var h=e("flatten");var l=e("fs");var c=e("is-file");var d=e("junk");var p=e("multistream");var m=e("once");var v=e("run-parallel");var g=e("simple-sha1");var _=e("stream");function y(e,t,r){if(typeof t==="function"){r=t;t={}}if(!t)t={};b(e,t,function(e,n,i){if(e)return r(e);t.singleFileTorrent=i;A(n,t,r)})}function b(e,t,r){if(typeof t==="function"){r=t;t={}}if(!t)t={};r=f(r);if(Array.isArray(e)&&e.length===0)throw new Error("invalid input type");if(I(e))e=Array.prototype.slice.call(e);if(!Array.isArray(e))e=[e];if(!t.name)t.name=e[0]&&e[0].name;if(!t.name)t.name=typeof e[0]==="string"&&a.basename(e[0]);if(t.name===undefined){throw new Error("missing option 'name' and unable to infer it from input[0].name")}if(e.length===1&&!e[0].name)e[0].name=t.name;var i=e.reduce(function(e,t){return e+Number(typeof t==="string")},0);var s=e.length===1;if(e.length===1&&typeof e[0]==="string"){c(e[0],function(e,t){if(e)return r(e);s=t;o()})}else{o()}function o(){v(e.map(function(e){return function(r){var o={};if(T(e)){o.getStream=B(e);o.length=e.size}else if(n.isBuffer(e)){o.getStream=C(e);o.length=e.length}else if(L(e)){if(!t.pieceLength){throw new Error("must specify `pieceLength` option if input is Stream")}o.getStream=P(e,o);o.length=0}else if(typeof e==="string"){if(typeof l.readdir!=="function"){throw new Error("filesystem paths do not work in the browser")}var f=i>1||s;w(e,f,r);return}else{throw new Error("invalid input type")}if(!e.name)throw new Error("missing requied `name` property on input");o.path=e.name.split(a.sep);r(null,o)}}),function(e,t){if(e)return r(e);t=h(t);r(null,t,s)})}}function w(e,t,r){x(e,S,function(n,i){if(n)return r(n);if(Array.isArray(i))i=h(i);else i=[i];e=a.normalize(e);if(t){e=e.slice(0,e.lastIndexOf(a.sep)+1)}if(e[e.length-1]!==a.sep)e+=a.sep;i.forEach(function(t){t.getStream=R(t.path);t.path=t.path.replace(e,"").split(a.sep)});r(null,i)})}function S(e,t){t=m(t);l.stat(e,function(r,n){if(r)return t(r);var i={length:n.size,path:e};t(null,i)})}function x(e,t,r){l.readdir(e,function(n,i){if(n&&n.code==="ENOTDIR"){t(e,r)}else if(n){r(n)}else{v(i.filter(k).filter(d.not).map(function(r){return function(n){x(a.join(e,r),t,n)}}),r)}})}function k(e){return e[0]!=="."}function E(e,t,r){r=m(r);var i=[];var o=0;var a=e.map(function(e){return e.getStream});var f=0;var u=0;var h=false;var l=new p(a);var c=new s(t,{zeroPadding:false});l.on("error",_);l.pipe(c).on("data",d).on("end",v).on("error",_);function d(e){o+=e.length;var t=u;g(e,function(e){i[t]=e;f-=1;b()});f+=1;u+=1}function v(){h=true;b()}function _(e){y();r(e)}function y(){l.removeListener("error",_);c.removeListener("data",d);c.removeListener("end",v);c.removeListener("error",_)}function b(){if(h&&f===0){y();r(null,new n(i.join(""),"hex"),o)}}}function A(e,n,s){var a=n.announceList;if(!a){if(typeof n.announce==="string")a=[[n.announce]];else if(Array.isArray(n.announce)){a=n.announce.map(function(e){return[e]})}}if(!a)a=[];if(r.WEBTORRENT_ANNOUNCE){if(typeof r.WEBTORRENT_ANNOUNCE==="string"){a.push([[r.WEBTORRENT_ANNOUNCE]])}else if(Array.isArray(r.WEBTORRENT_ANNOUNCE)){a=a.concat(r.WEBTORRENT_ANNOUNCE.map(function(e){return[e]}))}}if(a.length===0){a=a.concat(t.exports.announceList)}if(typeof n.urlList==="string")n.urlList=[n.urlList];var f={info:{name:n.name},announce:a[0][0],"announce-list":a,"creation date":Number(n.creationDate)||Date.now(),encoding:"UTF-8"};if(n.comment!==undefined)f.comment=n.comment;if(n.createdBy!==undefined)f["created by"]=n.createdBy;if(n.private!==undefined)f.info.private=Number(n.private);if(n.sslCert!==undefined)f.info["ssl-cert"]=n.sslCert;if(n.urlList!==undefined)f["url-list"]=n.urlList;var u=n.pieceLength||o(e.reduce(U,0));f.info["piece length"]=u;E(e,u,function(t,r,o){if(t)return s(t);f.info.pieces=r;e.forEach(function(e){delete e.getStream});if(n.singleFileTorrent){f.info.length=o}else{f.info.files=e}s(null,i.encode(f))})}function U(e,t){return e+t.length}function T(e){return typeof Blob!=="undefined"&&e instanceof Blob}function I(e){return typeof FileList==="function"&&e instanceof FileList}function L(e){return typeof e==="object"&&typeof e.pipe==="function"}function B(e){return function(){return new u(e)}}function C(e){return function(){var t=new _.PassThrough;t.end(e);return t}}function R(e){return function(){return l.createReadStream(e)}}function P(e,t){return function(){var r=new _.Transform;r._transform=function(e,r,n){t.length+=e.length;this.push(e);n()};e.pipe(r);return r}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{bencode:11,"block-stream2":27,buffer:36,dezalgo:45,"filestream/read":48,flatten:49,fs:35,"is-file":58,junk:61,multistream:72,once:73,path:77,"piece-length":79,"run-parallel":101,"simple-sha1":105,stream:108}],42:[function(e,t,r){r=t.exports=e("./debug");r.log=s;r.formatArgs=i;r.save=o;r.load=a;r.useColors=n;r.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:f();r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function n(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}r.formatters.j=function(e){return JSON.stringify(e)};function i(){var e=arguments;var t=this.useColors;e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+r.humanize(this.diff);if(!t)return e;var n="color: "+this.color;e=[e[0],n,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0;var s=0;e[0].replace(/%[a-z%]/g,function(e){if("%%"===e)return;i++;if("%c"===e){s=i}});e.splice(s,0,n);return e}function s(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function o(e){try{if(null==e){r.storage.removeItem("debug")}else{r.storage.debug=e}}catch(t){}}function a(){var e;try{e=r.storage.debug}catch(t){}return e}r.enable(a());function f(){try{return window.localStorage}catch(e){}}},{"./debug":43}],43:[function(e,t,r){r=t.exports=o;r.coerce=h;r.disable=f;r.enable=a;r.enabled=u;r.humanize=e("ms");r.names=[];r.skips=[];r.formatters={};var n=0;var i;function s(){return r.colors[n++%r.colors.length]}function o(e){function t(){}t.enabled=false;function n(){var e=n;var t=+new Date;var o=t-(i||t);e.diff=o;e.prev=i;e.curr=t;i=t;if(null==e.useColors)e.useColors=r.useColors();if(null==e.color&&e.useColors)e.color=s();var a=Array.prototype.slice.call(arguments);a[0]=r.coerce(a[0]);if("string"!==typeof a[0]){a=["%o"].concat(a)}var f=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,n){if(t==="%%")return t;f++;var i=r.formatters[n];if("function"===typeof i){var s=a[f];t=i.call(e,s);a.splice(f,1);f--}return t});if("function"===typeof r.formatArgs){a=r.formatArgs.apply(e,a)}var u=n.log||r.log||console.log.bind(console);u.apply(e,a)}n.enabled=true;var o=r.enabled(e)?n:t;o.namespace=e;return o}function a(e){r.save(e);var t=(e||"").split(/[\s,]+/);var n=t.length;for(var i=0;i0&&this._events[e].length>r){this._events[e].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[e].length);if(typeof console.trace==="function"){console.trace()}}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=false;function n(){this.removeListener(e,n);if(!r){r=true;t.apply(this,arguments)}}n.listener=t;this.on(e,n);return this};n.prototype.removeListener=function(e,t){var r,n,s,a;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;r=this._events[e];s=r.length;n=-1;if(r===t||i(r.listener)&&r.listener===t){delete this._events[e];if(this._events.removeListener)this.emit("removeListener",e,t)}else if(o(r)){for(a=s;a-- >0;){if(r[a]===t||r[a].listener&&r[a].listener===t){n=a;break}}if(n<0)return this;if(r.length===1){r.length=0;delete this._events[e]}else{r.splice(n,1)}if(this._events.removeListener)this.emit("removeListener",e,t)}return this};n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[e])delete this._events[e];return this}if(arguments.length===0){for(t in this._events){if(t==="removeListener")continue;this.removeAllListeners(t)}this.removeAllListeners("removeListener");this._events={};return this}r=this._events[e];if(i(r)){this.removeListener(e,r)}else if(r){while(r.length)this.removeListener(e,r[r.length-1])}delete this._events[e];return this};n.prototype.listeners=function(e){var t;if(!this._events||!this._events[e])t=[];else if(i(this._events[e]))t=[this._events[e]];else t=this._events[e].slice();return t};n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;else if(t)return t.length}return 0};n.listenerCount=function(e,t){return e.listenerCount(t)};function i(e){return typeof e==="function"}function s(e){return typeof e==="number"}function o(e){return typeof e==="object"&&e!==null}function a(e){return e===void 0}},{}],48:[function(e,t,r){var n=e("stream").Readable;var i=e("inherits");var s=/^.*\.(\w+)$/;var o=e("typedarray-to-buffer");function a(e,t){var r=this;if(!(this instanceof a)){return new a(e,t)}t=t||{};n.call(this,t);this._offset=0;this._ready=false;this._file=e;this._size=e.size;this._chunkSize=t.chunkSize||Math.max(this._size/1e3,200*1024);this.reader=new FileReader;this._generateHeaderBlocks(e,t,function(e,t){if(e){return r.emit("error",e)}if(Array.isArray(t)){t.forEach(function(e){r.push(e)})}r._ready=true;r.emit("_ready")})}i(a,n);t.exports=a;a.prototype._generateHeaderBlocks=function(e,t,r){r(null,[])};a.prototype._read=function(){if(!this._ready){this.once("_ready",this._read.bind(this));return}var e=this;var t=this.reader;var r=this._offset;var n=this._offset+this._chunkSize;if(n>this._size)n=this._size;if(r===this._size){this.destroy();this.push(null);return}t.onload=function(){e._offset=n;e.push(o(t.result))};t.onerror=function(){e.emit("error",t.error)};t.readAsArrayBuffer(this._file.slice(r,n))};a.prototype.destroy=function(){this._file=null;if(this.reader){this.reader.onload=null;this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}},{inherits:55,stream:108,"typedarray-to-buffer":118}],49:[function(e,t,r){t.exports=function n(e,t){t=typeof t=="number"?t:Infinity;return r(e,1);function r(e,n){return e.reduce(function(e,i){if(Array.isArray(i)&&n=Math.pow(2,e)){return n(e,t)}else return o};n.rack=function(e,t,r){var i=function(i){var o=0;do{if(o++>10){if(r)e+=r;else throw new Error("too many ID collisions, use more bits")}var a=n(e,t)}while(Object.hasOwnProperty.call(s,a));s[a]=i;return a};var s=i.hats={};i.get=function(e){return i.hats[e]};i.set=function(e,t){i.hats[e]=t;return i};i.bits=e||128;i.base=t||16;return i}},{}],52:[function(e,t,r){var n=e("http");var i=t.exports;for(var s in n){if(n.hasOwnProperty(s))i[s]=n[s]}i.request=function(e,t){if(!e)e={};e.scheme="https";e.protocol="https:";return n.request.call(this,e,t)}},{http:109}],53:[function(e,t,r){r.read=function(e,t,r,n,i){var s,o;var a=i*8-n-1;var f=(1<>1;var h=-7;var l=r?i-1:0;var c=r?-1:1;var d=e[t+l];l+=c;s=d&(1<<-h)-1;d>>=-h;h+=a;for(;h>0;s=s*256+e[t+l],l+=c,h-=8){}o=s&(1<<-h)-1;s>>=-h;h+=n;for(;h>0;o=o*256+e[t+l],l+=c,h-=8){}if(s===0){s=1-u}else if(s===f){return o?NaN:(d?-1:1)*Infinity}else{o=o+Math.pow(2,n);s=s-u}return(d?-1:1)*o*Math.pow(2,s-n)};r.write=function(e,t,r,n,i,s){var o,a,f;var u=s*8-i-1;var h=(1<>1;var c=i===23?Math.pow(2,-24)-Math.pow(2,-77):0;var d=n?0:s-1;var p=n?1:-1;var m=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){a=isNaN(t)?1:0;o=h}else{o=Math.floor(Math.log(t)/Math.LN2);if(t*(f=Math.pow(2,-o))<1){o--;f*=2}if(o+l>=1){t+=c/f}else{t+=c*Math.pow(2,1-l)}if(t*f>=2){o++;f/=2}if(o+l>=h){a=0;o=h}else if(o+l>=1){a=(t*f-1)*Math.pow(2,i);o=o+l}else{a=t*Math.pow(2,l-1)*Math.pow(2,i);o=0}}for(;i>=8;e[r+d]=a&255,d+=p,a/=256,i-=8){}o=o<0;e[r+d]=o&255,d+=p,o/=256,u-=8){}e[r+d-p]|=m*128}},{}],54:[function(e,t,r){(function(e){t.exports=r;function r(e){if(!(this instanceof r))return new r(e);this.store=e;if(!this.store||!this.store.get||!this.store.put){throw new Error("First argument must be abstract-chunk-store compliant")}this.mem=[]}r.prototype.put=function(e,t,r){var n=this;n.mem[e]=t;n.store.put(e,t,function(t){n.mem[e]=null;if(r)r(t)})};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);var i=t&&t.offset||0;var s=t&&t.length&&i+t.length;var o=this.mem[e];if(o)return n(r,null,t?o.slice(i,s):o);this.store.get(e,t,r)};r.prototype.close=function(e){this.store.close(e)};r.prototype.destroy=function(e){this.store.destroy(e)};function n(t,r,n){e.nextTick(function(){if(t)t(r,n)})}}).call(this,e("_process"))},{_process:83}],55:[function(e,t,r){if(typeof Object.create==="function"){t.exports=function n(e,t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}else{t.exports=function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype;e.prototype=new r;e.prototype.constructor=e}}},{}],56:[function(e,t,r){var n=Array.isArray;var i=Object.prototype.toString;t.exports=n||function(e){return!!e&&"[object Array]"==i.call(e)}},{}],57:[function(e,t,r){t.exports=function(e){return!!(e!=null&&(e._isBuffer||e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)))}},{}],58:[function(e,t,r){"use strict";var n=e("fs");t.exports=function s(e,t){if(!t)return i(e);n.stat(e,function(e,r){if(e)return t(e);return t(null,r.isFile())})};t.exports.sync=i;function i(e){return n.existsSync(e)&&n.statSync(e).isFile()}},{fs:35}],59:[function(e,t,r){t.exports=s;s.strict=o;s.loose=a;var n=Object.prototype.toString;var i={"[object Int8Array]":true,"[object Int16Array]":true,"[object Int32Array]":true,"[object Uint8Array]":true,"[object Uint8ClampedArray]":true,"[object Uint16Array]":true,"[object Uint32Array]":true,"[object Float32Array]":true,"[object Float64Array]":true};function s(e){return o(e)||a(e)}function o(e){return e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array}function a(e){return i[n.call(e)]}},{}],60:[function(e,t,r){t.exports=Array.isArray||function(e){return Object.prototype.toString.call(e)=="[object Array]"}},{}],61:[function(e,t,r){"use strict";r.re=/^npm-debug\.log$|^\..*\.swp$|^\.DS_Store$|^\.AppleDouble$|^\.LSOverride$|^Icon[\r\?]?|^\._.*|^\.Spotlight-V100$|\.Trashes|^__MACOSX$|~$|^Thumbs\.db$|^ehthumbs\.db$|^Desktop\.ini$/; +r.is=function(e){return r.re.test(e)};r.not=r.isnt=function(e){return!r.is(e)}},{}],62:[function(e,t,r){(function(r){t.exports=o;t.exports.decode=o;t.exports.encode=a;var n=e("thirty-two");var i=e("xtend");var s=e("uniq");function o(e){var t={};var i=e.split("magnet:?")[1];var o=i&&i.length>=0?i.split("&"):[];o.forEach(function(e){var r=e.split("=");if(r.length!==2)return;var n=r[0];var i=r[1];if(n==="dn")i=decodeURIComponent(i).replace(/\+/g," ");if(n==="tr"||n==="xs"||n==="as"||n==="ws"){i=decodeURIComponent(i)}if(n==="kt")i=decodeURIComponent(i).split("+");if(t[n]){if(Array.isArray(t[n])){t[n].push(i)}else{var s=t[n];t[n]=[s,i]}}else{t[n]=i}});var a;if(t.xt){var f=Array.isArray(t.xt)?t.xt:[t.xt];f.forEach(function(e){if(a=e.match(/^urn:btih:(.{40})/)){t.infoHash=new r(a[1],"hex").toString("hex")}else if(a=e.match(/^urn:btih:(.{32})/)){var i=n.decode(a[1]);t.infoHash=new r(i,"binary").toString("hex")}})}if(t.dn)t.name=t.dn;if(t.kt)t.keywords=t.kt;if(typeof t.tr==="string")t.announce=[t.tr];else if(Array.isArray(t.tr))t.announce=t.tr;else t.announce=[];s(t.announce);t.urlList=[];if(typeof t.as==="string"||Array.isArray(t.as)){t.urlList=t.urlList.concat(t.as)}if(typeof t.ws==="string"||Array.isArray(t.ws)){t.urlList=t.urlList.concat(t.ws)}return t}function a(e){e=i(e);if(e.infoHash)e.xt="urn:btih:"+e.infoHash;if(e.name)e.dn=e.name;if(e.keywords)e.kt=e.keywords;if(e.announce)e.tr=e.announce;if(e.urlList){e.ws=e.urlList;delete e.as}var t="magnet:?";Object.keys(e).filter(function(e){return e.length===2}).forEach(function(r,n){var i=Array.isArray(e[r])?e[r]:[e[r]];i.forEach(function(e,i){if((n>0||i>0)&&(r!=="kt"||i===0))t+="&";if(r==="dn")e=encodeURIComponent(e).replace(/%20/g,"+");if(r==="tr"||r==="xs"||r==="as"||r==="ws"){e=encodeURIComponent(e)}if(r==="kt")e=encodeURIComponent(e);if(r==="kt"&&i>0)t+="+"+e;else t+=r+"="+e})});return t}}).call(this,e("buffer").Buffer)},{buffer:36,"thirty-two":114,uniq:119,xtend:126}],63:[function(e,t,r){t.exports=o;var n=e("inherits");var i=e("stream");var s=typeof window!=="undefined"&&window.MediaSource;n(o,i.Writable);function o(e,t){var r=this;if(!(r instanceof o))return new o(e,t);i.Writable.call(r,t);if(!s)throw new Error("web browser lacks MediaSource support");if(!t)t={};r._elem=e;r._mediaSource=new s;r._sourceBuffer=null;r._cb=null;r._type=t.type||a(t.extname);if(!r._type)throw new Error("missing `opts.type` or `opts.extname` options");r._elem.src=window.URL.createObjectURL(r._mediaSource);r._mediaSource.addEventListener("sourceopen",function(){if(s.isTypeSupported(r._type)){r._sourceBuffer=r._mediaSource.addSourceBuffer(r._type);r._sourceBuffer.addEventListener("updateend",r._flow.bind(r));r._flow()}else{r._mediaSource.endOfStream("decode")}});r.on("finish",function(){r._mediaSource.endOfStream()})}o.prototype._write=function(e,t,r){var n=this;if(!n._sourceBuffer){n._cb=function(i){if(i)return r(i);n._write(e,t,r)};return}if(n._sourceBuffer.updating){return r(new Error("Cannot append buffer while source buffer updating"))}n._sourceBuffer.appendBuffer(e);n._cb=r};o.prototype._flow=function(){var e=this;if(e._cb){e._cb(null)}};function a(e){if(!e)return null;if(e[0]!==".")e="."+e;return{".m4a":'audio/mp4; codecs="mp4a.40.5"',".m4v":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".mp3":"audio/mpeg",".mp4":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".webm":'video/webm; codecs="vorbis, vp8"'}[e]}},{inherits:55,stream:108}],64:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(!(this instanceof r))return new r(e,t);if(!t)t={};this.chunkLength=Number(e);if(!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[];this.closed=false;this.length=Number(t.length)||Infinity;if(this.length!==Infinity){this.lastChunkLength=this.length%this.chunkLength||this.chunkLength;this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1}}r.prototype.put=function(e,t,r){if(this.closed)return n(r,new Error("Storage is closed"));var i=e===this.lastChunkIndex;if(i&&t.length!==this.lastChunkLength){return n(r,new Error("Last chunk length must be "+this.lastChunkLength))}if(!i&&t.length!==this.chunkLength){return n(r,new Error("Chunk length must be "+this.chunkLength))}this.chunks[e]=t;n(r,null)};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);if(this.closed)return n(r,new Error("Storage is closed"));var i=this.chunks[e];if(!i)return n(r,new Error("Chunk not found"));if(!t)return n(r,null,i);var s=t.offset||0;var o=t.length||i.length-s;n(r,null,i.slice(s,o+s))};r.prototype.close=r.prototype.destroy=function(e){if(this.closed)return n(e,new Error("Storage is closed"));this.closed=true;this.chunks=null;n(e,null)};function n(t,r,n){e.nextTick(function(){if(t)t(r,n)})}}).call(this,e("_process"))},{_process:83}],65:[function(e,t,r){var n=function(e,t,r){this._byteOffset=t||0;if(e instanceof ArrayBuffer){this.buffer=e}else if(typeof e=="object"){this.dataView=e;if(t){this._byteOffset+=t}}else{this.buffer=new ArrayBuffer(e||0)}this.position=0;this.endianness=r==null?n.LITTLE_ENDIAN:r};t.exports=n;n.prototype={};n.prototype.save=function(e){var t=new Blob([this.buffer]);var r=window.webkitURL||window.URL;if(r&&r.createObjectURL){var n=r.createObjectURL(t);var i=document.createElement("a");i.setAttribute("href",n);i.setAttribute("download",e);i.click();r.revokeObjectURL(n)}else{throw"DataStream.save: Can't create object URL."}};n.BIG_ENDIAN=false;n.LITTLE_ENDIAN=true;n.prototype._dynamicSize=true;Object.defineProperty(n.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(e){if(!e){this._trimAlloc()}this._dynamicSize=e}});n.prototype._byteLength=0;Object.defineProperty(n.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}});Object.defineProperty(n.prototype,"buffer",{get:function(){this._trimAlloc();return this._buffer},set:function(e){this._buffer=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(n.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(n.prototype,"dataView",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset;this._buffer=e.buffer;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._byteOffset+e.byteLength}});n.prototype._realloc=function(e){if(!this._dynamicSize){return}var t=this._byteOffset+this.position+e;var r=this._buffer.byteLength;if(t<=r){if(t>this._byteLength){this._byteLength=t}return}if(r<1){r=1}while(t>r){r*=2}var n=new ArrayBuffer(r);var i=new Uint8Array(this._buffer);var s=new Uint8Array(n,0,i.length);s.set(i);this.buffer=n;this._byteLength=t};n.prototype._trimAlloc=function(){if(this._byteLength==this._buffer.byteLength){return}var e=new ArrayBuffer(this._byteLength);var t=new Uint8Array(e);var r=new Uint8Array(this._buffer,0,t.length);t.set(r);this.buffer=e};n.prototype.shift=function(e){var t=new ArrayBuffer(this._byteLength-e);var r=new Uint8Array(t);var n=new Uint8Array(this._buffer,e,r.length);r.set(n);this.buffer=t;this.position-=e};n.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t};n.prototype.isEof=function(){return this.position>=this._byteLength};n.prototype.mapInt32Array=function(e,t){this._realloc(e*4);var r=new Int32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.mapInt16Array=function(e,t){this._realloc(e*2);var r=new Int16Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};n.prototype.mapInt8Array=function(e){this._realloc(e*1);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};n.prototype.mapUint32Array=function(e,t){this._realloc(e*4);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.mapUint16Array=function(e,t){this._realloc(e*2);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};n.prototype.mapUint8Array=function(e){this._realloc(e*1);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};n.prototype.mapFloat64Array=function(e,t){this._realloc(e*8);var r=new Float64Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*8;return r};n.prototype.mapFloat32Array=function(e,t){this._realloc(e*4);var r=new Float32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.readInt32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Int32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readInt16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Int16Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readInt8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Int8Array(e);n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};n.prototype.readUint32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Uint32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readUint16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Uint16Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readUint8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Uint8Array(e);n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};n.prototype.readFloat64Array=function(e,t){e=e==null?this.byteLength-this.position/8:e;var r=new Float64Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readFloat32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Float32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.writeInt32Array=function(e,t){this._realloc(e.length*4);if(e instanceof Int32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0){n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength);this.mapInt32Array(e.length,t)}else{for(var r=0;r0;n.memcpy=function(e,t,r,n,i){var s=new Uint8Array(e,t,i);var o=new Uint8Array(r,n,i);s.set(o)};n.arrayToNative=function(e,t){if(t==this.endianness){return e}else{return this.flipArrayEndianness(e)}};n.nativeToEndian=function(e,t){if(this.endianness==t){return e}else{return this.flipArrayEndianness(e)}};n.flipArrayEndianness=function(e){var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(var r=0;ri;n--,i++){var s=t[i];t[i]=t[n];t[n]=s}}return e};n.prototype.failurePosition=0;n.prototype.readStruct=function(e){var t={},r,n,i;var s=this.position;for(var o=0;o>16);this.writeUint8((e&65280)>>8);this.writeUint8(e&255)};n.prototype.adjustUint32=function(e,t){var r=this.position;this.seek(e);this.writeUint32(t);this.seek(r)}},{}],66:[function(e,t,r){var n=e("./DataStream");var s=e("./descriptor");var o=e("./log");var a={ERR_NOT_ENOUGH_DATA:0,OK:1,boxCodes:["mdat","avcC","hvcC","ftyp","payl","vmhd","smhd","hmhd","dref","elst"],fullBoxCodes:["mvhd","tkhd","mdhd","hdlr","smhd","hmhd","nhmd","url ","urn ","ctts","cslg","stco","co64","stsc","stss","stsz","stz2","stts","stsh","mehd","trex","mfhd","tfhd","trun","tfdt","esds","subs","txtC"],containerBoxCodes:[["moov",["trak"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl"],["mvex",["trex"]],["moof",["traf"]],["traf",["trun"]],["vttc"],["tref"]],sampleEntryCodes:[{prefix:"Visual",types:["mp4v","avc1","avc2","avc3","avc4","avcp","drac","encv","mjp2","mvc1","mvc2","resv","s263","svc1","vc-1","hvc1","hev1"]},{prefix:"Audio",types:["mp4a","ac-3","alac","dra1","dtsc","dtse",,"dtsh","dtsl","ec-3","enca","g719","g726","m4ae","mlpa","raw ","samr","sawb","sawp","sevc","sqcp","ssmv","twos"]},{prefix:"Hint",types:["fdp ","m2ts","pm2t","prtp","rm2t","rrtp","rsrp","rtp ","sm2t","srtp"]},{prefix:"Metadata",types:["metx","mett","urim"]},{prefix:"Subtitle",types:["stpp","wvtt","sbtt","tx3g","stxt"]}],trackReferenceTypes:["scal"],initialize:function(){var e,t;var r;a.FullBox.prototype=new a.Box;a.ContainerBox.prototype=new a.Box;a.stsdBox.prototype=new a.FullBox;a.SampleEntry.prototype=new a.FullBox;a.TrackReferenceTypeBox.prototype=new a.Box;r=a.boxCodes.length;for(e=0;ee.byteLength){e.seek(n);o.w("BoxParser",'Not enough data in stream to parse the entire "'+f+'" box');return{code:a.ERR_NOT_ENOUGH_DATA,type:f,size:s,hdr_size:i}}if(a[f+"Box"]){r=new a[f+"Box"](s-i)}else{if(t){r=new a.SampleEntry(f,s-i)}else{r=new a.Box(f,s-i)}}r.hdr_size=i;r.start=n;r.fileStart=n+e.buffer.fileStart;r.parse(e);e.seek(n+s);return{code:a.OK,box:r,size:s}}};t.exports=a;a.initialize();a.Box.prototype.parse=function(e){if(this.type!="mdat"){this.data=e.readUint8Array(this.size)}else{e.seek(this.start+this.size+this.hdr_size)}};a.FullBox.prototype.parseFullHeader=function(e){this.version=e.readUint8();this.flags=e.readUint24();this.size-=4};a.ContainerBox.prototype.parse=function(e){var t;var r;var n;n=e.position;while(e.position=4){this.compatible_brands[t]=e.readString(4);this.size-=4;t++}};a.mvhdBox.prototype.parse=function(e){this.flags=0;this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.rate=e.readUint32();this.volume=e.readUint16()>>8;e.readUint16();e.readUint32Array(2);this.matrix=e.readUint32Array(9);e.readUint32Array(6);this.next_track_id=e.readUint32()};a.TKHD_FLAG_ENABLED=1;a.TKHD_FLAG_IN_MOVIE=2;a.TKHD_FLAG_IN_PREVIEW=4;a.tkhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint32()}e.readUint32Array(2);this.layer=e.readInt16();this.alternate_group=e.readInt16();this.volume=e.readInt16()>>8;e.readUint16();this.matrix=e.readInt32Array(9);this.width=e.readUint32();this.height=e.readUint32()};a.mdhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.language=e.readUint16();var t=[];t[0]=this.language>>10&31;t[1]=this.language>>5&31;t[2]=this.language&31;this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96);e.readUint16()};a.hdlrBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version===0){e.readUint32();this.handler=e.readString(4);e.readUint32Array(3);this.name=e.readCString()}else{this.data=e.readUint8Array(size)}};a.stsdBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);r=e.readUint32();for(i=1;i<=r;i++){t=a.parseOneBox(e,true);this.entries.push(t.box)}};a.avcCBox.prototype.parse=function(e){var t;var r;var n;this.configurationVersion=e.readUint8();this.AVCProfileIndication=e.readUint8();this.profile_compatibility=e.readUint8();this.AVCLevelIndication=e.readUint8();this.lengthSizeMinusOne=e.readUint8()&3;r=e.readUint8()&31;this.size-=6;this.SPS=new Array(r);for(t=0;t0){this.ext=e.readUint8Array(this.size)}};a.hvcCBox.prototype.parse=function(e){var t;var r;var n;var i;this.configurationVersion=e.readUint8();i=e.readUint8();this.general_profile_space=i>>6;this.general_tier_flag=(i&32)>>5;this.general_profile_idc=i&31;this.general_profile_compatibility=e.readUint32();this.general_constraint_indicator=e.readUint8Array(6);this.general_level_idc=e.readUint8();this.min_spatial_segmentation_idc=e.readUint16()&4095;this.parallelismType=e.readUint8()&3;this.chromaFormat=e.readUint8()&3;this.bitDepthLumaMinus8=e.readUint8()&7;this.bitDepthChromaMinus8=e.readUint8()&7;this.avgFrameRate=e.readUint16();i=e.readUint8();this.constantFrameRate=i>>6;this.numTemporalLayers=(i&13)>>3;this.temporalIdNested=(i&4)>>2;this.lengthSizeMinusOne=i&3;this.nalu_arrays=[];numOfArrays=e.readUint8();for(t=0;t>7;s.nalu_type=i&63;numNalus=e.readUint16();for(j=0;j>=1}t+=f(n,0);t+=".";if(this.hvcC.general_tier_flag===0){t+="L"}else{t+="H"}t+=this.hvcC.general_level_idc;var i=false;var s="";for(e=5;e>=0;e--){if(this.hvcC.general_constraint_indicator[e]||i){s="."+f(this.hvcC.general_constraint_indicator[e],0)+s;i=true}}t+=s}return t};a.mp4aBox.prototype.getCodec=function(){var e=a.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var t=this.esds.esd.getOTI();var r=this.esds.esd.getAudioConfig();return e+"."+f(t)+(r?"."+r:"")}else{return e}};a.esdsBox.prototype.parse=function(e){this.parseFullHeader(e);this.data=e.readUint8Array(this.size);this.size=0;var t=new s;this.esd=t.parseOneDescriptor(new n(this.data.buffer,0,n.BIG_ENDIAN))};a.txtCBox.prototype.parse=function(e){this.parseFullHeader(e);this.config=e.readCString()};a.cttsBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);t=e.readUint32();this.sample_counts=[];this.sample_offsets=[];if(this.version===0){for(r=0;rt&&this.flags&a.TFHD_FLAG_BASE_DATA_OFFSET){this.base_data_offset=e.readUint64();t+=8}else{this.base_data_offset=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_DESC){this.default_sample_description_index=e.readUint32();t+=4}else{this.default_sample_description_index=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_DUR){this.default_sample_duration=e.readUint32();t+=4}else{this.default_sample_duration=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_SIZE){this.default_sample_size=e.readUint32();t+=4}else{this.default_sample_size=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_FLAGS){this.default_sample_flags=e.readUint32();t+=4}else{this.default_sample_flags=0}};a.TRUN_FLAGS_DATA_OFFSET=1;a.TRUN_FLAGS_FIRST_FLAG=4;a.TRUN_FLAGS_DURATION=256;a.TRUN_FLAGS_SIZE=512;a.TRUN_FLAGS_FLAGS=1024;a.TRUN_FLAGS_CTS_OFFSET=2048;a.trunBox.prototype.parse=function(e){var t=0;this.parseFullHeader(e);this.sample_count=e.readUint32();t+=4;if(this.size>t&&this.flags&a.TRUN_FLAGS_DATA_OFFSET){this.data_offset=e.readInt32();t+=4}else{this.data_offset=0}if(this.size>t&&this.flags&a.TRUN_FLAGS_FIRST_FLAG){this.first_sample_flags=e.readUint32();t+=4}else{this.first_sample_flags=0}this.sample_duration=[];this.sample_size=[];this.sample_flags=[];this.sample_composition_time_offset=[];if(this.size>t){for(var r=0;r0){for(r=0;rn.MAX_SIZE){this.size+=8}o.d("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.position+(t||""));if(this.size>n.MAX_SIZE){e.writeUint32(1)}else{this.sizePosition=e.position;e.writeUint32(this.size)}e.writeString(this.type,null,4);if(this.size>n.MAX_SIZE){e.writeUint64(this.size)}};a.FullBox.prototype.writeHeader=function(e){this.size+=4;a.Box.prototype.writeHeader.call(this,e," v="+this.version+" f="+this.flags);e.writeUint8(this.version);e.writeUint24(this.flags)};a.Box.prototype.write=function(e){if(this.type==="mdat"){if(this.data){this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}}else{this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}};a.ContainerBox.prototype.write=function(e){this.size=0;this.writeHeader(e);for(var t=0;t>3}else{return null}};a.DecoderConfigDescriptor=function(e){a.Descriptor.call(this,t,e)};a.DecoderConfigDescriptor.prototype=new a.Descriptor;a.DecoderConfigDescriptor.prototype.parse=function(e){this.oti=e.readUint8();this.streamType=e.readUint8();this.bufferSize=e.readUint24();this.maxBitrate=e.readUint32();this.avgBitrate=e.readUint32();this.size-=13;this.parseRemainingDescriptors(e)};a.DecoderSpecificInfo=function(e){a.Descriptor.call(this,r,e)};a.DecoderSpecificInfo.prototype=new a.Descriptor;a.SLConfigDescriptor=function(e){a.Descriptor.call(this,i,e)};a.SLConfigDescriptor.prototype=new a.Descriptor;return this};t.exports=i},{"./log":69}],68:[function(e,t,r){var n=e("./box");var i=e("./DataStream");var s=e("./log");var o=function(e){this.stream=e;this.boxes=[];this.mdats=[];this.moofs=[];this.isProgressive=false;this.lastMoofIndex=0;this.lastBoxStartPosition=0;this.parsingMdat=null;this.moovStartFound=false;this.samplesDataSize=0;this.nextParsePosition=0};t.exports=o;o.prototype.mergeNextBuffer=function(){var e;if(this.stream.bufferIndex+1"+this.stream.buffer.byteLength+")");return true}else{return false}}else{return false}};o.prototype.parse=function(){var e;var t;var r;s.d("ISOFile","Starting parsing with buffer #"+this.stream.bufferIndex+" (fileStart: "+this.stream.buffer.fileStart+" - Length: "+this.stream.buffer.byteLength+") from position "+this.lastBoxStartPosition+" ("+(this.stream.buffer.fileStart+this.lastBoxStartPosition)+" in the file)");this.stream.seek(this.lastBoxStartPosition);while(true){if(this.parsingMdat!==null){r=this.parsingMdat;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){s.d("ISOFile","Found 'mdat' end in buffer #"+this.stream.bufferIndex);this.parsingMdat=null;continue}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex);return}}else{this.lastBoxStartPosition=this.stream.position;t=n.parseOneBox(this.stream);if(t.code===n.ERR_NOT_ENOUGH_DATA){if(t.type==="mdat"){r=new n[t.type+"Box"](t.size-t.hdr_size);this.parsingMdat=r;this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+this.stream.position;r.hdr_size=t.hdr_size;this.stream.buffer.usedBytes+=t.hdr_size;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){this.parsingMdat=null;continue}else{if(!this.moovStartFound){this.nextParsePosition=r.fileStart+r.size+r.hdr_size}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex)}return}}else{if(t.type==="moov"){this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}}else if(t.type==="free"){e=this.reposition(false,this.stream.buffer.fileStart+this.stream.position+t.size);if(e){continue}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size;return}}merged=this.mergeNextBuffer();if(merged){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength;continue}else{if(!t.type){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{if(this.moovStartFound){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size}}return}}}else{r=t.box;this.boxes.push(r);switch(r.type){case"mdat":this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+r.start;break;case"moof":this.moofs.push(r);break;case"moov":this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}default:if(this[r.type]!==undefined){s.w("ISOFile","Duplicate Box of type: "+r.type+", overriding previous occurrence")}this[r.type]=r;break}if(r.type==="mdat"){this.stream.buffer.usedBytes+=r.hdr_size}else{this.stream.buffer.usedBytes+=t.size}}}}};o.prototype.reposition=function(e,t){var r;r=this.findPosition(e,t);if(r!==-1){this.stream.buffer=this.stream.nextBuffers[r];this.stream.bufferIndex=r;this.stream.position=t-this.stream.buffer.fileStart;s.d("ISOFile","Repositioning parser at buffer position: "+this.stream.position);return true}else{return false}};o.prototype.findPosition=function(e,t){var r;var n=null;var i=-1;if(e===true){r=0}else{r=this.stream.bufferIndex}while(r=t){s.d("ISOFile","Found position in existing buffer #"+i);return i}else{return-1}}else{return-1}};o.prototype.findEndContiguousBuf=function(e){var t;var r;var n;r=this.stream.nextBuffers[e];if(this.stream.nextBuffers.length>e+1){for(t=e+1;t-1){this.moov.boxes.splice(r,1)}this.moov.mvex=null}this.moov.mvex=new n.mvexBox;this.moov.boxes.push(this.moov.mvex);this.moov.mvex.mehd=new n.mehdBox;this.moov.mvex.boxes.push(this.moov.mvex.mehd);this.moov.mvex.mehd.fragment_duration=this.initial_duration;for(t=0;t0?this.moov.traks[t].samples[0].duration:0;o.default_sample_size=0;o.default_sample_flags=1<<16}this.moov.write(e)};o.prototype.resetTables=function(){var e;var t,r,n,i,s,o,a,f;this.initial_duration=this.moov.mvhd.duration;this.moov.mvhd.duration=0;for(e=0;eg){_++;if(g<0){g=0}g+=a.sample_counts[_]}if(t>0){n.samples[t-1].duration=a.sample_deltas[_];x.dts=n.samples[t-1].dts+n.samples[t-1].duration}else{x.dts=0}if(f){if(t>y){b++;y+=f.sample_counts[b]}x.cts=n.samples[t].dts+f.sample_offsets[b]}else{x.cts=x.dts}if(u){if(t==u.sample_numbers[w]-1){x.is_rap=true;w++}else{x.is_rap=false}}else{x.is_rap=true}if(l){if(l.samples[subs_entry_index].sample_delta+last_subs_sample_index==t){x.subsamples=l.samples[subs_entry_index].subsamples;last_subs_sample_index+=l.samples[subs_entry_index].sample_delta}}}if(t>0)n.samples[t-1].duration=n.mdia.mdhd.duration-n.samples[t-1].dts}};o.prototype.updateSampleLists=function(){var e,t,r;var i,s,o,a;var f;var u,h,l,c,d;var p;while(this.lastMoofIndex0){p.dts=c.samples[c.samples.length-2].dts+c.samples[c.samples.length-2].duration}else{if(l.tfdt){p.dts=l.tfdt.baseMediaDecodeTime}else{p.dts=0}c.first_traf_merged=true}p.cts=p.dts;if(m.flags&n.TRUN_FLAGS_CTS_OFFSET){p.cts=p.dts+m.sample_composition_time_offset[r]}sample_flags=a;if(m.flags&n.TRUN_FLAGS_FLAGS){sample_flags=m.sample_flags[r]}else if(r===0&&m.flags&n.TRUN_FLAGS_FIRST_FLAG){sample_flags=m.first_sample_flags}p.is_rap=sample_flags>>16&1?false:true;var v=l.tfhd.flags&n.TFHD_FLAG_BASE_DATA_OFFSET?true:false;var g=l.tfhd.flags&n.TFHD_FLAG_DEFAULT_BASE_IS_MOOF?true:false;var _=m.flags&n.TRUN_FLAGS_DATA_OFFSET?true:false;var y=0;if(!v){if(!g){if(t===0){y=h.fileStart}else{y=f}}else{y=h.fileStart}}else{y=l.tfhd.base_data_offset}if(t===0&&r===0){if(_){p.offset=y+m.data_offset}else{p.offset=y}}else{p.offset=f}f=p.offset+p.size}}if(l.subs){var b=l.first_sample_index;for(t=0;t0){t+=","}t+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return t};o.prototype.getTrexById=function(e){var t;if(!this.originalMvex)return null;for(t=0;t=r.fileStart&&o.offset+o.alreadyRead=o){console.debug("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},i:function(t,r){if(i>=o){console.info("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},w:function(t,i){if(r>=o){console.warn("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",i)}},e:function(r,i){if(t>=o){console.error("["+n.getDurationString(new Date-e,1e3)+"]","["+r+"]",i)}}};return a}();t.exports=n;n.getDurationString=function(e,t){function r(e,t){var r=""+e;var n=r.split(".");while(n[0].length0){var r="";for(var i=0;i0)r+=",";r+="["+n.getDurationString(e.start(i))+","+n.getDurationString(e.end(i))+"]"}return r}else{return"(empty)"}}},{}],70:[function(e,t,r){var n=e("./box");var s=e("./DataStream");var o=e("./isofile");var a=e("./log");var f=function(){this.inputStream=null;this.nextBuffers=[];this.inputIsoFile=null;this.onMoovStart=null;this.moovStartSent=false;this.onReady=null;this.readySent=false;this.onSegment=null;this.onSamples=null;this.onError=null;this.sampleListBuilt=false;this.fragmentedTracks=[];this.extractedTracks=[];this.isFragmentationStarted=false;this.nextMoofNumber=0};t.exports=f;f.prototype.setSegmentOptions=function(e,t,r){var n=this.inputIsoFile.getTrackById(e);if(n){var i={};this.fragmentedTracks.push(i);i.id=e;i.user=t;i.trak=n;n.nextSample=0;i.segmentStream=null;i.nb_samples=1e3;i.rapAlignement=true;if(r){if(r.nbSamples)i.nb_samples=r.nbSamples;if(r.rapAlignement)i.rapAlignement=r.rapAlignement}}};f.prototype.unsetSegmentOptions=function(e){var t=-1;for(var r=0;r-1){this.fragmentedTracks.splice(t,1)}};f.prototype.setExtractionOptions=function(e,t,r){var n=this.inputIsoFile.getTrackById(e);if(n){var i={};this.extractedTracks.push(i);i.id=e;i.user=t;i.trak=n;n.nextSample=0;i.nb_samples=1e3;i.samples=[];if(r){if(r.nbSamples)i.nb_samples=r.nbSamples}}};f.prototype.unsetExtractionOptions=function(e){var t=-1;for(var r=0;r-1){this.extractedTracks.splice(t,1)}};f.prototype.createSingleSampleMoof=function(e){var t=new n.moofBox;var r=new n.mfhdBox;r.sequence_number=this.nextMoofNumber;this.nextMoofNumber++;t.boxes.push(r);var i=new n.trafBox;t.boxes.push(i);var s=new n.tfhdBox;i.boxes.push(s);s.track_id=e.track_id;s.flags=n.TFHD_FLAG_DEFAULT_BASE_IS_MOOF;var o=new n.tfdtBox;i.boxes.push(o);o.baseMediaDecodeTime=e.dts;var a=new n.trunBox;i.boxes.push(a);t.trun=a;a.flags=n.TRUN_FLAGS_DATA_OFFSET|n.TRUN_FLAGS_DURATION|n.TRUN_FLAGS_SIZE|n.TRUN_FLAGS_FLAGS|n.TRUN_FLAGS_CTS_OFFSET;a.data_offset=0;a.first_sample_flags=0;a.sample_count=1;a.sample_duration=[];a.sample_duration[0]=e.duration;a.sample_size=[];a.sample_size[0]=e.size;a.sample_flags=[];a.sample_flags[0]=0;a.sample_composition_time_offset=[];a.sample_composition_time_offset[0]=e.cts-e.dts;return t};f.prototype.createFragment=function(e,t,r,i){var o=this.inputIsoFile.getTrackById(t);var f=this.inputIsoFile.getSample(o,r);if(f==null){if(this.nextSeekPosition){this.nextSeekPosition=Math.min(o.samples[r].offset,this.nextSeekPosition)}else{this.nextSeekPosition=o.samples[r].offset}return null}var u=i||new s;u.endianness=s.BIG_ENDIAN;var h=this.createSingleSampleMoof(f);h.write(u);h.trun.data_offset=h.size+8;a.d("BoxWriter","Adjusting data_offset with new value "+h.trun.data_offset);u.adjustUint32(h.trun.data_offset_position,h.trun.data_offset);var l=new n.mdatBox;l.data=f.data;l.write(u);return u};ArrayBuffer.concat=function(e,t){a.d("ArrayBuffer","Trying to create a new buffer of size: "+(e.byteLength+t.byteLength));var r=new Uint8Array(e.byteLength+t.byteLength);r.set(new Uint8Array(e),0);r.set(new Uint8Array(t),e.byteLength);return r.buffer};f.prototype.reduceBuffer=function(e,t,r){var n;n=new Uint8Array(r);n.set(new Uint8Array(e,t,r));n.buffer.fileStart=e.fileStart+t;n.buffer.usedBytes=0;return n.buffer};f.prototype.insertBuffer=function(e){var t=true;for(var r=0;rn.byteLength){this.nextBuffers.splice(r,1);r--;continue}else{a.w("MP4Box","Buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+") already appended, ignoring")}}else{if(e.fileStart+e.byteLength<=n.fileStart){}else{e=this.reduceBuffer(e,0,n.fileStart-e.fileStart)}a.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.splice(r,0,e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}t=false;break}else if(e.fileStart0){e=this.reduceBuffer(e,i,s)}else{t=false;break}}}if(t){a.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.push(e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}};f.prototype.processSamples=function(){var e;var t;if(this.isFragmentationStarted&&this.onSegment!==null){for(e=0;e=t.samples.length){a.i("MP4Box","Sending fragmented data on track #"+r.id+" for samples ["+(t.nextSample-r.nb_samples)+","+(t.nextSample-1)+"]");if(this.onSegment){this.onSegment(r.id,r.user,r.segmentStream.buffer,t.nextSample)}r.segmentStream=null;if(r!==this.fragmentedTracks[e]){break}}}}}if(this.onSamples!==null){for(e=0;e=t.samples.length){a.d("MP4Box","Sending samples on track #"+i.id+" for sample "+t.nextSample);if(this.onSamples){this.onSamples(i.id,i.user,i.samples)}i.samples=[];if(i!==this.extractedTracks[e]){break}}}}}};f.prototype.appendBuffer=function(e){var t;var r;if(e===null||e===undefined){throw"Buffer must be defined and non empty"}if(e.fileStart===undefined){throw"Buffer must have a fileStart property"}if(e.byteLength===0){a.w("MP4Box","Ignoring empty buffer (fileStart: "+e.fileStart+")");return}e.usedBytes=0;this.insertBuffer(e);if(!this.inputStream){if(this.nextBuffers.length>0){r=this.nextBuffers[0];if(r.fileStart===0){this.inputStream=new s(r,0,s.BIG_ENDIAN);this.inputStream.nextBuffers=this.nextBuffers;this.inputStream.bufferIndex=0}else{a.w("MP4Box","The first buffer should have a fileStart of 0");return}}else{a.w("MP4Box","No buffer to start parsing from");return}}if(!this.inputIsoFile){this.inputIsoFile=new o(this.inputStream)}this.inputIsoFile.parse();if(this.inputIsoFile.moovStartFound&&!this.moovStartSent){this.moovStartSent=true;if(this.onMoovStart)this.onMoovStart()}if(this.inputIsoFile.moov){if(!this.sampleListBuilt){this.inputIsoFile.buildSampleLists();this.sampleListBuilt=true}this.inputIsoFile.updateSampleLists();if(this.onReady&&!this.readySent){var n=this.getInfo();this.readySent=true;this.onReady(n)}this.processSamples();if(this.nextSeekPosition){t=this.nextSeekPosition;this.nextSeekPosition=undefined}else{t=this.inputIsoFile.nextParsePosition}var i=this.inputIsoFile.findPosition(true,t);if(i!==-1){t=this.inputIsoFile.findEndContiguousBuf(i)}a.i("MP4Box","Next buffer to fetch should have a fileStart position of "+t);return t}else{if(this.inputIsoFile!==null){return this.inputIsoFile.nextParsePosition}else{return 0}}};f.prototype.getInfo=function(){var e={};var t;var r;var n;var s=new Date(4,0,1,0,0,0,0).getTime();e.duration=this.inputIsoFile.moov.mvhd.duration;e.timescale=this.inputIsoFile.moov.mvhd.timescale;e.isFragmented=this.inputIsoFile.moov.mvex!=null;if(e.isFragmented&&this.inputIsoFile.moov.mvex.mehd){e.fragment_duration=this.inputIsoFile.moov.mvex.mehd.fragment_duration}else{e.fragment_duration=0}e.isProgressive=this.inputIsoFile.isProgressive;e.hasIOD=this.inputIsoFile.moov.iods!=null;e.brands=[];e.brands.push(this.inputIsoFile.ftyp.major_brand);e.brands=e.brands.concat(this.inputIsoFile.ftyp.compatible_brands);e.created=new Date(s+this.inputIsoFile.moov.mvhd.creation_time*1e3);e.modified=new Date(s+this.inputIsoFile.moov.mvhd.modification_time*1e3);e.tracks=[];e.audioTracks=[];e.videoTracks=[];e.subtitleTracks=[];e.metadataTracks=[];e.hintTracks=[];e.otherTracks=[];for(i=0;ie*i.timescale){f=r.samples[n-1].offset;h=n-1;break}if(t&&i.is_rap){s=i.offset;o=i.cts;u=n}}if(t){r.nextSample=u;a.i("MP4Box","Seeking to RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+a.getDurationString(o,l)+" and offset: "+s);return{offset:s,time:o/l}}else{r.nextSample=h;a.i("MP4Box","Seeking to non-RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+a.getDurationString(e)+" and offset: "+s);return{offset:f,time:e}}};f.prototype.seek=function(e,t){var r=this.inputIsoFile.moov;var n;var i;var s;var o={offset:Infinity,time:Infinity};if(!this.inputIsoFile.moov){throw"Cannot seek: moov not received!"}else{for(s=0;s1e4)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);var f=(t[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return r*a;case"days":case"day":case"d":return r*o;case"hours":case"hour":case"hrs":case"hr":case"h":return r*s;case"minutes":case"minute":case"mins":case"min":case"m":return r*i;case"seconds":case"second":case"secs":case"sec":case"s":return r*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r}}function u(e){if(e>=o)return Math.round(e/o)+"d";if(e>=s)return Math.round(e/s)+"h";if(e>=i)return Math.round(e/i)+"m";if(e>=n)return Math.round(e/n)+"s";return e+"ms"}function h(e){return l(e,o,"day")||l(e,s,"hour")||l(e,i,"minute")||l(e,n,"second")||e+" ms"}function l(e,t,r){if(e0?[e["url-list"]]:[]}t.urlList=(e["url-list"]||[]).map(function(e){return e.toString()});var a=e.info.files||[e.info];t.files=a.map(function(e,r){var n=[].concat(t.name,e["path.utf-8"]||e.path||[]).map(function(e){return e.toString()});return{path:i.join.apply(null,[i.sep].concat(n)).slice(1),name:n[n.length-1],length:e.length,offset:a.slice(0,r).reduce(u,0)}});t.length=a.reduce(u,0);var f=t.files[t.files.length-1];t.pieceLength=e.info["piece length"];t.lastPieceLength=(f.offset+f.length)%t.pieceLength||t.pieceLength;t.pieces=h(e.info.pieces);return t}function f(e){var t={info:e.info};t["announce-list"]=e.announce.map(function(e){if(!t.announce)t.announce=e;e=new r(e,"utf8");return[e]});if(e.created){t["creation date"]=e.created.getTime()/1e3|0}if(e.urlList){t["url-list"]=e.urlList}return n.encode(t)}function u(e,t){return e+t.length}function h(e){var t=[];for(var r=0;r=0;n--){var i=e[n];if(i==="."){e.splice(n,1)}else if(i===".."){e.splice(n,1);r++}else if(r){e.splice(n,1);r--}}if(t){for(;r--;r){e.unshift("..")}}return e}var n=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var i=function(e){return n.exec(e).slice(1)};r.resolve=function(){var r="",n=false;for(var i=arguments.length-1;i>=-1&&!n;i--){var o=i>=0?arguments[i]:e.cwd();if(typeof o!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!o){continue}r=o+"/"+r;n=o.charAt(0)==="/"}r=t(s(r.split("/"),function(e){return!!e}),!n).join("/");return(n?"/":"")+r||"."};r.normalize=function(e){var n=r.isAbsolute(e),i=o(e,-1)==="/";e=t(s(e.split("/"),function(e){return!!e}),!n).join("/");if(!e&&!n){e="."}if(e&&i){e+="/"}return(n?"/":"")+e};r.isAbsolute=function(e){return e.charAt(0)==="/"};r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(s(e,function(e,t){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))};r.relative=function(e,t){e=r.resolve(e).substr(1);t=r.resolve(t).substr(1);function n(e){var t=0;for(;t=0;r--){if(e[r]!=="")break}if(t>r)return[];return e.slice(t,r-t+1)}var i=n(e.split("/"));var s=n(t.split("/"));var o=Math.min(i.length,s.length);var a=o;for(var f=0;f1){for(var r=1;r0;return h(i,o,a,function(e){if(!r)r=e;if(e)n.forEach(l);if(o)return;n.forEach(l);t(r)})});return e.reduce(c)};t.exports=d},{"end-of-stream":46,fs:35,once:73}],85:[function(t,r,n){(function(t){(function(i){var s=typeof n=="object"&&n&&!n.nodeType&&n;var o=typeof r=="object"&&r&&!r.nodeType&&r;var a=typeof t=="object"&&t;if(a.global===a||a.window===a||a.self===a){i=a}var f,u=2147483647,h=36,l=1,c=26,d=38,p=700,m=72,v=128,g="-",_=/^xn--/,y=/[^\x20-\x7E]/,b=/[\x2E\u3002\uFF0E\uFF61]/g,w={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},S=h-l,x=Math.floor,k=String.fromCharCode,E;function A(e){throw RangeError(w[e])}function U(e,t){var r=e.length;var n=[];while(r--){n[r]=t(e[r])}return n}function T(e,t){var r=e.split("@");var n="";if(r.length>1){n=r[0]+"@";e=r[1]}e=e.replace(b,".");var i=e.split(".");var s=U(i,t).join(".");return n+s}function I(e){var t=[],r=0,n=e.length,i,s;while(r=55296&&i<=56319&&r65535){e-=65536;t+=k(e>>>10&1023|55296);e=56320|e&1023}t+=k(e);return t}).join("")}function B(e){if(e-48<10){return e-22}if(e-65<26){return e-65}if(e-97<26){return e-97}return h}function C(e,t){return e+22+75*(e<26)-((t!=0)<<5)}function R(e,t,r){var n=0;e=r?x(e/p):e>>1;e+=x(e/t);for(;e>S*c>>1;n+=h){e=x(e/S)}return x(n+(S+1)*e/(e+d))}function P(e){var t=[],r=e.length,n,i=0,s=v,o=m,a,f,d,p,_,y,b,w,S;a=e.lastIndexOf(g);if(a<0){a=0}for(f=0;f=128){A("not-basic")}t.push(e.charCodeAt(f))}for(d=a>0?a+1:0;d=r){A("invalid-input")}b=B(e.charCodeAt(d++));if(b>=h||b>x((u-i)/_)){A("overflow")}i+=b*_;w=y<=o?l:y>=o+c?c:y-o;if(bx(u/S)){A("overflow")}_*=S}n=t.length+1;o=R(i-p,n,p==0);if(x(i/n)>u-s){A("overflow")}s+=x(i/n);i%=n;t.splice(i++,0,s)}return L(t)}function F(e){var t,r,n,i,s,o,a,f,d,p,_,y=[],b,w,S,E;e=I(e);b=e.length;t=v;r=0;s=m;for(o=0;o=t&&_x((u-r)/w)){A("overflow")}r+=(a-t)*w;t=a;for(o=0;ou){A("overflow")}if(_==t){for(f=r,d=h;;d+=h){p=d<=s?l:d>=s+c?c:d-s;if(f0&&u>f){u=f}for(var h=0;h=0){d=l.substr(0,c);p=l.substr(c+1)}else{d=l;p=""}m=decodeURIComponent(d);v=decodeURIComponent(p);if(!n(o,m)){o[m]=v}else if(i(o[m])){o[m].push(v)}else{o[m]=[o[m],v]}}return o};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}},{}],87:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,a){t=t||"&";r=r||"=";if(e===null){e=undefined}if(typeof e==="object"){return s(o(e),function(o){var a=encodeURIComponent(n(o))+r;if(i(e[o])){return s(e[o],function(e){return a+encodeURIComponent(n(e))}).join(t)}else{return a+encodeURIComponent(n(e[o]))}}).join(t)}if(!a)return"";return encodeURIComponent(n(a))+r+encodeURIComponent(n(e))};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};function s(e,t){if(e.map)return e.map(t);var r=[];for(var n=0;n0){if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var o=new Error("stream.unshift() after end event");e.emit("error",o)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)S(e)}k(e,t)}}else if(!i){t.reading=false}return v(t)}function v(e){return!e.ended&&(e.needReadable||e.length=g){e=g}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function y(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(e===null||isNaN(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=_(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else{return t.length}}return e}p.prototype.read=function(e){l("read",e);var t=this._readableState;var r=e;if(typeof e!=="number"||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){l("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)C(this);else S(this);return null}e=y(e,t);if(e===0&&t.ended){if(t.length===0)C(this);return null}var n=t.needReadable;l("need readable",n);if(t.length===0||t.length-e0)i=B(e,t);else i=null;if(i===null){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)C(this);if(i!==null)this.emit("data",i);return i};function b(e,t){var r=null;if(!s.isBuffer(t)&&typeof t!=="string"&&t!==null&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function w(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;S(e)}function S(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){l("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)n(x,e);else x(e)}}function x(e){l("emit readable");e.emit("readable");L(e)}function k(e,t){if(!t.readingMore){t.readingMore=true;n(E,e,t)}}function E(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(i)a=r.join("");else if(r.length===1)a=r[0];else a=s.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;n(R,t,e)}}function R(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function P(e,t){for(var r=0,n=e.length;r-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e};function p(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=new i(t,r)}return t}function m(e,t,r,n,s){r=p(t,r,n);if(i.isBuffer(r))n="buffer";var o=t.objectMode?1:r.length;t.length+=o;var a=t.length0;e+=1);return e};var o=function(e,t){for(var r=t>>2;r>2]|=128<<24-(t%4<<3);e[((t>>2)+2&~15)+14]=r>>29;e[((t>>2)+2&~15)+15]=r<<3};var f=function(e,t,r,n,i){var s=this,o,a=i%4,f=n%4,u=n-f;if(u>0){switch(a){case 0:e[i+3|0]=s.charCodeAt(r);case 1:e[i+2|0]=s.charCodeAt(r+1);case 2:e[i+1|0]=s.charCodeAt(r+2);case 3:e[i|0]=s.charCodeAt(r+3)}}for(o=a;o>2]=s.charCodeAt(r+o)<<24|s.charCodeAt(r+o+1)<<16|s.charCodeAt(r+o+2)<<8|s.charCodeAt(r+o+3)}switch(f){case 3:e[i+u+1|0]=s.charCodeAt(r+u+2);case 2:e[i+u+2|0]=s.charCodeAt(r+u+1);case 1:e[i+u+3|0]=s.charCodeAt(r+u)}};var u=function(e,t,r,n,i){var s=this,o,a=i%4,f=n%4,u=n-f;if(u>0){switch(a){case 0:e[i+3|0]=s[r];case 1:e[i+2|0]=s[r+1];case 2:e[i+1|0]=s[r+2];case 3:e[i|0]=s[r+3]}}for(o=4-a;o>2]=s[r+o]<<24|s[r+o+1]<<16|s[r+o+2]<<8|s[r+o+3]}switch(f){case 3:e[i+u+1|0]=s[r+u+2];case 2:e[i+u+2|0]=s[r+u+1];case 1:e[i+u+3|0]=s[r+u]}};var h=function(e,t,r,n,s){var o=this,a,f=s%4,u=n%4,h=n-u;var l=new Uint8Array(i.readAsArrayBuffer(o.slice(r,r+n)));if(h>0){switch(f){case 0:e[s+3|0]=l[0];case 1:e[s+2|0]=l[1];case 2:e[s+1|0]=l[2];case 3:e[s|0]=l[3]}}for(a=4-f;a>2]=l[a]<<24|l[a+1]<<16|l[a+2]<<8|l[a+3]}switch(u){case 3:e[s+h+1|0]=l[h+2];case 2:e[s+h+2|0]=l[h+1];case 1:e[s+h+3|0]=l[h]}};var l=function(e){switch(r.getDataType(e)){case"string":return f.bind(e);case"array":return u.bind(e);case"buffer":return u.bind(e);case"arraybuffer":return u.bind(new Uint8Array(e));case"view":return u.bind(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));case"blob":return h.bind(e)}};var c=function(e,t){switch(r.getDataType(e)){case"string":return e.slice(t);case"array":return e.slice(t);case"buffer":return e.slice(t);case"arraybuffer":return e.slice(t);case"view":return e.buffer.slice(t)}};var d=function(e){var t,r,n="0123456789abcdef",i=[],s=new Uint8Array(e);for(t=0;t>4&15)+n.charAt(r>>0&15)}return i.join("")};var p=function(e){var t;if(e<=65536)return 65536;if(e<16777216){for(t=1;t0){throw new Error("Chunk size must be a multiple of 128 bit")}t.maxChunkLen=e;t.padMaxChunkLen=s(e);t.heap=new ArrayBuffer(p(t.padMaxChunkLen+320+20));t.h32=new Int32Array(t.heap);t.h8=new Int8Array(t.heap);t.core=new n._core({Int32Array:Int32Array,DataView:DataView},{},t.heap);t.buffer=null};m(e||64*1024);var v=function(e,t){var r=new Int32Array(e,t+320,5);r[0]=1732584193;r[1]=-271733879;r[2]=-1732584194;r[3]=271733878;r[4]=-1009589776};var g=function(e,r){ +var n=s(e);var i=new Int32Array(t.heap,0,n>>2);o(i,e);a(i,e,r);return n};var _=function(e,r,n){l(e)(t.h8,t.h32,r,n,0)};var y=function(e,r,n,i,s){var o=n;if(s){o=g(n,i)}_(e,r,n);t.core.hash(o,t.padMaxChunkLen)};var b=function(e,t){var r=new Int32Array(e,t+320,5);var n=new Int32Array(5);var i=new DataView(n.buffer);i.setInt32(0,r[0],false);i.setInt32(4,r[1],false);i.setInt32(8,r[2],false);i.setInt32(12,r[3],false);i.setInt32(16,r[4],false);return n};var w=this.rawDigest=function(e){var r=e.byteLength||e.length||e.size||0;v(t.heap,t.padMaxChunkLen);var n=0,i=t.maxChunkLen,s;for(n=0;r>n+i;n+=i){y(e,n,i,r,false)}y(e,n,r-n,r,true);return b(t.heap,t.padMaxChunkLen)};this.digest=this.digestFromString=this.digestFromBuffer=this.digestFromArrayBuffer=function(e){return d(w(e).buffer)}}n._core=function o(e,t,r){"use asm";var n=new e.Int32Array(r);function i(e,t){e=e|0;t=t|0;var r=0,i=0,s=0,o=0,a=0,f=0,u=0,h=0,l=0,c=0,d=0,p=0,m=0,v=0;s=n[t+320>>2]|0;a=n[t+324>>2]|0;u=n[t+328>>2]|0;l=n[t+332>>2]|0;d=n[t+336>>2]|0;for(r=0;(r|0)<(e|0);r=r+64|0){o=s;f=a;h=u;c=l;p=d;for(i=0;(i|0)<64;i=i+4|0){v=n[r+i>>2]|0;m=((s<<5|s>>>27)+(a&u|~a&l)|0)+((v+d|0)+1518500249|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[e+i>>2]=v}for(i=e+64|0;(i|0)<(e+80|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a&u|~a&l)|0)+((v+d|0)+1518500249|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+80|0;(i|0)<(e+160|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a^u^l)|0)+((v+d|0)+1859775393|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+160|0;(i|0)<(e+240|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a&u|a&l|u&l)|0)+((v+d|0)-1894007588|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+240|0;(i|0)<(e+320|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a^u^l)|0)+((v+d|0)-899497514|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}s=s+o|0;a=a+f|0;u=u+h|0;l=l+c|0;d=d+p|0}n[t+320>>2]=s;n[t+324>>2]=a;n[t+328>>2]=u;n[t+332>>2]=l;n[t+336>>2]=d}return{hash:i}};if(typeof t!=="undefined"){t.exports=n}else if(typeof window!=="undefined"){window.Rusha=n}if(typeof FileReaderSync!=="undefined"){var i=new FileReaderSync,s=new n(4*1024*1024);self.onmessage=function a(e){var t,r=e.data.data;try{t=s.digest(r);self.postMessage({id:e.data.id,hash:t})}catch(n){self.postMessage({id:e.data.id,error:n.name})}}}})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],103:[function(e,t,r){(function(r){t.exports=u;var n=e("xtend");var i=e("http");var s=e("https");var o=e("once");var a=e("unzip-response");var f=e("url");function u(e,t){e=typeof e==="string"?{url:e}:n(e);t=o(t);if(e.url)h(e);if(e.headers==null)e.headers={};if(e.maxRedirects==null)e.maxRedirects=10;var r=e.body;e.body=undefined;if(r&&!e.method)e.method="POST";var f=Object.keys(e.headers).some(function(e){return e.toLowerCase()==="accept-encoding"});if(!f)e.headers["accept-encoding"]="gzip, deflate";var l=e.protocol==="https:"?s:i;var c=l.request(e,function(r){if(r.statusCode>=300&&r.statusCode<400&&"location"in r.headers){e.url=r.headers.location;h(e);r.resume();e.maxRedirects-=1;if(e.maxRedirects>0)u(e,t);else t(new Error("too many redirects"));return}t(null,typeof a==="function"?a(r):r)});c.on("error",t);c.end(r);return c}t.exports.concat=function(e,t){return u(e,function(e,n){if(e)return t(e);var i=[];n.on("data",function(e){i.push(e)});n.on("end",function(){t(null,r.concat(i),n)})})};["get","post","put","patch","head","delete"].forEach(function(e){t.exports[e]=function(t,r){if(typeof t==="string")t={url:t};t.method=e.toUpperCase();return u(t,r)}});function h(e){var t=f.parse(e.url);if(t.hostname)e.hostname=t.hostname;if(t.port)e.port=t.port;if(t.protocol)e.protocol=t.protocol;e.path=t.path;delete e.url}}).call(this,e("buffer").Buffer)},{buffer:36,http:109,https:52,once:73,"unzip-response":34,url:120,xtend:126}],104:[function(e,t,r){(function(r){t.exports=l;var n=e("debug")("simple-peer");var i=e("get-browser-rtc");var s=e("hat");var o=e("inherits");var a=e("is-typedarray");var f=e("once");var u=e("stream");var h=e("typedarray-to-buffer");o(l,u.Duplex);function l(e){var t=this;if(!(t instanceof l))return new l(e);t._debug("new peer %o",e);if(!e)e={};e.allowHalfOpen=false;if(e.highWaterMark==null)e.highWaterMark=1024*1024;u.Duplex.call(t,e);t.initiator=e.initiator||false;t.channelConfig=e.channelConfig||l.channelConfig;t.channelName=e.channelName||s(160);if(!e.initiator)t.channelName=null;t.config=e.config||l.config;t.constraints=e.constraints||l.constraints;t.reconnectTimer=e.reconnectTimer||0;t.sdpTransform=e.sdpTransform||function(e){return e};t.stream=e.stream||false;t.trickle=e.trickle!==undefined?e.trickle:true;t.destroyed=false;t.connected=false;t.remoteAddress=undefined;t.remoteFamily=undefined;t.remotePort=undefined;t.localAddress=undefined;t.localPort=undefined;t._wrtc=e.wrtc||i();if(!t._wrtc){if(typeof window==="undefined"){throw new Error("No WebRTC support: Specify `opts.wrtc` option in this environment")}else{throw new Error("No WebRTC support: Not a supported browser")}}t._maxBufferedAmount=e.highWaterMark;t._pcReady=false;t._channelReady=false;t._iceComplete=false;t._channel=null;t._pendingCandidates=[];t._chunk=null;t._cb=null;t._interval=null;t._reconnectTimeout=null;t._pc=new t._wrtc.RTCPeerConnection(t.config,t.constraints);t._pc.oniceconnectionstatechange=t._onIceConnectionStateChange.bind(t);t._pc.onsignalingstatechange=t._onSignalingStateChange.bind(t);t._pc.onicecandidate=t._onIceCandidate.bind(t);if(t.stream)t._pc.addStream(t.stream);t._pc.onaddstream=t._onAddStream.bind(t);if(t.initiator){t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)});t._pc.onnegotiationneeded=f(t._createOffer.bind(t));if(typeof window==="undefined"||!window.webkitRTCPeerConnection){t._pc.onnegotiationneeded()}}else{t._pc.ondatachannel=t._setupData.bind(t)}t.on("finish",function(){if(t.connected){setTimeout(function(){t._destroy()},100)}else{t.once("connect",function(){setTimeout(function(){t._destroy()},100)})}})}l.WEBRTC_SUPPORT=!!i();l.config={iceServers:[{url:"stun:23.21.150.121",urls:"stun:23.21.150.121"}]};l.constraints={};l.channelConfig={};Object.defineProperty(l.prototype,"bufferSize",{get:function(){var e=this;return e._channel&&e._channel.bufferedAmount||0}});l.prototype.address=function(){var e=this;return{port:e.localPort,family:"IPv4",address:e.localAddress}};l.prototype.signal=function(e){var t=this;if(t.destroyed)throw new Error("cannot signal after peer is destroyed");if(typeof e==="string"){try{e=JSON.parse(e)}catch(r){e={}}}t._debug("signal()");function n(e){try{t._pc.addIceCandidate(new t._wrtc.RTCIceCandidate(e),c,t._onError.bind(t))}catch(r){t._destroy(new Error("error adding candidate: "+r.message))}}if(e.sdp){t._pc.setRemoteDescription(new t._wrtc.RTCSessionDescription(e),function(){if(t.destroyed)return;if(t._pc.remoteDescription.type==="offer")t._createAnswer();t._pendingCandidates.forEach(n);t._pendingCandidates=[]},t._onError.bind(t))}if(e.candidate){if(t._pc.remoteDescription)n(e.candidate);else t._pendingCandidates.push(e.candidate)}if(!e.sdp&&!e.candidate){t._destroy(new Error("signal() called with invalid signal data"))}};l.prototype.send=function(e){var t=this;if(!a.strict(e)&&!(e instanceof ArrayBuffer)&&!r.isBuffer(e)&&typeof e!=="string"&&(typeof Blob==="undefined"||!(e instanceof Blob))){e=JSON.stringify(e)}if(r.isBuffer(e)&&!a.strict(e)){e=new Uint8Array(e)}var n=e.length||e.byteLength||e.size;t._channel.send(e);t._debug("write: %d bytes",n)};l.prototype.destroy=function(e){var t=this;t._destroy(null,e)};l.prototype._destroy=function(e,t){var r=this;if(r.destroyed)return;if(t)r.once("close",t);r._debug("destroy (error: %s)",e&&e.message);r.readable=r.writable=false;if(!r._readableState.ended)r.push(null);if(!r._writableState.finished)r.end();r.destroyed=true;r.connected=false;r._pcReady=false;r._channelReady=false;r._chunk=null;r._cb=null;clearInterval(r._interval);clearTimeout(r._reconnectTimeout);if(r._pc){try{r._pc.close()}catch(e){}r._pc.oniceconnectionstatechange=null;r._pc.onsignalingstatechange=null;r._pc.onicecandidate=null}if(r._channel){try{r._channel.close()}catch(e){}r._channel.onmessage=null;r._channel.onopen=null;r._channel.onclose=null}r._pc=null;r._channel=null;if(e)r.emit("error",e);r.emit("close")};l.prototype._setupData=function(e){var t=this;t._channel=e.channel;t.channelName=t._channel.label;t._channel.binaryType="arraybuffer";t._channel.onmessage=t._onChannelMessage.bind(t);t._channel.onopen=t._onChannelOpen.bind(t);t._channel.onclose=t._onChannelClose.bind(t)};l.prototype._read=function(){};l.prototype._write=function(e,t,r){var n=this;if(n.destroyed)return r(new Error("cannot write after peer is destroyed"));if(n.connected){try{n.send(e)}catch(i){return n._onError(i)}if(n._channel.bufferedAmount>n._maxBufferedAmount){n._debug("start backpressure: bufferedAmount %d",n._channel.bufferedAmount);n._cb=r}else{r(null)}}else{n._debug("write before connect");n._chunk=e;n._cb=r}};l.prototype._createOffer=function(){var e=this;if(e.destroyed)return;e._pc.createOffer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,c,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.offerConstraints)};l.prototype._createAnswer=function(){var e=this;if(e.destroyed)return;e._pc.createAnswer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,c,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.answerConstraints)};l.prototype._onIceConnectionStateChange=function(){var e=this;if(e.destroyed)return;var t=e._pc.iceGatheringState;var r=e._pc.iceConnectionState;e._debug("iceConnectionStateChange %s %s",t,r);e.emit("iceConnectionStateChange",t,r);if(r==="connected"||r==="completed"){clearTimeout(e._reconnectTimeout);e._pcReady=true;e._maybeReady()}if(r==="disconnected"){if(e.reconnectTimer){clearTimeout(e._reconnectTimeout);e._reconnectTimeout=setTimeout(function(){e._destroy()},e.reconnectTimer)}else{e._destroy()}}if(r==="closed"){e._destroy()}};l.prototype._maybeReady=function(){var e=this;e._debug("maybeReady pc %s channel %s",e._pcReady,e._channelReady);if(e.connected||e._connecting||!e._pcReady||!e._channelReady)return;e._connecting=true;if(typeof window!=="undefined"&&!!window.mozRTCPeerConnection){e._pc.getStats(null,function(e){var r=[];e.forEach(function(e){r.push(e)});t(r)},e._onError.bind(e))}else{e._pc.getStats(function(e){var r=[];e.result().forEach(function(e){var t={};e.names().forEach(function(r){t[r]=e.stat(r)});t.id=e.id;t.type=e.type;t.timestamp=e.timestamp;r.push(t)});t(r)})}function t(t){t.forEach(function(t){if(t.type==="remotecandidate"){e.remoteAddress=t.ipAddress;e.remotePort=Number(t.portNumber);e.remoteFamily="IPv4";e._debug("connect remote: %s:%s (%s)",e.remoteAddress,e.remotePort,e.remoteFamily)}else if(t.type==="localcandidate"&&t.candidateType==="host"){e.localAddress=t.ipAddress;e.localPort=Number(t.portNumber);e._debug("connect local: %s:%s",e.localAddress,e.localPort)}});e._connecting=false;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(r){return e._onError(r)}e._chunk=null;e._debug('sent chunk from "write before connect"');var n=e._cb;e._cb=null;n(null)}e._interval=setInterval(function(){if(!e._cb||!e._channel||e._channel.bufferedAmount>e._maxBufferedAmount)return;e._debug("ending backpressure: bufferedAmount %d",e._channel.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref();e._debug("connect");e.emit("connect")}};l.prototype._onSignalingStateChange=function(){var e=this;if(e.destroyed)return;e._debug("signalingStateChange %s",e._pc.signalingState);e.emit("signalingStateChange",e._pc.signalingState)};l.prototype._onIceCandidate=function(e){var t=this;if(t.destroyed)return;if(e.candidate&&t.trickle){t.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}})}else if(!e.candidate){t._iceComplete=true;t.emit("_iceComplete")}};l.prototype._onChannelMessage=function(e){var t=this;if(t.destroyed)return;var r=e.data;t._debug("read: %d bytes",r.byteLength||r.length);if(r instanceof ArrayBuffer){r=h(new Uint8Array(r));t.push(r)}else{try{r=JSON.parse(r)}catch(n){}t.emit("data",r)}};l.prototype._onChannelOpen=function(){var e=this;if(e.connected||e.destroyed)return;e._debug("on channel open");e._channelReady=true;e._maybeReady()};l.prototype._onChannelClose=function(){var e=this;if(e.destroyed)return;e._debug("on channel close");e._destroy()};l.prototype._onAddStream=function(e){var t=this;if(t.destroyed)return;t._debug("on add stream");t.emit("stream",e.stream)};l.prototype._onError=function(e){var t=this;if(t.destroyed)return;t._debug("error %s",e.message||e);t._destroy(e)};l.prototype._debug=function(){var e=this;var t=[].slice.call(arguments);var r=e.channelName&&e.channelName.substring(0,7);t[0]="["+r+"] "+t[0];n.apply(null,t)};function c(){}}).call(this,{isBuffer:e("../is-buffer/index.js")})},{"../is-buffer/index.js":57,debug:42,"get-browser-rtc":50,hat:51,inherits:55,"is-typedarray":59,once:73,stream:108,"typedarray-to-buffer":118}],105:[function(e,t,r){var n=e("rusha");var i=new n;var s=window.crypto||window.msCrypto||{};var o=s.subtle||s.webkitSubtle;var a=i.digest.bind(i);try{o.digest({name:"sha-1"},new Uint8Array).catch(function(){o=false})}catch(f){o=false}function u(e,t){if(!o){setTimeout(t,0,a(e));return}if(typeof e==="string"){e=h(e)}o.digest({name:"sha-1"},e).then(function r(e){t(l(new Uint8Array(e)))},function n(r){t(a(e))})}function h(e){var t=e.length;var r=new Uint8Array(t);for(var n=0;n>>4).toString(16));r.push((i&15).toString(16))}return r.join("")}t.exports=u;t.exports.sync=a},{rusha:102}],106:[function(e,t,r){(function(r){t.exports=h;var n=e("debug")("simple-websocket");var i=e("inherits");var s=e("is-typedarray");var o=e("stream");var a=e("typedarray-to-buffer");var f=e("ws");var u=typeof window!=="undefined"?window.WebSocket:f;i(h,o.Duplex);function h(e,t){var r=this;if(!(r instanceof h))return new h(e,t);if(!t)t={};n("new websocket: %s %o",e,t);t.allowHalfOpen=false;if(t.highWaterMark==null)t.highWaterMark=1024*1024;o.Duplex.call(r,t);r.url=e;r.connected=false;r.destroyed=false;r._maxBufferedAmount=t.highWaterMark;r._chunk=null;r._cb=null;r._interval=null;r._ws=new u(r.url);r._ws.binaryType="arraybuffer";r._ws.onopen=r._onOpen.bind(r);r._ws.onmessage=r._onMessage.bind(r);r._ws.onclose=r._onClose.bind(r);r._ws.onerror=function(){r._onError(new Error("connection error to "+r.url))};r.on("finish",function(){if(r.connected){setTimeout(function(){r._destroy()},100)}else{r.once("connect",function(){setTimeout(function(){r._destroy()},100)})}})}h.WEBSOCKET_SUPPORT=!!u;h.prototype.send=function(e){var t=this;if(!s.strict(e)&&!(e instanceof ArrayBuffer)&&!r.isBuffer(e)&&typeof e!=="string"&&(typeof Blob==="undefined"||!(e instanceof Blob))){e=JSON.stringify(e)}var i=e.length||e.byteLength||e.size;t._ws.send(e);n("write: %d bytes",i)};h.prototype.destroy=function(e){var t=this;t._destroy(null,e)};h.prototype._destroy=function(e,t){var r=this;if(r.destroyed)return;if(t)r.once("close",t);n("destroy (error: %s)",e&&e.message);this.readable=this.writable=false;if(!r._readableState.ended)r.push(null);if(!r._writableState.finished)r.end();r.connected=false;r.destroyed=true;clearInterval(r._interval);r._interval=null;r._chunk=null;r._cb=null;if(r._ws){var i=r._ws;var s=function(){i.onclose=null;r.emit("close")};if(i.readyState===u.CLOSED){s()}else{try{i.onclose=s;i.close()}catch(e){s()}}i.onopen=null;i.onmessage=null;i.onerror=null}r._ws=null;if(e)r.emit("error",e)};h.prototype._read=function(){};h.prototype._write=function(e,t,r){var i=this;if(i.destroyed)return r(new Error("cannot write after socket is destroyed"));if(i.connected){try{i.send(e)}catch(s){return i._onError(s)}if(typeof f!=="function"&&i._ws.bufferedAmount>i._maxBufferedAmount){n("start backpressure: bufferedAmount %d",i._ws.bufferedAmount);i._cb=r}else{r(null)}}else{n("write before connect");i._chunk=e;i._cb=r}};h.prototype._onMessage=function(e){var t=this;if(t.destroyed)return;var i=e.data;n("read: %d bytes",i.byteLength||i.length);if(i instanceof ArrayBuffer){i=a(new Uint8Array(i));t.push(i)}else if(r.isBuffer(i)){t.push(i)}else{try{i=JSON.parse(i)}catch(s){}t.emit("data",i)}};h.prototype._onOpen=function(){var e=this;if(e.connected||e.destroyed)return;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(t){return e._onError(t)}e._chunk=null;n('sent chunk from "write before connect"');var r=e._cb;e._cb=null;r(null)}if(typeof f!=="function"){e._interval=setInterval(function(){if(!e._cb||!e._ws||e._ws.bufferedAmount>e._maxBufferedAmount){return}n("ending backpressure: bufferedAmount %d",e._ws.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref()}n("connect");e.emit("connect")};h.prototype._onClose=function(){var e=this;if(e.destroyed)return;n("on close");e._destroy()};h.prototype._onError=function(e){var t=this;if(t.destroyed)return;n("error: %s",e.message||e);t._destroy(e)}}).call(this,{isBuffer:e("../is-buffer/index.js")})},{"../is-buffer/index.js":57,debug:42,inherits:55,"is-typedarray":59,stream:108,"typedarray-to-buffer":118,ws:34}],107:[function(e,t,r){var n=1;var i=65535;var s=4;var o=function(){n=n+1&i};var a=setInterval(o,1e3/s|0);if(a.unref)a.unref();t.exports=function(e){var t=s*(e||5);var r=[0];var o=1;var a=n-1&i;return function(e){var f=n-a&i;if(f>t)f=t;a=n;while(f--){if(o===t)o=0;r[o]=r[o===0?t-1:o-1];o++}if(e)r[o-1]+=e;var u=r[o-1];var h=r.lengthe._pos){var o=r.substr(e._pos);if(e._charset==="x-user-defined"){var a=new i(o.length);for(var u=0;ue._pos){e.push(new i(new Uint8Array(h.result.slice(e._pos))));e._pos=h.result.byteLength}};h.onload=function(){e.push(null)};h.readAsArrayBuffer(r);break}if(e._xhr.readyState===f.DONE&&e._mode!=="ms-stream"){e.push(null)}}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{"./capability":110,_process:83,buffer:36,inherits:55,stream:108}],113:[function(e,t,r){var n=e("buffer").Buffer;var i=n.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function s(e){if(e&&!i(e)){throw new Error("Unknown encoding: "+e)}}var o=r.StringDecoder=function(e){this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,"");s(e);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=f;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=u;break;default:this.write=a;return}this.charBuffer=new n(6);this.charReceived=0;this.charLength=0};o.prototype.write=function(e){var t="";while(this.charLength){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;e.copy(this.charBuffer,this.charReceived,0,r);this.charReceived+=r;if(this.charReceived=55296&&n<=56319){this.charLength+=this.surrogateSize;t="";continue}this.charReceived=this.charLength=0;if(e.length===0){return t}break}this.detectIncompleteChar(e);var i=e.length;if(this.charLength){e.copy(this.charBuffer,0,e.length-this.charReceived,i);i-=this.charReceived}t+=e.toString(this.encoding,0,i);var i=t.length-1;var n=t.charCodeAt(i);if(n>=55296&&n<=56319){var s=this.surrogateSize;this.charLength+=s;this.charReceived+=s;this.charBuffer.copy(this.charBuffer,s,0,s);e.copy(this.charBuffer,0,0,s);return t.substring(0,i)}return t};o.prototype.detectIncompleteChar=function(e){var t=e.length>=3?3:e.length;for(;t>0;t--){var r=e[e.length-t];if(t==1&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t};o.prototype.end=function(e){var t="";if(e&&e.length)t=this.write(e);if(this.charReceived){var r=this.charReceived;var n=this.charBuffer;var i=this.encoding;t+=n.slice(0,r).toString(i)}return t};function a(e){return e.toString(this.encoding)}function f(e){this.charReceived=e.length%2;this.charLength=this.charReceived?2:0}function u(e){this.charReceived=e.length%3;this.charLength=this.charReceived?3:0}},{buffer:36}],114:[function(e,t,r){var n=e("./thirty-two");r.encode=n.encode;r.decode=n.decode},{"./thirty-two":115}],115:[function(e,t,r){(function(e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";var n=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,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,255,255,255,255,255,255,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,255,255,255,255,255];function i(e){var t=Math.floor(e.length/5);return e.length%5==0?t:t+1}r.encode=function(r){var n=0;var s=0;var o=0;var a=0;var f=new e(i(r)*8);if(!e.isBuffer(r)){r=new e(r)}while(n3){a=u&255>>o;o=(o+5)%8;a=a<>8-o;n++}else{a=u>>8-(o+5)&31;o=(o+5)%8;if(o==0)n++}f[s]=t.charCodeAt(a);s++}for(n=s;n>>r;a[o]=s;o++;s=255&i<<8-r}}else{throw new Error("Invalid input - it is not base32 encoded string")}}return a.slice(0,o)}}).call(this,e("buffer").Buffer)},{buffer:36}],116:[function(e,t,r){(function(r,n){t.exports=c;var i=e("debug")("torrent-discovery");var s=e("bittorrent-dht/client");var o=e("events").EventEmitter;var a=e("xtend/mutable");var f=e("inherits");var u=e("run-parallel");var h=e("re-emitter"); +var l=e("bittorrent-tracker/client");f(c,o);function c(e){var t=this;if(!(t instanceof c))return new c(e);o.call(t);a(t,{announce:[],dht:typeof s==="function",rtcConfig:null,peerId:null,port:0,tracker:true,wrtc:null},e);t.infoHash=null;t.infoHashHex=null;t.torrent=null;t._externalDHT=typeof t.dht==="object";t._performedDHTLookup=false;if(!t.peerId)throw new Error("peerId required");if(!r.browser&&!t.port)throw new Error("port required");if(t.dht)t._createDHT(t.dhtPort)}c.prototype.setTorrent=function(e){var t=this;if(!t.infoHash&&n.isBuffer(e)||typeof e==="string"){t.infoHash=typeof e==="string"?new n(e,"hex"):e}else if(!t.torrent&&e&&e.infoHash){t.torrent=e;t.infoHash=typeof e.infoHash==="string"?new n(e.infoHash,"hex"):e.infoHash}else{return}t.infoHashHex=t.infoHash.toString("hex");i("setTorrent %s",t.infoHashHex);if(t.tracker&&t.tracker!==true){t.tracker.torrentLength=e.length}else{t._createTracker()}if(t.dht){if(t.dht.ready)t._dhtLookupAndAnnounce();else t.dht.on("ready",t._dhtLookupAndAnnounce.bind(t))}};c.prototype.updatePort=function(e){var t=this;if(e===t.port)return;t.port=e;if(t.dht&&t.infoHash){t._performedDHTLookup=false;t._dhtLookupAndAnnounce()}if(t.tracker&&t.tracker!==true){t.tracker.stop();t.tracker.destroy(function(){t._createTracker()})}};c.prototype.stop=function(e){var t=this;var r=[];if(t.tracker&&t.tracker!==true){t.tracker.stop();r.push(function(e){t.tracker.destroy(e)})}if(!t._externalDHT&&t.dht&&t.dht!==true){r.push(function(e){t.dht.destroy(e)})}u(r,e)};c.prototype._createDHT=function(e){var t=this;if(!t._externalDHT)t.dht=new s;h(t.dht,t,["error","warning"]);t.dht.on("peer",function(e,r){if(r===t.infoHashHex)t.emit("peer",e)});if(!t._externalDHT)t.dht.listen(e)};c.prototype._createTracker=function(){var e=this;if(!e.tracker)return;var t=e.torrent?a({announce:[]},e.torrent):{infoHash:e.infoHashHex,announce:[]};if(e.announce)t.announce=t.announce.concat(e.announce);var r={rtcConfig:e.rtcConfig,wrtc:e.wrtc};e.tracker=new l(e.peerId,e.port,t,r);h(e.tracker,e,["peer","warning","error"]);e.tracker.on("update",function(t){e.emit("trackerAnnounce",t)});e.tracker.start()};c.prototype._dhtLookupAndAnnounce=function(){var e=this;if(e._performedDHTLookup)return;e._performedDHTLookup=true;i("dht lookup");e.dht.lookup(e.infoHash,function(t){if(t||!e.port)return;i("dht announce");e.dht.announce(e.infoHash,e.port,function(){i("dht announce complete");e.emit("dhtAnnounce")})})}}).call(this,e("_process"),e("buffer").Buffer)},{_process:83,"bittorrent-dht/client":34,"bittorrent-tracker/client":23,buffer:36,debug:42,events:47,inherits:55,"re-emitter":90,"run-parallel":101,"xtend/mutable":127}],117:[function(e,t,r){(function(e){t.exports=n;var r=1<<14;function n(e){if(!(this instanceof n))return new n(e);this.length=e;this.missing=e;this.sources=null;this._chunks=Math.ceil(e/r);this._remainder=e%r||r;this._buffered=0;this._buffer=null;this._cancellations=null;this._reservations=0;this._flushed=false}n.BLOCK_LENGTH=r;n.prototype.chunkLength=function(e){return e===this._chunks-1?this._remainder:r};n.prototype.chunkOffset=function(e){return e*r};n.prototype.reserve=function(){if(!this.init())return-1;if(this._cancellations.length)return this._cancellations.pop();if(this._reservations",'"',"`"," ","\r","\n"," "],h=["{","}","|","\\","^","`"].concat(u),l=["'"].concat(h),c=["%","/","?",";","#"].concat(l),d=["/","?","#"],p=255,m=/^[+a-z0-9A-Z_-]{0,63}$/,v=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:true,"javascript:":true},_={javascript:true,"javascript:":true},y={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},b=e("querystring");function w(e,t,r){if(e&&i.isObject(e)&&e instanceof s)return e;var n=new s;n.parse(e,t,r);return n}s.prototype.parse=function(e,t,r){if(!i.isString(e)){throw new TypeError("Parameter 'url' must be a string, not "+typeof e)}var s=e.indexOf("?"),a=s!==-1&&s127){F+="x"}else{F+=P[O]}}if(!F.match(m)){var D=C.slice(0,U);var N=C.slice(U+1);var z=P.match(v);if(z){D.push(z[1]);N.unshift(z[2])}if(N.length){w="/"+N.join(".")+w}this.hostname=D.join(".");break}}}}if(this.hostname.length>p){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!B){this.hostname=n.toASCII(this.hostname)}var j=this.port?":"+this.port:"";var H=this.hostname||"";this.host=H+j;this.href+=this.host;if(B){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(w[0]!=="/"){w="/"+w}}}if(!g[k]){for(var U=0,R=l.length;U0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}r.search=e.search;r.query=e.query;if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.href=r.format();return r}if(!x.length){r.pathname=null;if(r.search){r.path="/"+r.search}else{r.path=null}r.href=r.format();return r}var A=x.slice(-1)[0];var U=(r.host||e.host||x.length>1)&&(A==="."||A==="..")||A==="";var T=0;for(var I=x.length;I>=0;I--){A=x[I];if(A==="."){x.splice(I,1)}else if(A===".."){x.splice(I,1);T++}else if(T){x.splice(I,1);T--}}if(!w&&!S){for(;T--;T){x.unshift("..")}}if(w&&x[0]!==""&&(!x[0]||x[0].charAt(0)!=="/")){x.unshift("")}if(U&&x.join("/").substr(-1)!=="/"){x.push("")}var L=x[0]===""||x[0]&&x[0].charAt(0)==="/";if(k){r.hostname=r.host=L?"":x.length?x.shift():"";var E=r.host&&r.host.indexOf("@")>0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}w=w||r.host&&x.length;if(w&&!L){x.unshift("")}if(!x.length){r.pathname=null;r.path=null}else{r.pathname=x.join("/")}if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.auth=e.auth||r.auth;r.slashes=r.slashes||e.slashes;r.href=r.format();return r};s.prototype.parseHost=function(){var e=this.host;var t=a.exec(e);if(t){t=t[0];if(t!==":"){this.port=t.substr(1)}e=e.substr(0,e.length-t.length)}if(e)this.hostname=e}},{"./util":121,punycode:85,querystring:88}],121:[function(e,t,r){"use strict";t.exports={isString:function(e){return typeof e==="string"},isObject:function(e){return typeof e==="object"&&e!==null},isNull:function(e){return e===null},isNullOrUndefined:function(e){return e==null}}},{}],122:[function(e,t,r){(function(r){var n=e("bencode");var i=e("bitfield");var s=e("events").EventEmitter;var o=e("inherits");var a=e("simple-sha1");var f=1e7;var u=1e3;var h=16*1024;t.exports=function(e){o(t,s);function t(t){s.call(this);this._wire=t;this._metadataComplete=false;this._metadataSize=null;this._remainingRejects=null;this._fetching=false;this._bitfield=new i(0,{grow:u});if(r.isBuffer(e)){this.setMetadata(e)}}t.prototype.name="ut_metadata";t.prototype.onHandshake=function(e,t,r){this._infoHash=e;this._infoHashHex=e.toString("hex")};t.prototype.onExtendedHandshake=function(e){if(!e.m||!e.m.ut_metadata){return this.emit("warning",new Error("Peer does not support ut_metadata"))}if(!e.metadata_size){return this.emit("warning",new Error("Peer does not have metadata"))}if(e.metadata_size>f){return this.emit("warning",new Error("Peer gave maliciously large metadata size"))}this._metadataSize=e.metadata_size;this._numPieces=Math.ceil(this._metadataSize/h);this._remainingRejects=this._numPieces*2;if(this._fetching){this._requestPieces()}};t.prototype.onMessage=function(e){var t,r;try{var i=e.toString();var s=i.indexOf("ee")+2;t=n.decode(i.substring(0,s));r=e.slice(s)}catch(o){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,r,t.total_size);break;case 2:this._onReject(t.piece);break}};t.prototype.fetch=function(){if(this._metadataComplete){return}this._fetching=true;if(this._metadataSize){this._requestPieces()}};t.prototype.cancel=function(){this._fetching=false};t.prototype.setMetadata=function(e){if(this._metadataComplete)return true;try{var t=n.decode(e).info;if(t){e=n.encode(t)}}catch(r){}if(this._infoHashHex&&this._infoHashHex!==a.sync(e)){return false}this.cancel();this.metadata=e;this._metadataComplete=true;this._metadataSize=this.metadata.length;this._wire.extendedHandshake.metadata_size=this._metadataSize;this.emit("metadata",n.encode({info:n.decode(this.metadata)}));return true};t.prototype._send=function(e,t){var i=n.encode(e);if(r.isBuffer(t)){i=r.concat([i,t])}this._wire.extended("ut_metadata",i)};t.prototype._request=function(e){this._send({msg_type:0,piece:e})};t.prototype._data=function(e,t,r){var n={msg_type:1,piece:e};if(typeof r==="number"){n.total_size=r}this._send(n,t)};t.prototype._reject=function(e){this._send({msg_type:2,piece:e})};t.prototype._onRequest=function(e){if(!this._metadataComplete){this._reject(e);return}var t=e*h;var r=t+h;if(r>this._metadataSize){r=this._metadataSize}var n=this.metadata.slice(t,r);this._data(e,n,this._metadataSize)};t.prototype._onData=function(e,t,r){if(t.length>h){return}t.copy(this.metadata,e*h);this._bitfield.set(e);this._checkDone()};t.prototype._onReject=function(e){if(this._remainingRejects>0&&this._fetching){this._request(e);this._remainingRejects-=1}else{this.emit("warning",new Error('Peer sent "reject" too much'))}};t.prototype._requestPieces=function(){this.metadata=new r(this._metadataSize);for(var e=0;e0){this._requestPieces()}else{this.emit("warning",new Error("Peer sent invalid metadata"))}};return t}}).call(this,e("buffer").Buffer)},{bencode:11,bitfield:15,buffer:36,events:47,inherits:55,"simple-sha1":105}],123:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(n("noDeprecation")){return e}var r=false;function i(){if(!r){if(n("throwDeprecation")){throw new Error(t)}else if(n("traceDeprecation")){console.trace(t)}else{console.warn(t)}r=true}return e.apply(this,arguments)}return i}function n(t){try{if(!e.localStorage)return false}catch(r){return false}var n=e.localStorage[t];if(null==n)return false;return String(n).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],124:[function(e,t,r){var n=e("debug")("videostream");var i=e("mp4box");var s=.01;var o=60;t.exports=function(e,t,r){r=r||{};var f=r.debugTrack||-1;var u=[];function h(){t.addEventListener("waiting",S);t.addEventListener("timeupdate",E)}h();var l=false;function c(e){l=true;t.removeEventListener("waiting",S);t.removeEventListener("timeupdate",E);if(p.readyState==="open")p.endOfStream(e)}function d(e){var r=e.buffer.buffered;var i=t.currentTime;var a=-1;for(var f=0;fi){break}else if(a>=0||i<=h){a=h}}var l=a-i;if(l<0)l=0;n("Buffer length: %f",l);return l<=o}var p=new MediaSource;p.addEventListener("sourceopen",function(){w(0)});t.src=window.URL.createObjectURL(p);var m=new i;m.onError=function(e){n("MP4Box error: %s",e.message);if(b){b()}if(p.readyState==="open"){c("decode")}};var v=false;var g={};m.onReady=function(e){n("MP4 info: %o",e);e.tracks.forEach(function(e){var t;if(e.video){t="video/mp4"}else if(e.audio){t="audio/mp4"}else{return}t+='; codecs="'+e.codec+'"';if(MediaSource.isTypeSupported(t)){var r=p.addSourceBuffer(t);var n={buffer:r,arrayBuffers:[],meta:e,ended:false};r.addEventListener("updateend",A.bind(null,n));m.setSegmentOptions(e.id,null,{nbSamples:e.video?1:100});g[e.id]=n}});if(Object.keys(g).length===0){c("decode");return}var t=m.initializeSegmentation();t.forEach(function(e){k(g[e.id],e.buffer);if(e.id===f){a("init-track-"+f+".mp4",[e.buffer]);u.push(e.buffer)}});v=true};m.onSegment=function(e,t,r,n){var i=g[e];k(i,r,n===i.meta.nb_samples);if(e===f&&u){u.push(r);if(n>1e3){a("track-"+f+".mp4",u);u=null}}};var _;var y=null;var b=null;function w(t){if(t===e.length){m.flush();return}if(y&&t===_){var r=y;setTimeout(function(){if(y===r)y.resume()});return}if(y){y.destroy();b()}_=t;var i={start:_,end:e.length-1};y=e.createReadStream(i);function s(e){y.pause();var t=e.toArrayBuffer();t.fileStart=_;_+=t.byteLength;var r;try{r=m.appendBuffer(t)}catch(i){n("MP4Box threw exception: %s",i.message);if(p.readyState==="open"){c("decode")}y.destroy();b();return}w(r)}y.on("data",s);function o(){b();w(_)}y.on("end",o);function a(e){n("Stream error: %s",e.message);if(p.readyState==="open"){c("network")}}y.on("error",a);b=function(){y.removeListener("data",s);y.removeListener("end",o);y.removeListener("error",a);y=null;b=null}}function S(){if(v){x(t.currentTime)}}function x(e){if(l)h();var t=m.seek(e,true);n("Seeking to time: %d",e);n("Seeked file offset: %d",t.offset);w(t.offset)}function k(e,t,r){e.arrayBuffers.push({buffer:t,ended:r||false});A(e)}function E(){Object.keys(g).forEach(function(e){var t=g[e];if(t.blocked){A(t)}})}function A(e){if(e.buffer.updating)return;e.blocked=!d(e);if(e.blocked)return;if(e.arrayBuffers.length===0)return;var t=e.arrayBuffers.shift();var r=false;try{e.buffer.appendBuffer(t.buffer);e.ended=t.ended;r=true}catch(i){n("SourceBuffer error: %s",i.message);c("decode");return}if(r){U()}}function U(){if(p.readyState!=="open"){return}var e=Object.keys(g).every(function(e){var t=g[e];return t.ended&&!t.buffer.updating});if(e){c()}}};function a(e,t){var r=new Blob(t);var n=URL.createObjectURL(r);var i=document.createElement("a");i.setAttribute("href",n);i.setAttribute("download",e);i.click()}},{debug:42,mp4box:70}],125:[function(e,t,r){t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=="function")throw new TypeError("need wrapper function");Object.keys(e).forEach(function(t){r[t]=e[t]});return r;function r(){var t=new Array(arguments.length);for(var r=0;r0)return new Array(e+(/\./.test(t)?2:1)).join(r)+t;return t+""}},{}],129:[function(e,t,r){t.exports={name:"webtorrent",description:"Streaming torrent client",version:"0.63.0",author:{name:"Feross Aboukhadijeh",email:"feross@feross.org",url:"http://feross.org/"},bin:{webtorrent:"./bin/cmd.js"},browser:{"./lib/server.js":false,"bittorrent-dht/client":false,"fs-chunk-store":"memory-chunk-store","load-ip-set":false,ut_pex:false},bugs:{url:"https://github.com/feross/webtorrent/issues"},dependencies:{"addr-to-ip-port":"^1.0.1",bitfield:"^1.0.2","bittorrent-dht":"^4.0.4","bittorrent-swarm":"^5.0.0","chunk-store-stream":"^2.0.0",clivas:"^0.2.0","create-torrent":"^3.4.0","cross-spawn-async":"^2.0.0",debug:"^2.1.0","end-of-stream":"^1.0.0",executable:"^2.1.0","fs-chunk-store":"^1.3.4",hat:"0.0.3","immediate-chunk-store":"^1.0.7",inherits:"^2.0.1",inquirer:"^0.11.0","load-ip-set":"^1.0.3",mediasource:"^1.0.0","memory-chunk-store":"^1.2.0",mime:"^1.2.11",minimist:"^1.1.0",moment:"^2.8.3",multistream:"^2.0.2","network-address":"^1.0.0","parse-torrent":"^5.1.0","path-exists":"^2.1.0","pretty-bytes":"^2.0.1",pump:"^1.0.0","random-iterate":"^1.0.1","range-parser":"^1.0.2","re-emitter":"^1.0.0","run-parallel":"^1.0.0","simple-sha1":"^2.0.0",speedometer:"^1.0.0",thunky:"^0.1.0","torrent-discovery":"^3.0.0","torrent-piece":"^1.0.0",uniq:"^1.0.1",ut_metadata:"^2.1.0",ut_pex:"^1.0.1",videostream:"^1.1.4","windows-no-runnable":"0.0.6",xtend:"^4.0.0","zero-fill":"^2.2.0"},devDependencies:{"bittorrent-tracker":"^6.0.0",brfs:"^1.2.0",browserify:"^12.0.1",finalhandler:"^0.4.0","run-auto":"^1.0.0","serve-static":"^1.9.3","simple-get":"^1.0.0",standard:"^5.1.0",tape:"^4.0.0","uglify-js":"^2.4.15",zelda:"^2.0.0",zuul:"^3.0.0"},homepage:"http://webtorrent.io",keywords:["torrent","bittorrent","bittorrent client","streaming","download","webrtc","webrtc data","webtorrent","mad science"],license:"MIT",main:"index.js",optionalDependencies:{"airplay-js":"^0.2.3",chromecasts:"^1.5.3",nodebmc:"0.0.5"},repository:{type:"git",url:"git://github.com/feross/webtorrent.git"},scripts:{build:"browserify -s WebTorrent -e ./ | uglifyjs -m > webtorrent.min.js","build-debug":"browserify -s WebTorrent -e ./ > webtorrent.debug.js",size:"npm run build && cat webtorrent.min.js | gzip | wc -c",test:"standard && node ./bin/test.js","test-browser":"zuul -- test/basic.js","test-browser-local":"zuul --local -- test/basic.js","test-node":"tape test/*.js"}}},{}],130:[function(e,t,r){(function(r,n,i){t.exports=w;var s=e("create-torrent");var o=e("debug")("webtorrent");var a=e("bittorrent-dht/client");var f=e("events").EventEmitter;var u=e("xtend");var h=e("hat");var l=e("inherits");var c=e("load-ip-set");var d=e("run-parallel");var p=e("parse-torrent");var m=e("speedometer");var v=e("zero-fill");var g=e("path");var _=e("./lib/torrent");l(w,f);var y=e("./package.json").version;var b=y.match(/([0-9]+)/g).slice(0,2).map(v(2)).join("");function w(e){var t=this;if(!(t instanceof w))return new w(e);if(!e)e={};f.call(t);if(!o.enabled)t.setMaxListeners(0);t.destroyed=false;t.torrentPort=e.torrentPort||0;t.tracker=e.tracker!==undefined?e.tracker:true;t._rtcConfig=e.rtcConfig;t._wrtc=e.wrtc||n.WRTC;t.torrents=[];t.downloadSpeed=m();t.uploadSpeed=m();t.peerId=e.peerId===undefined?new i("-WW"+b+"-"+h(48),"utf8"):typeof e.peerId==="string"?new i(e.peerId,"hex"):e.peerId;t.peerIdHex=t.peerId.toString("hex");t.nodeId=e.nodeId===undefined?new i(h(160),"hex"):typeof e.nodeId==="string"?new i(e.nodeId,"hex"):e.nodeId;t.nodeIdHex=t.nodeId.toString("hex");if(e.dht!==false&&typeof a==="function"){t.dht=new a(u({nodeId:t.nodeId},e.dht));t.dht.listen(e.dhtPort)}o("new webtorrent (peerId %s, nodeId %s)",t.peerIdHex,t.nodeIdHex);if(typeof c==="function"){c(e.blocklist,{headers:{"user-agent":"WebTorrent/"+y+" (http://webtorrent.io)"}},function(e,r){if(e)return t.error("Failed to load blocklist: "+e.message);t.blocked=r;s()})}else r.nextTick(s);function s(){if(t.destroyed)return;t.ready=true;t.emit("ready")}}Object.defineProperty(w.prototype,"ratio",{get:function(){var e=this;var t=e.torrents.reduce(function(e,t){return e+t.uploaded},0);var r=e.torrents.reduce(function(e,t){return e+t.downloaded},0)||1;return t/r}});w.prototype.get=function(e){var t=this;if(e instanceof _)return e;var r;try{r=p(e)}catch(n){}if(!r)return null;if(!r.infoHash)throw new Error("Invalid torrent identifier");for(var i=0,s=t.torrents.length;i Date: Wed, 2 Dec 2015 15:47:35 -0500 Subject: [PATCH 10/44] timeRemaining should be 0 once done (Fix #503) timeRemaining property should be 0 once a torrent has been downloaded (or is being seeded) --- lib/torrent.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/torrent.js b/lib/torrent.js index 6b58f7762f..64d38ffea7 100644 --- a/lib/torrent.js +++ b/lib/torrent.js @@ -94,6 +94,7 @@ function Torrent (torrentId, opts) { // Time remaining (in milliseconds) Object.defineProperty(Torrent.prototype, 'timeRemaining', { get: function () { + if (this.done) return 0 if (this.swarm.downloadSpeed() === 0) return Infinity else return ((this.length - this.downloaded) / this.swarm.downloadSpeed()) * 1000 } From efbc9f8083f6f90b3b25a0f05881e897b8ff0754 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 12:59:16 -0800 Subject: [PATCH 11/44] zuul: test current and last chrome/firefox version --- .zuul.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.zuul.yml b/.zuul.yml index a71898c222..0142da14c0 100644 --- a/.zuul.yml +++ b/.zuul.yml @@ -1,6 +1,6 @@ ui: tape browsers: - name: chrome - version: latest + version: -2..latest - name: firefox - version: latest + version: -2..latest From f6c872ee37aeb4a52b2e67107bfb558748f754e6 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 13:00:50 -0800 Subject: [PATCH 12/44] 0.63.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2f9f2272e5..bc060b905c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "webtorrent", "description": "Streaming torrent client", - "version": "0.63.0", + "version": "0.63.1", "author": { "name": "Feross Aboukhadijeh", "email": "feross@feross.org", From 46487f5a79d3c4f72225f233fe44ebed39081a16 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 13:01:08 -0800 Subject: [PATCH 13/44] build --- webtorrent.min.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/webtorrent.min.js b/webtorrent.min.js index d8d0127945..8c970488c9 100644 --- a/webtorrent.min.js +++ b/webtorrent.min.js @@ -1,10 +1,10 @@ -(function(e){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=e()}else if(typeof define==="function"&&define.amd){define([],e)}else{var t;if(typeof window!=="undefined"){t=window}else if(typeof global!=="undefined"){t=global}else if(typeof self!=="undefined"){t=self}else{t=this}t.WebTorrent=e()}})(function(){var e,t,r;return function n(e,t,r){function i(o,a){if(!t[o]){if(!e[o]){var f=typeof require=="function"&&require;if(!a&&f)return f(o,!0);if(s)return s(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var h=t[o]={exports:{}};e[o][0].call(h.exports,function(t){var r=e[o][1][t];return i(r?r:t)},h,h.exports,n,e,t,r)}return t[o].exports}var s=typeof require=="function"&&require;for(var o=0;o=0)y();else if(l.indexOf(g)>=0)w();else if(c.indexOf(g)>=0)S();else if(d.indexOf(g)>=0)x();else v(r,new Error('Unsupported file type "'+g+'": Cannot append to DOM'));function y(){if(!p){return v(r,new Error("Video/audio streaming is not supported in your browser. You can still share "+"or download "+e.name+" (once it's fully downloaded). Use Chrome for "+"MediaSource support."))}var s=f.indexOf(g)>=0?"video":"audio";if(a.indexOf(g)>=0)h();else l();function h(){n("Use `videostream` package for "+e.name);y();u.addEventListener("error",d);u.addEventListener("playing",b);o(e,u)}function l(){n("Use MediaSource API for "+e.name);y();u.addEventListener("error",m);u.addEventListener("playing",b);e.createReadStream().pipe(new i(u,{extname:g}));if(_)u.currentTime=_}function c(){n("Use Blob URL for "+e.name);y();u.addEventListener("error",k);u.addEventListener("playing",b);e.getBlobURL(function(e,t){if(e)return k(e);u.src=t;if(_)u.currentTime=_})}function d(e){n("videostream error: fallback to MediaSource API: %o",e.message||e);u.removeEventListener("error",d);u.removeEventListener("playing",b);l()}function m(e){n("MediaSource API error: fallback to Blob URL: %o",e.message||e);u.removeEventListener("error",m);u.removeEventListener("playing",b);c()}function y(e){if(!u){u=document.createElement(s);u.controls=true;u.autoplay=true;u.play();u.addEventListener("progress",function(){_=u.currentTime});t.appendChild(u)}}}function b(){u.removeEventListener("playing",b);r(null,u)}function w(){u=document.createElement("audio");u.controls=true;u.autoplay=true;t.appendChild(u);e.getBlobURL(function(e,t){if(e)return k(e);u.addEventListener("error",k);u.addEventListener("playing",b);u.src=t;u.play()})}function S(){e.getBlobURL(function(n,i){if(n)return k(n);u=document.createElement("img");u.src=i;u.alt=e.name;t.appendChild(u);r(null,u)})}function x(){e.getBlobURL(function(e,n){if(e)return k(e);u=document.createElement("iframe");u.src=n;if(g!==".pdf")u.sandbox="allow-forms allow-scripts";t.appendChild(u);r(null,u)})}function k(t){if(u)u.remove();t.message='Error appending file "'+e.name+'" to DOM: '+t.message;n(t.message);if(r)r(t)}};function m(){}function v(e,t,n){r.nextTick(function(){if(e)e(t,n)})}}).call(this,e("_process"))},{_process:83,debug:42,mediasource:63,path:77,videostream:124}],2:[function(e,t,r){t.exports=o;var n=e("debug")("webtorrent:file-stream");var i=e("inherits");var s=e("stream");i(o,s.Readable);function o(e,t){s.Readable.call(this,t);this.destroyed=false;this._torrent=e._torrent;var r=t&&t.start||0;var n=t&&t.end||e.length-1;var i=e._torrent.pieceLength;this._startPiece=(r+e.offset)/i|0;this._endPiece=(n+e.offset)/i|0;this._piece=this._startPiece;this._offset=r+e.offset-this._startPiece*i;this._missing=n-r+1;this._reading=false;this._notifying=false;this._criticalLength=Math.min(1024*1024/i|0,2)}o.prototype._read=function(){if(this._reading)return;this._reading=true;this._notify()};o.prototype._notify=function(){var e=this;if(!e._reading||e._missing===0)return;if(!e._torrent.bitfield.get(e._piece)){return e._torrent.critical(e._piece,e._piece+e._criticalLength)}if(e._notifying)return;e._notifying=true;var t=e._piece;e._torrent.store.get(t,function(r,i){e._notifying=false;if(e.destroyed)return;if(r)return e.destroy(r);n("read %s (length %s) (err %s)",t,i.length,r&&r.message);if(e._offset){i=i.slice(e._offset);e._offset=0}if(e._missing0){return r[Math.random()*r.length|0]}else{return-1}}},{}],6:[function(e,t,r){(function(r,n){t.exports=H;var i=e("addr-to-ip-port");var s=e("bitfield");var o=e("chunk-store-stream/write");var a=e("create-torrent");var f=e("debug")("webtorrent:torrent");var u=e("torrent-discovery");var h=e("events").EventEmitter;var l=e("xtend/mutable");var c=e("fs-chunk-store");var d=e("immediate-chunk-store");var p=e("inherits");var m=e("multistream");var v=e("os");var g=e("run-parallel");var _=e("parse-torrent");var y=e("path");var b=e("path-exists");var w=e("torrent-piece");var S=e("pump");var x=e("random-iterate");var k=e("re-emitter");var E=e("simple-sha1");var A=e("bittorrent-swarm");var U=e("uniq");var T=e("ut_metadata");var I=e("ut_pex");var L=e("./file");var B=e("./rarity-map");var C=e("./server");var R=128*1024;var P=3e4;var F=5e3;var O=3*w.BLOCK_LENGTH;var M=.5;var D=1;var N=1e4;var z=2;var j=y.join(b.sync("/tmp")?"/tmp":v.tmpDir(),"webtorrent");p(H,h);function H(e,t){var r=this;h.call(r);if(!f.enabled)r.setMaxListeners(0);f("new torrent");r.client=t.client;r.announce=t.announce;r.urlList=t.urlList;r.path=t.path;r._store=t.store||c;r.strategy=t.strategy||"sequential";r._rechokeNumSlots=t.uploads===false||t.uploads===0?0:+t.uploads||10;r._rechokeOptimisticWire=null;r._rechokeOptimisticTime=0;r._rechokeIntervalId=null;r.ready=false;r.destroyed=false;r.metadata=null;r.store=null;r.numBlockedPeers=0;r.files=null;r.done=false;r._amInterested=false;r._selections=[];r._critical=[];r._servers=[];if(e)r._onTorrentId(e)}Object.defineProperty(H.prototype,"timeRemaining",{get:function(){if(this.swarm.downloadSpeed()===0)return Infinity;else return(this.length-this.downloaded)/this.swarm.downloadSpeed()*1e3}});Object.defineProperty(H.prototype,"downloaded",{get:function(){var e=0;for(var t=0,r=this.pieces.length;tt||e<0||t>=i.pieces.length){throw new Error("invalid selection ",e,":",t)}r=Number(r)||0;f("select %s-%s (priority %s)",e,t,r);i._selections.push({from:e,to:t,offset:0,priority:r,notify:n||W});i._selections.sort(function(e,t){return t.priority-e.priority});i._updateSelections()};H.prototype.deselect=function(e,t,r){var n=this;r=Number(r)||0;f("deselect %s-%s (priority %s)",e,t,r);for(var i=0;i2*(t.swarm.numConns-t.swarm.numPeers)&&e.amInterested){e.destroy()}else{r=setTimeout(n,F);if(r.unref)r.unref()}}var i=0;function s(){if(e.peerPieces.length!==t.pieces.length)return;for(;iR){return e.destroy()}if(t.pieces[r])return;t.store.get(r,{offset:n,length:i},s)});e.bitfield(t.bitfield);e.interested();r=setTimeout(n,F);if(r.unref)r.unref();e.isSeeder=false;s()};H.prototype._updateSelections=function(){var e=this;if(!e.swarm||e.destroyed)return;if(!e.metadata)return e.once("metadata",e._updateSelections.bind(e));r.nextTick(e._gcSelections.bind(e));e._updateInterest();e._update()};H.prototype._gcSelections=function(){var e=this;for(var t=0;t=r)return;var n=q(e,D);f(false)||f(true);function i(t,r,n,i){return function(s){return s>=t&&s<=r&&!(s in n)&&e.peerPieces.get(s)&&(!i||i(s))}}function s(){if(e.requests.length)return;var r=t._selections.length;while(r--){var n=t._selections[r];var s;if(t.strategy==="rarest"){var o=n.from+n.offset;var a=n.to;var f=a-o+1;var u={};var h=0;var l=i(o,a,u);while(h=n.from+n.offset;--s){if(!e.peerPieces.get(s))continue;if(t._request(e,s,false))return}}}}function o(){var r=e.downloadSpeed()||1;if(r>O)return function(){return true};var n=Math.max(1,e.requests.length)*w.BLOCK_LENGTH/r;var i=10;var s=0;return function(e){if(!i||t.bitfield.get(e))return true;var o=t.pieces[e].missing;for(;s0)continue;i--;return false}return true}}function a(e){var r=e;for(var n=e;n=n)return true;var s=o();for(var f=0;f0)e._rechokeOptimisticTime-=1;else e._rechokeOptimisticWire=null;var t=[];e.swarm.wires.forEach(function(r){if(!r.isSeeder&&r!==e._rechokeOptimisticWire){t.push({wire:r,downloadSpeed:r.downloadSpeed(),uploadSpeed:r.uploadSpeed(),salt:Math.random(),isChoked:true})}});t.sort(o);var r=0;var n=0;for(;n=O)continue;if(2*u>n||u>s)continue;o=f;s=u}if(!o)return false;for(a=0;a=o)return false;var a=i.pieces[t];var u=a.reserve();if(u===-1&&n&&i._hotswap(e,t)){u=a.reserve()}if(u===-1)return false;var h=i._reservations[t];if(!h)h=i._reservations[t]=[];var l=h.indexOf(null);if(l===-1)l=h.length;h[l]=e;var c=a.chunkOffset(u);var d=a.chunkLength(u);e.request(t,c,d,function m(r,n){if(!i.ready)return i.once("ready",function(){m(r,n)});if(h[l]===e)h[l]=null;if(a!==i.pieces[t])return p();if(r){f("error getting piece %s (offset: %s length: %s) from %s: %s",t,c,d,e.remoteAddress+":"+e.remotePort,r.message);a.cancel(u);p();return}f("got piece %s (offset: %s length: %s) from %s",t,c,d,e.remoteAddress+":"+e.remotePort);if(!a.set(u,n,e))return p();var s=a.flush();E(s,function(e){if(e===i._hashes[t]){if(!i.pieces[t])return;f("piece verified %s",t);i.pieces[t]=null;i._reservations[t]=null;i.bitfield.set(t,true);i.store.put(t,s);i.swarm.wires.forEach(function(e){e.have(t)});i._checkDone()}else{i.pieces[t]=new w(a.length);i.emit("warning",new Error("Piece "+t+" failed verification"))}p()})});function p(){r.nextTick(function(){i._update()})}return true};H.prototype._checkDone=function(){var e=this;if(e.destroyed)return;e.files.forEach(function(t){if(t.done)return;for(var r=t._startPiece;r<=t._endPiece;++r){if(!e.bitfield.get(r))return}t.done=true;t.emit("done");f("file done: "+t.name)});if(e.files.every(function(e){return e.done})){e.done=true;e.emit("done");f("torrent done: "+e.infoHash);if(e.discovery.tracker)e.discovery.tracker.complete()}e._gcSelections()};H.prototype.load=function(e,t){var r=this;if(!Array.isArray(e))e=[e];if(!t)t=W;var n=new m(e);var i=new o(r.store,r.pieceLength);S(n,i,function(e){if(e)return t(e);r.pieces.forEach(function(e,t){r.pieces[t]=null;r._reservations[t]=null;r.bitfield.set(t,true)});r._checkDone();t(null)})};H.prototype.createServer=function(e){var t=this;if(typeof C!=="function")return;var r=new C(t,e);t._servers.push(r);return r};H.prototype._onError=function(e){var t=this;f("torrent error: %s",e.message||e);t.emit("error",e);t.destroy()};function q(e,t){return Math.ceil(2+t*e.downloadSpeed()/w.BLOCK_LENGTH)}function G(e){return Math.random()*e|0}function W(){}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./file":3,"./rarity-map":5,"./server":34,_process:83,"addr-to-ip-port":7,bitfield:15,"bittorrent-swarm":18,"chunk-store-stream/write":38,"create-torrent":41,debug:42,events:47,"fs-chunk-store":64,"immediate-chunk-store":54,inherits:55,multistream:72,os:74,"parse-torrent":76,path:77,"path-exists":78,pump:84,"random-iterate":89,"re-emitter":90,"run-parallel":101,"simple-sha1":105,"torrent-discovery":116,"torrent-piece":117,uniq:119,ut_metadata:122,ut_pex:34,"xtend/mutable":127}],7:[function(e,t,r){var n=/^\[?([^\]]+)\]?:(\d+)$/;var i={};var s=0;t.exports=function o(e){if(s===1e5)t.exports.reset();if(!i[e]){var r=n.exec(e);if(!r)throw new Error("invalid addr: "+e);i[e]=[r[1],Number(r[2])];s+=1}return i[e]};t.exports.reset=function a(){i={};s=0}},{}],8:[function(e,t,r){"use strict";var n=e("./raw");var i=[];var s=[];var o=n.makeRequestCallFromTimer(a);function a(){if(s.length){throw s.shift()}}t.exports=f;function f(e){var t;if(i.length){t=i.pop()}else{t=new u}t.task=e;n(t)}function u(){this.task=null}u.prototype.call=function(){try{this.task.call()}catch(e){if(f.onerror){f.onerror(e)}else{s.push(e);o()}}finally{this.task=null;i[i.length]=this}}},{"./raw":9}],9:[function(e,t,r){(function(e){"use strict";t.exports=r;function r(e){if(!n.length){s();i=true}n[n.length]=e}var n=[];var i=false;var s;var o=0;var a=1024;function f(){while(oa){for(var t=0,r=n.length-o;t0){throw new Error("Invalid string. Length must be a multiple of 4")}var f=e.length;o="="===e.charAt(f-2)?2:"="===e.charAt(f-1)?1:0;a=new t(e.length*3/4-o);i=o>0?e.length-4:e.length;var u=0;function l(e){a[u++]=e}for(r=0,n=0;r>16);l((s&65280)>>8);l(s&255)}if(o===2){s=h(e.charAt(r))<<2|h(e.charAt(r+1))>>4;l(s&255)}else if(o===1){s=h(e.charAt(r))<<10|h(e.charAt(r+1))<<4|h(e.charAt(r+2))>>2;l(s>>8&255);l(s&255)}return a}function c(e){var t,r=e.length%3,i="",s,o;function a(e){return n.charAt(e)}function f(e){return a(e>>18&63)+a(e>>12&63)+a(e>>6&63)+a(e&63)}for(t=0,o=e.length-r;t>2);i+=a(s<<4&63);i+="==";break;case 2:s=(e[e.length-2]<<8)+e[e.length-1];i+=a(s>>10);i+=a(s>>4&63);i+=a(s<<2&63);i+="=";break}return i}e.toByteArray=l;e.fromByteArray=c})(typeof r==="undefined"?this.base64js={}:r)},{}],11:[function(e,t,r){t.exports={encode:e("./lib/encode"),decode:e("./lib/decode")}},{"./lib/decode":12,"./lib/encode":14}],12:[function(e,t,r){(function(r){var n=e("./dict");function i(e,t){i.position=0;i.encoding=t||null;i.data=!r.isBuffer(e)?new r(e):e;return i.next()}i.position=0;i.data=null;i.encoding=null;i.next=function(){switch(i.data[i.position]){case 100:return i.dictionary();break;case 108:return i.list();break;case 105:return i.integer();break;default:return i.bytes();break}};i.find=function(e){var t=i.position;var r=i.data.length;var n=i.data;while(t>3;if(e%8!==0)t++;return t}n.prototype.get=function(e){ -var t=e>>3;return t>e%8)};n.prototype.set=function(e,t){var r=e>>3;if(t||arguments.length===1){if(this.buffer.length>e%8}else if(r>e%8)}};n.prototype._grow=function(e){if(this.buffer.length=this._parserSize){var i=this._buffer.length===1?this._buffer[0]:r.concat(this._buffer);this._bufferSize-=this._parserSize;this._buffer=this._bufferSize?[i.slice(this._parserSize)]:[];this._parser(i.slice(0,this._parserSize))}n(null)};w.prototype._read=function(){};w.prototype._callback=function(e,t,r){if(!e)return;this._clearTimeout();if(!this.peerChoking&&!this._finished)this._updateTimeout();e.callback(t,r)};w.prototype._clearTimeout=function(){if(!this._timeout)return;clearTimeout(this._timeout);this._timeout=null};w.prototype._updateTimeout=function(){if(!this._timeoutMs||!this.requests.length||this._timeout)return;this._timeout=setTimeout(this._onTimeout.bind(this),this._timeoutMs);if(this._timeoutUnref&&this._timeout.unref)this._timeout.unref()};w.prototype._parse=function(e,t){this._parserSize=e;this._parser=t};w.prototype._message=function(e,t,n){var i=n?n.length:0;var s=new r(5+4*t.length);s.writeUInt32BE(s.length+i-4,0);s[4]=e;for(var o=0;o0){this._parse(t,this._onmessage)}else{this._onKeepAlive();this._parse(4,this._onmessagelength)}};w.prototype._onmessage=function(e){this._parse(4,this._onmessagelength);switch(e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:this._debug("got unknown message");return this.emit("unknownmessage",e)}};w.prototype._parseHandshake=function(){this._parse(1,function(e){var t=e.readUInt8(0);this._parse(t+48,function(e){var r=e.slice(0,t);if(r.toString()!=="BitTorrent protocol"){this._debug("Error: wire not speaking BitTorrent protocol (%s)",r.toString());this.end();return}e=e.slice(t);this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(e[7]&1),extended:!!(e[5]&16)});this._parse(4,this._onmessagelength)}.bind(this))}.bind(this))};w.prototype._onfinish=function(){this._finished=true;this.push(null);while(this.read()){}clearInterval(this._keepAliveInterval);this._parse(Number.MAX_VALUE,function(){});this.peerRequests=[];while(this.requests.length){this._callback(this.requests.shift(),new Error("wire was closed"),null)}};w.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._debugId+"] "+e[0];s.apply(null,e)};function S(e,t,r,n){for(var i=0;it)f=t;a=n;while(f--){if(o===t)o=0;r[o]=r[o===0?t-1:o-1];o++}if(e)r[o-1]+=e;var u=r[o-1];var h=r.length=e.maxConns){return}s("drain (%s queued, %s/%s peers)",e.numQueued,e.numPeers,e.maxConns);var t=e._queue.shift();if(!t)return;s("tcp connect attempt to %s",t.addr);var r=i(t.addr);var n={host:r[0],port:r[1]};if(e._hostname)n.localAddress=e._hostname;var o=t.conn=u.connect(n);o.once("connect",function(){t.onConnect()});o.once("error",function(e){t.destroy(e)});t.setConnectTimeout();o.on("close",function(){if(e.destroyed)return;if(t.retries>=p.length){s("conn %s closed: will not re-add (max %s attempts)",t.addr,p.length);return}var r=p[t.retries];s("conn %s closed: will re-add to queue in %sms (attempt %s)",t.addr,r,t.retries+1);var n=setTimeout(function i(){var r=e._addPeer(t.addr);if(r)r.retries=t.retries+1},r);if(n.unref)n.unref()})};m.prototype._onError=function(e){var t=this;t.emit("error",e);t.destroy()};m.prototype._validAddr=function(e){var t=this;var r=i(e);var n=r[0];var s=r[1];return s>0&&s<65535&&!(n==="127.0.0.1"&&s===t._port)}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/peer":19,"./lib/tcp-pool":20,_process:83,"addr-to-ip-port":34,buffer:36,debug:42,dezalgo:45,events:47,inherits:55,net:34,speedometer:22}],19:[function(e,t,r){var n=e("debug")("bittorrent-swarm:peer");var i=e("./webconn");var s=e("bittorrent-protocol");var o=25e3;var a=25e3;r.createWebRTCPeer=function(e,t){var r=new f(e.id);r.conn=e;r.swarm=t;if(r.conn.connected){r.onConnect()}else{r.conn.once("connect",function(){r.onConnect()});r.conn.once("error",function(e){r.destroy(e)});r.setConnectTimeout()}return r};r.createIncomingTCPPeer=function(e){var t=e.remoteAddress+":"+e.remotePort;var r=new f(t);r.conn=e;r.addr=t;r.onConnect();return r};r.createOutgoingTCPPeer=function(e,t){var r=new f(e);r.addr=e;r.swarm=t;return r};r.createWebPeer=function(e,t,r){var n=new f(e);n.swarm=r;n.conn=new i(e,t);n.onConnect();return n};function f(e){var t=this;t.id=e;n("new Peer %s",e);t.addr=null;t.conn=null;t.swarm=null;t.wire=null;t.connected=false;t.destroyed=false;t.timeout=null;t.retries=0;t.sentHandshake=false}f.prototype.onConnect=function(){var e=this;if(e.destroyed)return;e.connected=true;n("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 r=e.wire=new s;r.once("end",function(){e.destroy()});r.once("close",function(){e.destroy()});r.once("finish",function(){e.destroy()});r.once("error",function(t){e.destroy(t)});r.once("handshake",function(t,r){e.onHandshake(t,r)});e.setHandshakeTimeout();t.pipe(r).pipe(t);if(e.swarm&&!e.sentHandshake)e.handshake()};f.prototype.onHandshake=function(e,t){var r=this;if(!r.swarm)return;var i=e.toString("hex");var s=t.toString("hex");if(r.swarm.destroyed)return r.destroy(new Error("swarm already destroyed"));if(i!==r.swarm.infoHashHex){return r.destroy(new Error("unexpected handshake info hash for this swarm"))}if(s===r.swarm.peerIdHex){return r.destroy(new Error("refusing to handshake with self"))}n("Peer %s got handshake %s",r.id,i);clearTimeout(r.handshakeTimeout);r.retries=0;r.wire.on("download",function(e){if(r.destroyed)return;r.swarm.downloaded+=e;r.swarm.downloadSpeed(e);r.swarm.emit("download",e)});r.wire.on("upload",function(e){if(r.destroyed)return;r.swarm.uploaded+=e;r.swarm.uploadSpeed(e);r.swarm.emit("upload",e)});if(!r.sentHandshake)r.handshake();r.swarm.wires.push(r.wire);var o=r.addr;if(!o&&r.conn.remoteAddress){o=r.conn.remoteAddress+":"+r.conn.remotePort}r.swarm.emit("wire",r.wire,o)};f.prototype.handshake=function(){var e=this;e.wire.handshake(e.swarm.infoHash,e.swarm.peerId,e.swarm.handshakeOpts);e.sentHandshake=true};f.prototype.setConnectTimeout=function(){var e=this;clearTimeout(e.connectTimeout);e.connectTimeout=setTimeout(function(){e.destroy(new Error("connect timeout"))},o);if(e.connectTimeout.unref)e.connectTimeout.unref()};f.prototype.setHandshakeTimeout=function(){var e=this;clearTimeout(e.handshakeTimeout);e.handshakeTimeout=setTimeout(function(){e.destroy(new Error("handshake timeout"))},a);if(e.handshakeTimeout.unref)e.handshakeTimeout.unref()};f.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;t.connected=false;n("destroy %s (error: %s)",t.id,e&&(e.message||e));clearTimeout(t.connectTimeout);clearTimeout(t.handshakeTimeout);var r=t.swarm;var i=t.conn;var s=t.wire;t.conn=null;t.swarm=null;t.wire=null;if(r&&s){var o=r.wires.indexOf(s);if(o>=0)r.wires.splice(o,1)}if(i)i.destroy();if(s)s.destroy();if(r)r.removePeer(t.id)}},{"./webconn":21,"bittorrent-protocol":16,debug:42}],20:[function(e,t,r){(function(r){t.exports=f;var n=e("debug")("bittorrent-swarm:tcp-pool");var i=e("dezalgo");var s=e("net");var o=e("./peer");var a={};function f(e,t){var r=this;r.port=e;r.listening=false;r.swarms={};n("new TCPPool (port: %s, hostname: %s)",e,t);r.pendingConns=[];r.server=s.createServer();r.server.on("connection",function(e){r._onConnection(e)});r.server.on("error",function(e){r._onError(e)});r.server.on("listening",function(){r._onListening()});r.server.listen(r.port,t)}f.addSwarm=function(e){var t=a[e._port];if(!t)t=a[e._port]=new f(e._port,e._hostname);t.addSwarm(e);return t};f.removeSwarm=function(e,t){var n=a[e._port];if(!n)return t();n.removeSwarm(e);var i=0;for(var s in n.swarms){var o=n.swarms[s];if(o)i+=1}if(i===0)n.destroy(t);else r.nextTick(t)};f.getDefaultListenPort=function(e){for(var t in a){var r=a[t];if(r&&!r.swarms[e])return r.port}return 0};f.prototype.addSwarm=function(e){var t=this;if(t.swarms[e.infoHashHex]){r.nextTick(function(){e._onError(new Error("There is already a swarm with info hash "+e.infoHashHex+" "+"listening on port "+e._port))});return}t.swarms[e.infoHashHex]=e;if(t.listening){r.nextTick(function(){e._onListening(t.port)})}n("add swarm %s to tcp pool %s",e.infoHashHex,t.port)};f.prototype.removeSwarm=function(e){var t=this;n("remove swarm %s from tcp pool %s",e.infoHashHex,t.port);t.swarms[e.infoHashHex]=null};f.prototype.destroy=function(e){var t=this;if(e)e=i(e);n("destroy tcp pool %s",t.port);t.listening=false;t.pendingConns.forEach(function(e){e.destroy()});a[t.port]=null;try{t.server.close(e)}catch(r){if(e)e(null)}};f.prototype._onListening=function(){var e=this;var t=e.server.address()||{port:0};var r=t.port;n("tcp pool listening on %s",r);if(r!==e.port){a[e.port]=null;e.port=r;a[e.port]=e}e.listening=true;for(var i in e.swarms){var s=e.swarms[i];if(s)s._onListening(e.port)}};f.prototype._onConnection=function(e){var t=this;t.pendingConns.push(e);e.once("close",r);function r(){t.pendingConns.splice(t.pendingConns.indexOf(e))}var n=o.createIncomingTCPPeer(e);n.wire.once("handshake",function(i,s){var o=i.toString("hex");r();e.removeListener("close",r);var a=t.swarms[o];if(a){n.swarm=a;a._addIncomingPeer(n);n.onHandshake(i,s)}else{var f=new Error("Unexpected info hash "+o+" from incoming peer "+n.id+": destroying peer");n.destroy(f)}})};f.prototype._onError=function(e){var t=this;t.destroy();for(var r in t.swarms){var n=t.swarms[r];if(n){t.removeSwarm(n);n._onError(e)}}}}).call(this,e("_process"))},{"./peer":19,_process:83,debug:42,dezalgo:45,net:34}],21:[function(e,t,r){(function(r){t.exports=f;var n=e("bitfield");var i=e("debug")("bittorrent-swarm:webconn");var s=e("simple-get");var o=e("inherits");var a=e("bittorrent-protocol");o(f,a);function f(e,t){var s=this;a.call(this);s.url=e;s.parsedTorrent=t;s.setKeepAlive(true);s.on("handshake",function(t,i){s.handshake(t,new r(20).fill(e));var o=s.parsedTorrent.pieces.length;var a=new n(o);for(var f=0;f<=o;f++){a.set(f,true)}s.bitfield(a)});s.on("choke",function(){i("choke")});s.on("unchoke",function(){i("unchoke")});s.once("interested",function(){i("interested");s.unchoke()});s.on("uninterested",function(){i("uninterested")});s.on("bitfield",function(){i("bitfield")});s.on("request",function(e,t,r,n){i("request pieceIndex=%d offset=%d length=%d",e,t,r);s.httpRequest(e,t,r,n)})}f.prototype.httpRequest=function(e,t,r,n){var o=this;var a=e*o.parsedTorrent.pieceLength;var f=a+t;var u=f+r-1;i("Requesting pieceIndex=%d offset=%d length=%d start=%d end=%d",e,t,r,f,u);var h={url:o.url,method:"GET",headers:{"user-agent":"WebTorrent (http://webtorrent.io)",range:"bytes="+f+"-"+u}};s.concat(h,function(e,t,r){if(e)return n(e);if(r.statusCode<200||r.statusCode>=300){return n(new Error("Unexpected HTTP status code "+r.statusCode))}i("Got data of length %d",t.length);n(null,t)})}}).call(this,e("buffer").Buffer)},{bitfield:15,"bittorrent-protocol":16,buffer:36,debug:42,inherits:55,"simple-get":103}],22:[function(e,t,r){arguments[4][17][0].apply(r,arguments)},{dup:17}],23:[function(e,t,r){(function(r,n){t.exports=m;var i=e("events").EventEmitter;var s=e("debug")("bittorrent-tracker");var o=e("inherits");var a=e("once");var f=e("run-parallel");var u=e("uniq");var h=e("url");var l=e("./lib/common");var c=e("./lib/client/http-tracker");var d=e("./lib/client/udp-tracker");var p=e("./lib/client/websocket-tracker");o(m,i);function m(e,t,o,a){var f=this;if(!(f instanceof m))return new m(e,t,o,a);i.call(f);if(!a)a={};f._peerId=n.isBuffer(e)?e:new n(e,"hex");f._peerIdHex=f._peerId.toString("hex");f._peerIdBinary=f._peerId.toString("binary");f._infoHash=n.isBuffer(o.infoHash)?o.infoHash:new n(o.infoHash,"hex");f._infoHashHex=f._infoHash.toString("hex");f._infoHashBinary=f._infoHash.toString("binary");f.torrentLength=o.length;f.destroyed=false;f._port=t;f._rtcConfig=a.rtcConfig;f._wrtc=a.wrtc;s("new client %s",f._infoHashHex);var l=!!f._wrtc||typeof window!=="undefined";var v=typeof o.announce==="string"?[o.announce]:o.announce==null?[]:o.announce;v=v.map(function(e){e=e.toString();if(e[e.length-1]==="/"){e=e.substring(0,e.length-1)}return e});v=u(v);f._trackers=v.map(function(e){var t=h.parse(e).protocol;if((t==="http:"||t==="https:")&&typeof c==="function"){return new c(f,e)}else if(t==="udp:"&&typeof d==="function"){return new d(f,e)}else if((t==="ws:"||t==="wss:")&&l){return new p(f,e)}else{r.nextTick(function(){var t=new Error("unsupported tracker protocol for "+e);f.emit("warning",t)})}return null}).filter(Boolean)}m.scrape=function(e,t,r){r=a(r);var i=new n("01234567890123456789");var s=6881;var o={infoHash:Array.isArray(t)?t[0]:t,announce:[e]};var f=new m(i,s,o);f.once("error",r);var u=Array.isArray(t)?t.length:1;var h={};f.on("scrape",function(e){u-=1;h[e.infoHash]=e;if(u===0){f.destroy();var t=Object.keys(h);if(t.length===1){r(null,h[t[0]])}else{r(null,h)}}});t=Array.isArray(t)?t.map(function(e){return new n(e,"hex")}):new n(t,"hex");f.scrape({infoHash:t})};m.prototype.start=function(e){var t=this;s("send `start`");e=t._defaultAnnounceOpts(e);e.event="started";t._announce(e);t._trackers.forEach(function(e){e.setInterval()})};m.prototype.stop=function(e){var t=this;s("send `stop`");e=t._defaultAnnounceOpts(e);e.event="stopped";t._announce(e)};m.prototype.complete=function(e){var t=this;s("send `complete`");if(!e)e={};if(e.downloaded==null&&t.torrentLength!=null){e.downloaded=t.torrentLength}e=t._defaultAnnounceOpts(e);e.event="completed";t._announce(e)};m.prototype.update=function(e){var t=this;s("send `update`");e=t._defaultAnnounceOpts(e);if(e.event)delete e.event;t._announce(e)};m.prototype._announce=function(e){var t=this;t._trackers.forEach(function(t){t.announce(e)})};m.prototype.scrape=function(e){var t=this;s("send `scrape`");if(!e)e={};t._trackers.forEach(function(t){t.scrape(e)})};m.prototype.setInterval=function(e){var t=this;s("setInterval %d",e);t._trackers.forEach(function(t){t.setInterval(e)})};m.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;s("destroy");var r=t._trackers.map(function(e){return function(t){e.destroy(t)}});f(r,e);t._trackers=[]};m.prototype._defaultAnnounceOpts=function(e){var t=this;if(!e)e={};if(e.numwant==null)e.numwant=l.DEFAULT_ANNOUNCE_PEERS;if(e.uploaded==null)e.uploaded=0;if(e.downloaded==null)e.downloaded=0;if(e.left==null&&t.torrentLength!=null){e.left=t.torrentLength-e.downloaded}return e}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/client/http-tracker":34,"./lib/client/udp-tracker":34,"./lib/client/websocket-tracker":25,"./lib/common":26,_process:83,buffer:36,debug:42,events:47,inherits:55,once:73,"run-parallel":101,uniq:119,url:120}],24:[function(e,t,r){t.exports=s;var n=e("events").EventEmitter;var i=e("inherits");i(s,n);function s(e,t){var r=this;n.call(r);r.client=e;r.announceUrl=t;r.interval=null;r.destroyed=false}s.prototype.setInterval=function(e){var t=this;if(t.interval)return;if(e==null)e=t.DEFAULT_ANNOUNCE_INTERVAL;clearInterval(t.interval);if(e){var r=t.announce.bind(t,t.client._defaultAnnounceOpts());t.interval=setInterval(r,e);if(t.interval.unref)t.interval.unref()}}},{events:47,inherits:55}],25:[function(e,t,r){t.exports=d;var n=e("debug")("bittorrent-tracker:websocket-tracker");var i=e("hat");var s=e("inherits");var o=e("simple-peer");var a=e("simple-websocket");var f=e("../common");var u=e("./tracker");var h={};var l=30*1e3;var c=5*1e3;s(d,u);function d(e,t,r){var i=this;u.call(i,e,t);n("new websocket tracker %s",t);i.peers={};i.socket=null;i.reconnecting=false;i._openSocket()}d.prototype.DEFAULT_ANNOUNCE_INTERVAL=30*1e3;d.prototype.announce=function(e){var t=this;if(t.destroyed||t.reconnecting)return;if(!t.socket.connected){return t.socket.once("connect",t.announce.bind(t,e))}var r=Math.min(e.numwant,10);t._generateOffers(r,function(n){var i={numwant:r,uploaded:e.uploaded||0,downloaded:e.downloaded,event:e.event,info_hash:t.client._infoHashBinary,peer_id:t.client._peerIdBinary,offers:n};if(t._trackerId)i.trackerid=t._trackerId;t._send(i)})};d.prototype.scrape=function(e){var t=this;if(t.destroyed||t.reconnecting)return;t._onSocketError(new Error("scrape not supported "+t.announceUrl))};d.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;clearInterval(t.interval);h[t.announceUrl]=null;t.socket.removeListener("connect",t._onSocketConnectBound);t.socket.removeListener("data",t._onSocketDataBound);t.socket.removeListener("close",t._onSocketCloseBound);t.socket.removeListener("error",t._onSocketErrorBound);t._onSocketConnectBound=null;t._onSocketErrorBound=null;t._onSocketDataBound=null;t._onSocketCloseBound=null;t.socket.on("error",p);try{t.socket.destroy(e)}catch(r){if(e)e()}t.socket=null};d.prototype._openSocket=function(){var e=this;e.destroyed=false;e._onSocketConnectBound=e._onSocketConnect.bind(e);e._onSocketErrorBound=e._onSocketError.bind(e);e._onSocketDataBound=e._onSocketData.bind(e);e._onSocketCloseBound=e._onSocketClose.bind(e);e.socket=h[e.announceUrl];if(!e.socket){e.socket=h[e.announceUrl]=new a(e.announceUrl);e.socket.on("connect",e._onSocketConnectBound)}e.socket.on("data",e._onSocketDataBound);e.socket.on("close",e._onSocketCloseBound);e.socket.on("error",e._onSocketErrorBound)};d.prototype._onSocketConnect=function(){var e=this;if(e.destroyed)return;if(e.reconnecting){e.reconnecting=false;e.announce(e.client._defaultAnnounceOpts())}};d.prototype._onSocketData=function(e){var t=this;if(t.destroyed)return;if(!(typeof e==="object"&&e!==null)){return t.client.emit("warning",new Error("Invalid tracker response"))}if(e.info_hash!==t.client._infoHashBinary){n("ignoring websocket data from %s for %s (looking for %s: reused socket)",t.announceUrl,f.binaryToHex(e.info_hash),t.client._infoHashHex);return}if(e.peer_id&&e.peer_id===t.client._peerIdBinary){return}n("received %s from %s for %s",JSON.stringify(e),t.announceUrl,t.client._infoHashHex);var r=e["failure reason"];if(r)return t.client.emit("warning",new Error(r));var i=e["warning message"];if(i)t.client.emit("warning",new Error(i));var s=e.interval||e["min interval"];if(s)t.setInterval(s*1e3);var a=e["tracker id"];if(a){t._trackerId=a}if(e.complete){t.client.emit("update",{announce:t.announceUrl,complete:e.complete,incomplete:e.incomplete})}var u;if(e.offer&&e.peer_id){u=new o({trickle:false,config:t.client._rtcConfig,wrtc:t.client._wrtc});u.id=f.binaryToHex(e.peer_id);u.once("signal",function(r){var n={info_hash:t.client._infoHashBinary,peer_id:t.client._peerIdBinary, -to_peer_id:e.peer_id,answer:r,offer_id:e.offer_id};if(t._trackerId)n.trackerid=t._trackerId;t._send(n)});u.signal(e.offer);t.client.emit("peer",u)}if(e.answer&&e.peer_id){u=t.peers[f.binaryToHex(e.offer_id)];if(u){u.id=f.binaryToHex(e.peer_id);u.signal(e.answer);t.client.emit("peer",u)}else{n("got unexpected answer: "+JSON.stringify(e.answer))}}};d.prototype._onSocketClose=function(){var e=this;if(e.destroyed)return;e.destroy();e._startReconnectTimer()};d.prototype._onSocketError=function(e){var t=this;if(t.destroyed)return;t.destroy();t.client.emit("warning",e);t._startReconnectTimer()};d.prototype._startReconnectTimer=function(){var e=this;var t=Math.floor(Math.random()*l)+c;e.reconnecting=true;var r=setTimeout(function(){e._openSocket()},t);if(r.unref)r.unref();n("reconnecting socket in %s ms",t)};d.prototype._send=function(e){var t=this;if(t.destroyed)return;var r=JSON.stringify(e);n("send %s",r);t.socket.send(r)};d.prototype._generateOffers=function(e,t){var r=this;var s=[];n("generating %s offers",e);for(var a=0;a=this.size){var i=r.concat(this._buffered);this._bufferedBytes-=this.size;this.push(i.slice(0,this.size));this._buffered=[i.slice(this.size,i.length)]}n()};o.prototype._flush=function(){if(this._bufferedBytes&&this._zeroPadding){var e=new r(this.size-this._bufferedBytes);e.fill(0);this._buffered.push(e);this.push(r.concat(this._buffered));this._buffered=null}else if(this._bufferedBytes){this.push(r.concat(this._buffered));this._buffered=null}this.push(null)}}).call(this,e("buffer").Buffer)},{buffer:36,defined:44,inherits:55,"readable-stream":33}],28:[function(e,t,r){(function(r){t.exports=a;var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};var i=e("core-util-is");i.inherits=e("inherits");var s=e("./_stream_readable");var o=e("./_stream_writable");i.inherits(a,s);u(n(o.prototype),function(e){if(!a.prototype[e])a.prototype[e]=o.prototype[e]});function a(e){if(!(this instanceof a))return new a(e);s.call(this,e);o.call(this,e);if(e&&e.readable===false)this.readable=false;if(e&&e.writable===false)this.writable=false;this.allowHalfOpen=true;if(e&&e.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",f)}function f(){if(this.allowHalfOpen||this._writableState.ended)return;r.nextTick(this.end.bind(this))}function u(e,t){for(var r=0,n=e.length;r0){if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var o=new Error("stream.unshift() after end event");e.emit("error",o)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)y(e)}w(e,t)}}else if(!i){t.reading=false}return d(t)}function d(e){return!e.ended&&(e.needReadable||e.length=p){e=p}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function v(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(isNaN(e)||a.isNull(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=m(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else return t.length}return e}l.prototype.read=function(e){u("read",e);var t=this._readableState;var r=e;if(!a.isNumber(e)||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){u("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)T(this);else y(this);return null}e=v(e,t);if(e===0&&t.ended){if(t.length===0)T(this);return null}var n=t.needReadable;u("need readable",n);if(t.length===0||t.length-e0)i=U(e,t);else i=null;if(a.isNull(i)){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)T(this);if(!a.isNull(i))this.emit("data",i);return i};function g(e,t){var r=null;if(!a.isBuffer(t)&&!a.isString(t)&&!a.isNullOrUndefined(t)&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function _(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;y(e)}function y(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)r.nextTick(function(){b(e)});else b(e)}}function b(e){u("emit readable");e.emit("readable");A(e)}function w(e,t){if(!t.readingMore){t.readingMore=true;r.nextTick(function(){S(e,t)})}}function S(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(s)a=r.join("");else a=i.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;r.nextTick(function(){if(!t.endEmitted&&t.length===0){t.endEmitted=true;e.readable=false;e.emit("end")}})}}function I(e,t){for(var r=0,n=e.length;r1){var r=[];for(var n=0;n1)return new u(e,arguments[1]);return new u(e)}this.length=0;this.parent=undefined;if(typeof e==="number"){return h(this,e)}if(typeof e==="string"){return l(this,e,arguments.length>1?arguments[1]:"utf8")}return c(this,e)}function h(e,t){e=y(e,t<0?0:b(t)|0);if(!u.TYPED_ARRAY_SUPPORT){for(var r=0;r>>1;if(r)e.parent=o;return e}function b(e){if(e>=f()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+f().toString(16)+" bytes")}return e|0}function w(e,t){if(!(this instanceof w))return new w(e,t);var r=new u(e,t);delete r.parent;return r}u.isBuffer=function te(e){return!!(e!=null&&e._isBuffer)};u.compare=function re(e,t){if(!u.isBuffer(e)||!u.isBuffer(t)){throw new TypeError("Arguments must be Buffers")}if(e===t)return 0;var r=e.length;var n=t.length;var i=0;var s=Math.min(r,n);while(i>>1;case"base64":return Q(e).length;default:if(n)return X(e).length;t=(""+t).toLowerCase();n=true}}}u.byteLength=S;u.prototype.length=undefined;u.prototype.parent=undefined;function x(e,t,r){var n=false;t=t|0;r=r===undefined||r===Infinity?this.length:r|0;if(!e)e="utf8";if(t<0)t=0;if(r>this.length)r=this.length;if(r<=t)return"";while(true){switch(e){case"hex":return O(this,t,r);case"utf8":case"utf-8":return B(this,t,r);case"ascii":return P(this,t,r);case"binary":return F(this,t,r);case"base64":return L(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase();n=true}}}u.prototype.toString=function se(){var e=this.length|0;if(e===0)return"";if(arguments.length===0)return B(this,0,e);return x.apply(this,arguments)};u.prototype.equals=function oe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return true;return u.compare(this,e)===0};u.prototype.inspect=function ae(){var e="";var t=r.INSPECT_MAX_BYTES;if(this.length>0){e=this.toString("hex",0,t).match(/.{2}/g).join(" ");if(this.length>t)e+=" ... "}return""};u.prototype.compare=function fe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return 0;return u.compare(this,e)};u.prototype.indexOf=function ue(e,t){if(t>2147483647)t=2147483647;else if(t<-2147483648)t=-2147483648;t>>=0;if(this.length===0)return-1;if(t>=this.length)return-1;if(t<0)t=Math.max(this.length+t,0);if(typeof e==="string"){if(e.length===0)return-1;return String.prototype.indexOf.call(this,e,t)}if(u.isBuffer(e)){return r(this,e,t)}if(typeof e==="number"){if(u.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,e,t)}return r(this,[e],t)}function r(e,t,r){var n=-1;for(var i=0;r+ii){n=i}}var s=t.length;if(s%2!==0)throw new Error("Invalid hex string");if(n>s/2){n=s/2}for(var o=0;os)r=s;if(e.length>0&&(r<0||t<0)||t>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!n)n="utf8";var o=false;for(;;){switch(n){case"hex":return k(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":return A(this,e,t,r);case"binary":return U(this,e,t,r);case"base64":return T(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase();o=true}}};u.prototype.toJSON=function de(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function L(e,t,r){if(t===0&&r===e.length){return n.fromByteArray(e)}else{return n.fromByteArray(e.slice(t,r))}}function B(e,t,r){r=Math.min(e.length,r);var n=[];var i=t;while(i239?4:s>223?3:s>191?2:1;if(i+a<=r){var f,u,h,l;switch(a){case 1:if(s<128){o=s}break;case 2:f=e[i+1];if((f&192)===128){l=(s&31)<<6|f&63;if(l>127){o=l}}break;case 3:f=e[i+1];u=e[i+2];if((f&192)===128&&(u&192)===128){l=(s&15)<<12|(f&63)<<6|u&63;if(l>2047&&(l<55296||l>57343)){o=l}}break;case 4:f=e[i+1];u=e[i+2];h=e[i+3];if((f&192)===128&&(u&192)===128&&(h&192)===128){l=(s&15)<<18|(f&63)<<12|(u&63)<<6|h&63;if(l>65535&&l<1114112){o=l}}}}if(o===null){o=65533;a=1}else if(o>65535){o-=65536;n.push(o>>>10&1023|55296);o=56320|o&1023}n.push(o);i+=a}return R(n)}var C=4096;function R(e){var t=e.length;if(t<=C){return String.fromCharCode.apply(String,e)}var r="";var n=0;while(nn)r=n;var i="";for(var s=t;sr){e=r}if(t<0){t+=r;if(t<0)t=0}else if(t>r){t=r}if(tr)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUIntLE=function me(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s0&&(i*=256)){n+=this[e+--t]*i}return n};u.prototype.readUInt8=function ge(e,t){if(!t)D(e,1,this.length);return this[e]};u.prototype.readUInt16LE=function _e(e,t){if(!t)D(e,2,this.length);return this[e]|this[e+1]<<8};u.prototype.readUInt16BE=function ye(e,t){if(!t)D(e,2,this.length);return this[e]<<8|this[e+1]};u.prototype.readUInt32LE=function be(e,t){if(!t)D(e,4,this.length);return(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};u.prototype.readUInt32BE=function we(e,t){if(!t)D(e,4,this.length);return this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};u.prototype.readIntLE=function Se(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s=i)n-=Math.pow(2,8*t);return n};u.prototype.readIntBE=function xe(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=t;var i=1;var s=this[e+--n];while(n>0&&(i*=256)){s+=this[e+--n]*i}i*=128;if(s>=i)s-=Math.pow(2,8*t);return s};u.prototype.readInt8=function ke(e,t){if(!t)D(e,1,this.length);if(!(this[e]&128))return this[e];return(255-this[e]+1)*-1};u.prototype.readInt16LE=function Ee(e,t){if(!t)D(e,2,this.length);var r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};u.prototype.readInt16BE=function Ae(e,t){if(!t)D(e,2,this.length);var r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};u.prototype.readInt32LE=function Ue(e,t){if(!t)D(e,4,this.length);return this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};u.prototype.readInt32BE=function Te(e,t){if(!t)D(e,4,this.length);return this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};u.prototype.readFloatLE=function Ie(e,t){if(!t)D(e,4,this.length);return i.read(this,e,true,23,4)};u.prototype.readFloatBE=function Le(e,t){ +(function(e){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=e()}else if(typeof define==="function"&&define.amd){define([],e)}else{var t;if(typeof window!=="undefined"){t=window}else if(typeof global!=="undefined"){t=global}else if(typeof self!=="undefined"){t=self}else{t=this}t.WebTorrent=e()}})(function(){var e,t,r;return function n(e,t,r){function i(o,a){if(!t[o]){if(!e[o]){var f=typeof require=="function"&&require;if(!a&&f)return f(o,!0);if(s)return s(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var h=t[o]={exports:{}};e[o][0].call(h.exports,function(t){var r=e[o][1][t];return i(r?r:t)},h,h.exports,n,e,t,r)}return t[o].exports}var s=typeof require=="function"&&require;for(var o=0;o=0)y();else if(l.indexOf(g)>=0)w();else if(c.indexOf(g)>=0)S();else if(d.indexOf(g)>=0)x();else v(r,new Error('Unsupported file type "'+g+'": Cannot append to DOM'));function y(){if(!p){return v(r,new Error("Video/audio streaming is not supported in your browser. You can still share "+"or download "+e.name+" (once it's fully downloaded). Use Chrome for "+"MediaSource support."))}var s=f.indexOf(g)>=0?"video":"audio";if(a.indexOf(g)>=0)h();else l();function h(){n("Use `videostream` package for "+e.name);y();u.addEventListener("error",d);u.addEventListener("playing",b);o(e,u)}function l(){n("Use MediaSource API for "+e.name);y();u.addEventListener("error",m);u.addEventListener("playing",b);e.createReadStream().pipe(new i(u,{extname:g}));if(_)u.currentTime=_}function c(){n("Use Blob URL for "+e.name);y();u.addEventListener("error",k);u.addEventListener("playing",b);e.getBlobURL(function(e,t){if(e)return k(e);u.src=t;if(_)u.currentTime=_})}function d(e){n("videostream error: fallback to MediaSource API: %o",e.message||e);u.removeEventListener("error",d);u.removeEventListener("playing",b);l()}function m(e){n("MediaSource API error: fallback to Blob URL: %o",e.message||e);u.removeEventListener("error",m);u.removeEventListener("playing",b);c()}function y(e){if(!u){u=document.createElement(s);u.controls=true;u.autoplay=true;u.play();u.addEventListener("progress",function(){_=u.currentTime});t.appendChild(u)}}}function b(){u.removeEventListener("playing",b);r(null,u)}function w(){u=document.createElement("audio");u.controls=true;u.autoplay=true;t.appendChild(u);e.getBlobURL(function(e,t){if(e)return k(e);u.addEventListener("error",k);u.addEventListener("playing",b);u.src=t;u.play()})}function S(){e.getBlobURL(function(n,i){if(n)return k(n);u=document.createElement("img");u.src=i;u.alt=e.name;t.appendChild(u);r(null,u)})}function x(){e.getBlobURL(function(e,n){if(e)return k(e);u=document.createElement("iframe");u.src=n;if(g!==".pdf")u.sandbox="allow-forms allow-scripts";t.appendChild(u);r(null,u)})}function k(t){if(u)u.remove();t.message='Error appending file "'+e.name+'" to DOM: '+t.message;n(t.message);if(r)r(t)}};function m(){}function v(e,t,n){r.nextTick(function(){if(e)e(t,n)})}}).call(this,e("_process"))},{_process:83,debug:42,mediasource:63,path:77,videostream:124}],2:[function(e,t,r){t.exports=o;var n=e("debug")("webtorrent:file-stream");var i=e("inherits");var s=e("stream");i(o,s.Readable);function o(e,t){s.Readable.call(this,t);this.destroyed=false;this._torrent=e._torrent;var r=t&&t.start||0;var n=t&&t.end||e.length-1;var i=e._torrent.pieceLength;this._startPiece=(r+e.offset)/i|0;this._endPiece=(n+e.offset)/i|0;this._piece=this._startPiece;this._offset=r+e.offset-this._startPiece*i;this._missing=n-r+1;this._reading=false;this._notifying=false;this._criticalLength=Math.min(1024*1024/i|0,2)}o.prototype._read=function(){if(this._reading)return;this._reading=true;this._notify()};o.prototype._notify=function(){var e=this;if(!e._reading||e._missing===0)return;if(!e._torrent.bitfield.get(e._piece)){return e._torrent.critical(e._piece,e._piece+e._criticalLength)}if(e._notifying)return;e._notifying=true;var t=e._piece;e._torrent.store.get(t,function(r,i){e._notifying=false;if(e.destroyed)return;if(r)return e.destroy(r);n("read %s (length %s) (err %s)",t,i.length,r&&r.message);if(e._offset){i=i.slice(e._offset);e._offset=0}if(e._missing0){return r[Math.random()*r.length|0]}else{return-1}}},{}],6:[function(e,t,r){(function(r,n){t.exports=H;var i=e("addr-to-ip-port");var s=e("bitfield");var o=e("chunk-store-stream/write");var a=e("create-torrent");var f=e("debug")("webtorrent:torrent");var u=e("torrent-discovery");var h=e("events").EventEmitter;var l=e("xtend/mutable");var c=e("fs-chunk-store");var d=e("immediate-chunk-store");var p=e("inherits");var m=e("multistream");var v=e("os");var g=e("run-parallel");var _=e("parse-torrent");var y=e("path");var b=e("path-exists");var w=e("torrent-piece");var S=e("pump");var x=e("random-iterate");var k=e("re-emitter");var E=e("simple-sha1");var A=e("bittorrent-swarm");var U=e("uniq");var T=e("ut_metadata");var I=e("ut_pex");var L=e("./file");var B=e("./rarity-map");var C=e("./server");var R=128*1024;var P=3e4;var F=5e3;var O=3*w.BLOCK_LENGTH;var M=.5;var D=1;var N=1e4;var z=2;var j=y.join(b.sync("/tmp")?"/tmp":v.tmpDir(),"webtorrent");p(H,h);function H(e,t){var r=this;h.call(r);if(!f.enabled)r.setMaxListeners(0);f("new torrent");r.client=t.client;r.announce=t.announce;r.urlList=t.urlList;r.path=t.path;r._store=t.store||c;r.strategy=t.strategy||"sequential";r._rechokeNumSlots=t.uploads===false||t.uploads===0?0:+t.uploads||10;r._rechokeOptimisticWire=null;r._rechokeOptimisticTime=0;r._rechokeIntervalId=null;r.ready=false;r.destroyed=false;r.metadata=null;r.store=null;r.numBlockedPeers=0;r.files=null;r.done=false;r._amInterested=false;r._selections=[];r._critical=[];r._servers=[];if(e)r._onTorrentId(e)}Object.defineProperty(H.prototype,"timeRemaining",{get:function(){if(this.done)return 0;if(this.swarm.downloadSpeed()===0)return Infinity;else return(this.length-this.downloaded)/this.swarm.downloadSpeed()*1e3}});Object.defineProperty(H.prototype,"downloaded",{get:function(){var e=0;for(var t=0,r=this.pieces.length;tt||e<0||t>=i.pieces.length){throw new Error("invalid selection ",e,":",t)}r=Number(r)||0;f("select %s-%s (priority %s)",e,t,r);i._selections.push({from:e,to:t,offset:0,priority:r,notify:n||W});i._selections.sort(function(e,t){return t.priority-e.priority});i._updateSelections()};H.prototype.deselect=function(e,t,r){var n=this;r=Number(r)||0;f("deselect %s-%s (priority %s)",e,t,r);for(var i=0;i2*(t.swarm.numConns-t.swarm.numPeers)&&e.amInterested){e.destroy()}else{r=setTimeout(n,F);if(r.unref)r.unref()}}var i=0;function s(){if(e.peerPieces.length!==t.pieces.length)return;for(;iR){return e.destroy()}if(t.pieces[r])return;t.store.get(r,{offset:n,length:i},s)});e.bitfield(t.bitfield);e.interested();r=setTimeout(n,F);if(r.unref)r.unref();e.isSeeder=false;s()};H.prototype._updateSelections=function(){var e=this;if(!e.swarm||e.destroyed)return;if(!e.metadata)return e.once("metadata",e._updateSelections.bind(e));r.nextTick(e._gcSelections.bind(e));e._updateInterest();e._update()};H.prototype._gcSelections=function(){var e=this;for(var t=0;t=r)return;var n=q(e,D);f(false)||f(true);function i(t,r,n,i){return function(s){return s>=t&&s<=r&&!(s in n)&&e.peerPieces.get(s)&&(!i||i(s))}}function s(){if(e.requests.length)return;var r=t._selections.length;while(r--){var n=t._selections[r];var s;if(t.strategy==="rarest"){var o=n.from+n.offset;var a=n.to;var f=a-o+1;var u={};var h=0;var l=i(o,a,u);while(h=n.from+n.offset;--s){if(!e.peerPieces.get(s))continue;if(t._request(e,s,false))return}}}}function o(){var r=e.downloadSpeed()||1;if(r>O)return function(){return true};var n=Math.max(1,e.requests.length)*w.BLOCK_LENGTH/r;var i=10;var s=0;return function(e){if(!i||t.bitfield.get(e))return true;var o=t.pieces[e].missing;for(;s0)continue;i--;return false}return true}}function a(e){var r=e;for(var n=e;n=n)return true;var s=o();for(var f=0;f0)e._rechokeOptimisticTime-=1;else e._rechokeOptimisticWire=null;var t=[];e.swarm.wires.forEach(function(r){if(!r.isSeeder&&r!==e._rechokeOptimisticWire){t.push({wire:r,downloadSpeed:r.downloadSpeed(),uploadSpeed:r.uploadSpeed(),salt:Math.random(),isChoked:true})}});t.sort(o);var r=0;var n=0;for(;n=O)continue;if(2*u>n||u>s)continue;o=f;s=u}if(!o)return false;for(a=0;a=o)return false;var a=i.pieces[t];var u=a.reserve();if(u===-1&&n&&i._hotswap(e,t)){u=a.reserve()}if(u===-1)return false;var h=i._reservations[t];if(!h)h=i._reservations[t]=[];var l=h.indexOf(null);if(l===-1)l=h.length;h[l]=e;var c=a.chunkOffset(u);var d=a.chunkLength(u);e.request(t,c,d,function m(r,n){if(!i.ready)return i.once("ready",function(){m(r,n)});if(h[l]===e)h[l]=null;if(a!==i.pieces[t])return p();if(r){f("error getting piece %s (offset: %s length: %s) from %s: %s",t,c,d,e.remoteAddress+":"+e.remotePort,r.message);a.cancel(u);p();return}f("got piece %s (offset: %s length: %s) from %s",t,c,d,e.remoteAddress+":"+e.remotePort);if(!a.set(u,n,e))return p();var s=a.flush();E(s,function(e){if(e===i._hashes[t]){if(!i.pieces[t])return;f("piece verified %s",t);i.pieces[t]=null;i._reservations[t]=null;i.bitfield.set(t,true);i.store.put(t,s);i.swarm.wires.forEach(function(e){e.have(t)});i._checkDone()}else{i.pieces[t]=new w(a.length);i.emit("warning",new Error("Piece "+t+" failed verification"))}p()})});function p(){r.nextTick(function(){i._update()})}return true};H.prototype._checkDone=function(){var e=this;if(e.destroyed)return;e.files.forEach(function(t){if(t.done)return;for(var r=t._startPiece;r<=t._endPiece;++r){if(!e.bitfield.get(r))return}t.done=true;t.emit("done");f("file done: "+t.name)});if(e.files.every(function(e){return e.done})){e.done=true;e.emit("done");f("torrent done: "+e.infoHash);if(e.discovery.tracker)e.discovery.tracker.complete()}e._gcSelections()};H.prototype.load=function(e,t){var r=this;if(!Array.isArray(e))e=[e];if(!t)t=W;var n=new m(e);var i=new o(r.store,r.pieceLength);S(n,i,function(e){if(e)return t(e);r.pieces.forEach(function(e,t){r.pieces[t]=null;r._reservations[t]=null;r.bitfield.set(t,true)});r._checkDone();t(null)})};H.prototype.createServer=function(e){var t=this;if(typeof C!=="function")return;var r=new C(t,e);t._servers.push(r);return r};H.prototype._onError=function(e){var t=this;f("torrent error: %s",e.message||e);t.emit("error",e);t.destroy()};function q(e,t){return Math.ceil(2+t*e.downloadSpeed()/w.BLOCK_LENGTH)}function G(e){return Math.random()*e|0}function W(){}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./file":3,"./rarity-map":5,"./server":34,_process:83,"addr-to-ip-port":7,bitfield:15,"bittorrent-swarm":18,"chunk-store-stream/write":38,"create-torrent":41,debug:42,events:47,"fs-chunk-store":64,"immediate-chunk-store":54,inherits:55,multistream:72,os:74,"parse-torrent":76,path:77,"path-exists":78,pump:84,"random-iterate":89,"re-emitter":90,"run-parallel":101,"simple-sha1":105,"torrent-discovery":116,"torrent-piece":117,uniq:119,ut_metadata:122,ut_pex:34,"xtend/mutable":127}],7:[function(e,t,r){var n=/^\[?([^\]]+)\]?:(\d+)$/;var i={};var s=0;t.exports=function o(e){if(s===1e5)t.exports.reset();if(!i[e]){var r=n.exec(e);if(!r)throw new Error("invalid addr: "+e);i[e]=[r[1],Number(r[2])];s+=1}return i[e]};t.exports.reset=function a(){i={};s=0}},{}],8:[function(e,t,r){"use strict";var n=e("./raw");var i=[];var s=[];var o=n.makeRequestCallFromTimer(a);function a(){if(s.length){throw s.shift()}}t.exports=f;function f(e){var t;if(i.length){t=i.pop()}else{t=new u}t.task=e;n(t)}function u(){this.task=null}u.prototype.call=function(){try{this.task.call()}catch(e){if(f.onerror){f.onerror(e)}else{s.push(e);o()}}finally{this.task=null;i[i.length]=this}}},{"./raw":9}],9:[function(e,t,r){(function(e){"use strict";t.exports=r;function r(e){if(!n.length){s();i=true}n[n.length]=e}var n=[];var i=false;var s;var o=0;var a=1024;function f(){while(oa){for(var t=0,r=n.length-o;t0){throw new Error("Invalid string. Length must be a multiple of 4")}var f=e.length;o="="===e.charAt(f-2)?2:"="===e.charAt(f-1)?1:0;a=new t(e.length*3/4-o);i=o>0?e.length-4:e.length;var u=0;function l(e){a[u++]=e}for(r=0,n=0;r>16);l((s&65280)>>8);l(s&255)}if(o===2){s=h(e.charAt(r))<<2|h(e.charAt(r+1))>>4;l(s&255)}else if(o===1){s=h(e.charAt(r))<<10|h(e.charAt(r+1))<<4|h(e.charAt(r+2))>>2;l(s>>8&255);l(s&255)}return a}function c(e){var t,r=e.length%3,i="",s,o;function a(e){return n.charAt(e)}function f(e){return a(e>>18&63)+a(e>>12&63)+a(e>>6&63)+a(e&63)}for(t=0,o=e.length-r;t>2);i+=a(s<<4&63);i+="==";break;case 2:s=(e[e.length-2]<<8)+e[e.length-1];i+=a(s>>10);i+=a(s>>4&63);i+=a(s<<2&63);i+="=";break}return i}e.toByteArray=l;e.fromByteArray=c})(typeof r==="undefined"?this.base64js={}:r)},{}],11:[function(e,t,r){t.exports={encode:e("./lib/encode"),decode:e("./lib/decode")}},{"./lib/decode":12,"./lib/encode":14}],12:[function(e,t,r){(function(r){var n=e("./dict");function i(e,t){i.position=0;i.encoding=t||null;i.data=!r.isBuffer(e)?new r(e):e;return i.next()}i.position=0;i.data=null;i.encoding=null;i.next=function(){switch(i.data[i.position]){case 100:return i.dictionary();break;case 108:return i.list();break;case 105:return i.integer();break;default:return i.bytes();break}};i.find=function(e){var t=i.position;var r=i.data.length;var n=i.data;while(t>3;if(e%8!==0)t++;return t; +}n.prototype.get=function(e){var t=e>>3;return t>e%8)};n.prototype.set=function(e,t){var r=e>>3;if(t||arguments.length===1){if(this.buffer.length>e%8}else if(r>e%8)}};n.prototype._grow=function(e){if(this.buffer.length=this._parserSize){var i=this._buffer.length===1?this._buffer[0]:r.concat(this._buffer);this._bufferSize-=this._parserSize;this._buffer=this._bufferSize?[i.slice(this._parserSize)]:[];this._parser(i.slice(0,this._parserSize))}n(null)};w.prototype._read=function(){};w.prototype._callback=function(e,t,r){if(!e)return;this._clearTimeout();if(!this.peerChoking&&!this._finished)this._updateTimeout();e.callback(t,r)};w.prototype._clearTimeout=function(){if(!this._timeout)return;clearTimeout(this._timeout);this._timeout=null};w.prototype._updateTimeout=function(){if(!this._timeoutMs||!this.requests.length||this._timeout)return;this._timeout=setTimeout(this._onTimeout.bind(this),this._timeoutMs);if(this._timeoutUnref&&this._timeout.unref)this._timeout.unref()};w.prototype._parse=function(e,t){this._parserSize=e;this._parser=t};w.prototype._message=function(e,t,n){var i=n?n.length:0;var s=new r(5+4*t.length);s.writeUInt32BE(s.length+i-4,0);s[4]=e;for(var o=0;o0){this._parse(t,this._onmessage)}else{this._onKeepAlive();this._parse(4,this._onmessagelength)}};w.prototype._onmessage=function(e){this._parse(4,this._onmessagelength);switch(e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:this._debug("got unknown message");return this.emit("unknownmessage",e)}};w.prototype._parseHandshake=function(){this._parse(1,function(e){var t=e.readUInt8(0);this._parse(t+48,function(e){var r=e.slice(0,t);if(r.toString()!=="BitTorrent protocol"){this._debug("Error: wire not speaking BitTorrent protocol (%s)",r.toString());this.end();return}e=e.slice(t);this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(e[7]&1),extended:!!(e[5]&16)});this._parse(4,this._onmessagelength)}.bind(this))}.bind(this))};w.prototype._onfinish=function(){this._finished=true;this.push(null);while(this.read()){}clearInterval(this._keepAliveInterval);this._parse(Number.MAX_VALUE,function(){});this.peerRequests=[];while(this.requests.length){this._callback(this.requests.shift(),new Error("wire was closed"),null)}};w.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._debugId+"] "+e[0];s.apply(null,e)};function S(e,t,r,n){for(var i=0;it)f=t;a=n;while(f--){if(o===t)o=0;r[o]=r[o===0?t-1:o-1];o++}if(e)r[o-1]+=e;var u=r[o-1];var h=r.length=e.maxConns){return}s("drain (%s queued, %s/%s peers)",e.numQueued,e.numPeers,e.maxConns);var t=e._queue.shift();if(!t)return;s("tcp connect attempt to %s",t.addr);var r=i(t.addr);var n={host:r[0],port:r[1]};if(e._hostname)n.localAddress=e._hostname;var o=t.conn=u.connect(n);o.once("connect",function(){t.onConnect()});o.once("error",function(e){t.destroy(e)});t.setConnectTimeout();o.on("close",function(){if(e.destroyed)return;if(t.retries>=p.length){s("conn %s closed: will not re-add (max %s attempts)",t.addr,p.length);return}var r=p[t.retries];s("conn %s closed: will re-add to queue in %sms (attempt %s)",t.addr,r,t.retries+1);var n=setTimeout(function i(){var r=e._addPeer(t.addr);if(r)r.retries=t.retries+1},r);if(n.unref)n.unref()})};m.prototype._onError=function(e){var t=this;t.emit("error",e);t.destroy()};m.prototype._validAddr=function(e){var t=this;var r=i(e);var n=r[0];var s=r[1];return s>0&&s<65535&&!(n==="127.0.0.1"&&s===t._port)}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/peer":19,"./lib/tcp-pool":20,_process:83,"addr-to-ip-port":34,buffer:36,debug:42,dezalgo:45,events:47,inherits:55,net:34,speedometer:22}],19:[function(e,t,r){var n=e("debug")("bittorrent-swarm:peer");var i=e("./webconn");var s=e("bittorrent-protocol");var o=25e3;var a=25e3;r.createWebRTCPeer=function(e,t){var r=new f(e.id);r.conn=e;r.swarm=t;if(r.conn.connected){r.onConnect()}else{r.conn.once("connect",function(){r.onConnect()});r.conn.once("error",function(e){r.destroy(e)});r.setConnectTimeout()}return r};r.createIncomingTCPPeer=function(e){var t=e.remoteAddress+":"+e.remotePort;var r=new f(t);r.conn=e;r.addr=t;r.onConnect();return r};r.createOutgoingTCPPeer=function(e,t){var r=new f(e);r.addr=e;r.swarm=t;return r};r.createWebPeer=function(e,t,r){var n=new f(e);n.swarm=r;n.conn=new i(e,t);n.onConnect();return n};function f(e){var t=this;t.id=e;n("new Peer %s",e);t.addr=null;t.conn=null;t.swarm=null;t.wire=null;t.connected=false;t.destroyed=false;t.timeout=null;t.retries=0;t.sentHandshake=false}f.prototype.onConnect=function(){var e=this;if(e.destroyed)return;e.connected=true;n("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 r=e.wire=new s;r.once("end",function(){e.destroy()});r.once("close",function(){e.destroy()});r.once("finish",function(){e.destroy()});r.once("error",function(t){e.destroy(t)});r.once("handshake",function(t,r){e.onHandshake(t,r)});e.setHandshakeTimeout();t.pipe(r).pipe(t);if(e.swarm&&!e.sentHandshake)e.handshake()};f.prototype.onHandshake=function(e,t){var r=this;if(!r.swarm)return;var i=e.toString("hex");var s=t.toString("hex");if(r.swarm.destroyed)return r.destroy(new Error("swarm already destroyed"));if(i!==r.swarm.infoHashHex){return r.destroy(new Error("unexpected handshake info hash for this swarm"))}if(s===r.swarm.peerIdHex){return r.destroy(new Error("refusing to handshake with self"))}n("Peer %s got handshake %s",r.id,i);clearTimeout(r.handshakeTimeout);r.retries=0;r.wire.on("download",function(e){if(r.destroyed)return;r.swarm.downloaded+=e;r.swarm.downloadSpeed(e);r.swarm.emit("download",e)});r.wire.on("upload",function(e){if(r.destroyed)return;r.swarm.uploaded+=e;r.swarm.uploadSpeed(e);r.swarm.emit("upload",e)});if(!r.sentHandshake)r.handshake();r.swarm.wires.push(r.wire);var o=r.addr;if(!o&&r.conn.remoteAddress){o=r.conn.remoteAddress+":"+r.conn.remotePort}r.swarm.emit("wire",r.wire,o)};f.prototype.handshake=function(){var e=this;e.wire.handshake(e.swarm.infoHash,e.swarm.peerId,e.swarm.handshakeOpts);e.sentHandshake=true};f.prototype.setConnectTimeout=function(){var e=this;clearTimeout(e.connectTimeout);e.connectTimeout=setTimeout(function(){e.destroy(new Error("connect timeout"))},o);if(e.connectTimeout.unref)e.connectTimeout.unref()};f.prototype.setHandshakeTimeout=function(){var e=this;clearTimeout(e.handshakeTimeout);e.handshakeTimeout=setTimeout(function(){e.destroy(new Error("handshake timeout"))},a);if(e.handshakeTimeout.unref)e.handshakeTimeout.unref()};f.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;t.connected=false;n("destroy %s (error: %s)",t.id,e&&(e.message||e));clearTimeout(t.connectTimeout);clearTimeout(t.handshakeTimeout);var r=t.swarm;var i=t.conn;var s=t.wire;t.conn=null;t.swarm=null;t.wire=null;if(r&&s){var o=r.wires.indexOf(s);if(o>=0)r.wires.splice(o,1)}if(i)i.destroy();if(s)s.destroy();if(r)r.removePeer(t.id)}},{"./webconn":21,"bittorrent-protocol":16,debug:42}],20:[function(e,t,r){(function(r){t.exports=f;var n=e("debug")("bittorrent-swarm:tcp-pool");var i=e("dezalgo");var s=e("net");var o=e("./peer");var a={};function f(e,t){var r=this;r.port=e;r.listening=false;r.swarms={};n("new TCPPool (port: %s, hostname: %s)",e,t);r.pendingConns=[];r.server=s.createServer();r.server.on("connection",function(e){r._onConnection(e)});r.server.on("error",function(e){r._onError(e)});r.server.on("listening",function(){r._onListening()});r.server.listen(r.port,t)}f.addSwarm=function(e){var t=a[e._port];if(!t)t=a[e._port]=new f(e._port,e._hostname);t.addSwarm(e);return t};f.removeSwarm=function(e,t){var n=a[e._port];if(!n)return t();n.removeSwarm(e);var i=0;for(var s in n.swarms){var o=n.swarms[s];if(o)i+=1}if(i===0)n.destroy(t);else r.nextTick(t)};f.getDefaultListenPort=function(e){for(var t in a){var r=a[t];if(r&&!r.swarms[e])return r.port}return 0};f.prototype.addSwarm=function(e){var t=this;if(t.swarms[e.infoHashHex]){r.nextTick(function(){e._onError(new Error("There is already a swarm with info hash "+e.infoHashHex+" "+"listening on port "+e._port))});return}t.swarms[e.infoHashHex]=e;if(t.listening){r.nextTick(function(){e._onListening(t.port)})}n("add swarm %s to tcp pool %s",e.infoHashHex,t.port)};f.prototype.removeSwarm=function(e){var t=this;n("remove swarm %s from tcp pool %s",e.infoHashHex,t.port);t.swarms[e.infoHashHex]=null};f.prototype.destroy=function(e){var t=this;if(e)e=i(e);n("destroy tcp pool %s",t.port);t.listening=false;t.pendingConns.forEach(function(e){e.destroy()});a[t.port]=null;try{t.server.close(e)}catch(r){if(e)e(null)}};f.prototype._onListening=function(){var e=this;var t=e.server.address()||{port:0};var r=t.port;n("tcp pool listening on %s",r);if(r!==e.port){a[e.port]=null;e.port=r;a[e.port]=e}e.listening=true;for(var i in e.swarms){var s=e.swarms[i];if(s)s._onListening(e.port)}};f.prototype._onConnection=function(e){var t=this;t.pendingConns.push(e);e.once("close",r);function r(){t.pendingConns.splice(t.pendingConns.indexOf(e))}var n=o.createIncomingTCPPeer(e);n.wire.once("handshake",function(i,s){var o=i.toString("hex");r();e.removeListener("close",r);var a=t.swarms[o];if(a){n.swarm=a;a._addIncomingPeer(n);n.onHandshake(i,s)}else{var f=new Error("Unexpected info hash "+o+" from incoming peer "+n.id+": destroying peer");n.destroy(f)}})};f.prototype._onError=function(e){var t=this;t.destroy();for(var r in t.swarms){var n=t.swarms[r];if(n){t.removeSwarm(n);n._onError(e)}}}}).call(this,e("_process"))},{"./peer":19,_process:83,debug:42,dezalgo:45,net:34}],21:[function(e,t,r){(function(r){t.exports=f;var n=e("bitfield");var i=e("debug")("bittorrent-swarm:webconn");var s=e("simple-get");var o=e("inherits");var a=e("bittorrent-protocol");o(f,a);function f(e,t){var s=this;a.call(this);s.url=e;s.parsedTorrent=t;s.setKeepAlive(true);s.on("handshake",function(t,i){s.handshake(t,new r(20).fill(e));var o=s.parsedTorrent.pieces.length;var a=new n(o);for(var f=0;f<=o;f++){a.set(f,true)}s.bitfield(a)});s.on("choke",function(){i("choke")});s.on("unchoke",function(){i("unchoke")});s.once("interested",function(){i("interested");s.unchoke()});s.on("uninterested",function(){i("uninterested")});s.on("bitfield",function(){i("bitfield")});s.on("request",function(e,t,r,n){i("request pieceIndex=%d offset=%d length=%d",e,t,r);s.httpRequest(e,t,r,n)})}f.prototype.httpRequest=function(e,t,r,n){var o=this;var a=e*o.parsedTorrent.pieceLength;var f=a+t;var u=f+r-1;i("Requesting pieceIndex=%d offset=%d length=%d start=%d end=%d",e,t,r,f,u);var h={url:o.url,method:"GET",headers:{"user-agent":"WebTorrent (http://webtorrent.io)",range:"bytes="+f+"-"+u}};s.concat(h,function(e,t,r){if(e)return n(e);if(r.statusCode<200||r.statusCode>=300){return n(new Error("Unexpected HTTP status code "+r.statusCode))}i("Got data of length %d",t.length);n(null,t)})}}).call(this,e("buffer").Buffer)},{bitfield:15,"bittorrent-protocol":16,buffer:36,debug:42,inherits:55,"simple-get":103}],22:[function(e,t,r){arguments[4][17][0].apply(r,arguments)},{dup:17}],23:[function(e,t,r){(function(r,n){t.exports=m;var i=e("events").EventEmitter;var s=e("debug")("bittorrent-tracker");var o=e("inherits");var a=e("once");var f=e("run-parallel");var u=e("uniq");var h=e("url");var l=e("./lib/common");var c=e("./lib/client/http-tracker");var d=e("./lib/client/udp-tracker");var p=e("./lib/client/websocket-tracker");o(m,i);function m(e,t,o,a){var f=this;if(!(f instanceof m))return new m(e,t,o,a);i.call(f);if(!a)a={};f._peerId=n.isBuffer(e)?e:new n(e,"hex");f._peerIdHex=f._peerId.toString("hex");f._peerIdBinary=f._peerId.toString("binary");f._infoHash=n.isBuffer(o.infoHash)?o.infoHash:new n(o.infoHash,"hex");f._infoHashHex=f._infoHash.toString("hex");f._infoHashBinary=f._infoHash.toString("binary");f.torrentLength=o.length;f.destroyed=false;f._port=t;f._rtcConfig=a.rtcConfig;f._wrtc=a.wrtc;s("new client %s",f._infoHashHex);var l=!!f._wrtc||typeof window!=="undefined";var v=typeof o.announce==="string"?[o.announce]:o.announce==null?[]:o.announce;v=v.map(function(e){e=e.toString();if(e[e.length-1]==="/"){e=e.substring(0,e.length-1)}return e});v=u(v);f._trackers=v.map(function(e){var t=h.parse(e).protocol;if((t==="http:"||t==="https:")&&typeof c==="function"){return new c(f,e)}else if(t==="udp:"&&typeof d==="function"){return new d(f,e)}else if((t==="ws:"||t==="wss:")&&l){return new p(f,e)}else{r.nextTick(function(){var t=new Error("unsupported tracker protocol for "+e);f.emit("warning",t)})}return null}).filter(Boolean)}m.scrape=function(e,t,r){r=a(r);var i=new n("01234567890123456789");var s=6881;var o={infoHash:Array.isArray(t)?t[0]:t,announce:[e]};var f=new m(i,s,o);f.once("error",r);var u=Array.isArray(t)?t.length:1;var h={};f.on("scrape",function(e){u-=1;h[e.infoHash]=e;if(u===0){f.destroy();var t=Object.keys(h);if(t.length===1){r(null,h[t[0]])}else{r(null,h)}}});t=Array.isArray(t)?t.map(function(e){return new n(e,"hex")}):new n(t,"hex");f.scrape({infoHash:t})};m.prototype.start=function(e){var t=this;s("send `start`");e=t._defaultAnnounceOpts(e);e.event="started";t._announce(e);t._trackers.forEach(function(e){e.setInterval()})};m.prototype.stop=function(e){var t=this;s("send `stop`");e=t._defaultAnnounceOpts(e);e.event="stopped";t._announce(e)};m.prototype.complete=function(e){var t=this;s("send `complete`");if(!e)e={};if(e.downloaded==null&&t.torrentLength!=null){e.downloaded=t.torrentLength}e=t._defaultAnnounceOpts(e);e.event="completed";t._announce(e)};m.prototype.update=function(e){var t=this;s("send `update`");e=t._defaultAnnounceOpts(e);if(e.event)delete e.event;t._announce(e)};m.prototype._announce=function(e){var t=this;t._trackers.forEach(function(t){t.announce(e)})};m.prototype.scrape=function(e){var t=this;s("send `scrape`");if(!e)e={};t._trackers.forEach(function(t){t.scrape(e)})};m.prototype.setInterval=function(e){var t=this;s("setInterval %d",e);t._trackers.forEach(function(t){t.setInterval(e)})};m.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;s("destroy");var r=t._trackers.map(function(e){return function(t){e.destroy(t)}});f(r,e);t._trackers=[]};m.prototype._defaultAnnounceOpts=function(e){var t=this;if(!e)e={};if(e.numwant==null)e.numwant=l.DEFAULT_ANNOUNCE_PEERS;if(e.uploaded==null)e.uploaded=0;if(e.downloaded==null)e.downloaded=0;if(e.left==null&&t.torrentLength!=null){e.left=t.torrentLength-e.downloaded}return e}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/client/http-tracker":34,"./lib/client/udp-tracker":34,"./lib/client/websocket-tracker":25,"./lib/common":26,_process:83,buffer:36,debug:42,events:47,inherits:55,once:73,"run-parallel":101,uniq:119,url:120}],24:[function(e,t,r){t.exports=s;var n=e("events").EventEmitter;var i=e("inherits");i(s,n);function s(e,t){var r=this;n.call(r);r.client=e;r.announceUrl=t;r.interval=null;r.destroyed=false}s.prototype.setInterval=function(e){var t=this;if(t.interval)return;if(e==null)e=t.DEFAULT_ANNOUNCE_INTERVAL;clearInterval(t.interval);if(e){var r=t.announce.bind(t,t.client._defaultAnnounceOpts());t.interval=setInterval(r,e);if(t.interval.unref)t.interval.unref()}}},{events:47,inherits:55}],25:[function(e,t,r){t.exports=d;var n=e("debug")("bittorrent-tracker:websocket-tracker");var i=e("hat");var s=e("inherits");var o=e("simple-peer");var a=e("simple-websocket");var f=e("../common");var u=e("./tracker");var h={};var l=30*1e3;var c=5*1e3;s(d,u);function d(e,t,r){var i=this;u.call(i,e,t);n("new websocket tracker %s",t);i.peers={};i.socket=null;i.reconnecting=false;i._openSocket()}d.prototype.DEFAULT_ANNOUNCE_INTERVAL=30*1e3;d.prototype.announce=function(e){var t=this;if(t.destroyed||t.reconnecting)return;if(!t.socket.connected){return t.socket.once("connect",t.announce.bind(t,e))}var r=Math.min(e.numwant,10);t._generateOffers(r,function(n){var i={numwant:r,uploaded:e.uploaded||0,downloaded:e.downloaded,event:e.event,info_hash:t.client._infoHashBinary,peer_id:t.client._peerIdBinary,offers:n};if(t._trackerId)i.trackerid=t._trackerId;t._send(i)})};d.prototype.scrape=function(e){var t=this;if(t.destroyed||t.reconnecting)return;t._onSocketError(new Error("scrape not supported "+t.announceUrl))};d.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;clearInterval(t.interval);h[t.announceUrl]=null;t.socket.removeListener("connect",t._onSocketConnectBound);t.socket.removeListener("data",t._onSocketDataBound);t.socket.removeListener("close",t._onSocketCloseBound);t.socket.removeListener("error",t._onSocketErrorBound);t._onSocketConnectBound=null;t._onSocketErrorBound=null;t._onSocketDataBound=null;t._onSocketCloseBound=null;t.socket.on("error",p);try{t.socket.destroy(e)}catch(r){if(e)e()}t.socket=null};d.prototype._openSocket=function(){var e=this;e.destroyed=false;e._onSocketConnectBound=e._onSocketConnect.bind(e);e._onSocketErrorBound=e._onSocketError.bind(e);e._onSocketDataBound=e._onSocketData.bind(e);e._onSocketCloseBound=e._onSocketClose.bind(e);e.socket=h[e.announceUrl];if(!e.socket){e.socket=h[e.announceUrl]=new a(e.announceUrl);e.socket.on("connect",e._onSocketConnectBound)}e.socket.on("data",e._onSocketDataBound);e.socket.on("close",e._onSocketCloseBound);e.socket.on("error",e._onSocketErrorBound)};d.prototype._onSocketConnect=function(){var e=this;if(e.destroyed)return;if(e.reconnecting){e.reconnecting=false;e.announce(e.client._defaultAnnounceOpts())}};d.prototype._onSocketData=function(e){var t=this;if(t.destroyed)return;if(!(typeof e==="object"&&e!==null)){return t.client.emit("warning",new Error("Invalid tracker response"))}if(e.info_hash!==t.client._infoHashBinary){n("ignoring websocket data from %s for %s (looking for %s: reused socket)",t.announceUrl,f.binaryToHex(e.info_hash),t.client._infoHashHex);return}if(e.peer_id&&e.peer_id===t.client._peerIdBinary){return}n("received %s from %s for %s",JSON.stringify(e),t.announceUrl,t.client._infoHashHex);var r=e["failure reason"];if(r)return t.client.emit("warning",new Error(r));var i=e["warning message"];if(i)t.client.emit("warning",new Error(i));var s=e.interval||e["min interval"];if(s)t.setInterval(s*1e3);var a=e["tracker id"];if(a){t._trackerId=a}if(e.complete){t.client.emit("update",{announce:t.announceUrl,complete:e.complete,incomplete:e.incomplete})}var u;if(e.offer&&e.peer_id){u=new o({trickle:false,config:t.client._rtcConfig,wrtc:t.client._wrtc});u.id=f.binaryToHex(e.peer_id);u.once("signal",function(r){var n={info_hash:t.client._infoHashBinary, +peer_id:t.client._peerIdBinary,to_peer_id:e.peer_id,answer:r,offer_id:e.offer_id};if(t._trackerId)n.trackerid=t._trackerId;t._send(n)});u.signal(e.offer);t.client.emit("peer",u)}if(e.answer&&e.peer_id){u=t.peers[f.binaryToHex(e.offer_id)];if(u){u.id=f.binaryToHex(e.peer_id);u.signal(e.answer);t.client.emit("peer",u)}else{n("got unexpected answer: "+JSON.stringify(e.answer))}}};d.prototype._onSocketClose=function(){var e=this;if(e.destroyed)return;e.destroy();e._startReconnectTimer()};d.prototype._onSocketError=function(e){var t=this;if(t.destroyed)return;t.destroy();t.client.emit("warning",e);t._startReconnectTimer()};d.prototype._startReconnectTimer=function(){var e=this;var t=Math.floor(Math.random()*l)+c;e.reconnecting=true;var r=setTimeout(function(){e._openSocket()},t);if(r.unref)r.unref();n("reconnecting socket in %s ms",t)};d.prototype._send=function(e){var t=this;if(t.destroyed)return;var r=JSON.stringify(e);n("send %s",r);t.socket.send(r)};d.prototype._generateOffers=function(e,t){var r=this;var s=[];n("generating %s offers",e);for(var a=0;a=this.size){var i=r.concat(this._buffered);this._bufferedBytes-=this.size;this.push(i.slice(0,this.size));this._buffered=[i.slice(this.size,i.length)]}n()};o.prototype._flush=function(){if(this._bufferedBytes&&this._zeroPadding){var e=new r(this.size-this._bufferedBytes);e.fill(0);this._buffered.push(e);this.push(r.concat(this._buffered));this._buffered=null}else if(this._bufferedBytes){this.push(r.concat(this._buffered));this._buffered=null}this.push(null)}}).call(this,e("buffer").Buffer)},{buffer:36,defined:44,inherits:55,"readable-stream":33}],28:[function(e,t,r){(function(r){t.exports=a;var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};var i=e("core-util-is");i.inherits=e("inherits");var s=e("./_stream_readable");var o=e("./_stream_writable");i.inherits(a,s);u(n(o.prototype),function(e){if(!a.prototype[e])a.prototype[e]=o.prototype[e]});function a(e){if(!(this instanceof a))return new a(e);s.call(this,e);o.call(this,e);if(e&&e.readable===false)this.readable=false;if(e&&e.writable===false)this.writable=false;this.allowHalfOpen=true;if(e&&e.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",f)}function f(){if(this.allowHalfOpen||this._writableState.ended)return;r.nextTick(this.end.bind(this))}function u(e,t){for(var r=0,n=e.length;r0){if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var o=new Error("stream.unshift() after end event");e.emit("error",o)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)y(e)}w(e,t)}}else if(!i){t.reading=false}return d(t)}function d(e){return!e.ended&&(e.needReadable||e.length=p){e=p}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function v(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(isNaN(e)||a.isNull(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=m(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else return t.length}return e}l.prototype.read=function(e){u("read",e);var t=this._readableState;var r=e;if(!a.isNumber(e)||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){u("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)T(this);else y(this);return null}e=v(e,t);if(e===0&&t.ended){if(t.length===0)T(this);return null}var n=t.needReadable;u("need readable",n);if(t.length===0||t.length-e0)i=U(e,t);else i=null;if(a.isNull(i)){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)T(this);if(!a.isNull(i))this.emit("data",i);return i};function g(e,t){var r=null;if(!a.isBuffer(t)&&!a.isString(t)&&!a.isNullOrUndefined(t)&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function _(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;y(e)}function y(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)r.nextTick(function(){b(e)});else b(e)}}function b(e){u("emit readable");e.emit("readable");A(e)}function w(e,t){if(!t.readingMore){t.readingMore=true;r.nextTick(function(){S(e,t)})}}function S(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(s)a=r.join("");else a=i.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;r.nextTick(function(){if(!t.endEmitted&&t.length===0){t.endEmitted=true;e.readable=false;e.emit("end")}})}}function I(e,t){for(var r=0,n=e.length;r1){var r=[];for(var n=0;n1)return new u(e,arguments[1]);return new u(e)}this.length=0;this.parent=undefined;if(typeof e==="number"){return h(this,e)}if(typeof e==="string"){return l(this,e,arguments.length>1?arguments[1]:"utf8")}return c(this,e)}function h(e,t){e=y(e,t<0?0:b(t)|0);if(!u.TYPED_ARRAY_SUPPORT){for(var r=0;r>>1;if(r)e.parent=o;return e}function b(e){if(e>=f()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+f().toString(16)+" bytes")}return e|0}function w(e,t){if(!(this instanceof w))return new w(e,t);var r=new u(e,t);delete r.parent;return r}u.isBuffer=function te(e){return!!(e!=null&&e._isBuffer)};u.compare=function re(e,t){if(!u.isBuffer(e)||!u.isBuffer(t)){throw new TypeError("Arguments must be Buffers")}if(e===t)return 0;var r=e.length;var n=t.length;var i=0;var s=Math.min(r,n);while(i>>1;case"base64":return Q(e).length;default:if(n)return X(e).length;t=(""+t).toLowerCase();n=true}}}u.byteLength=S;u.prototype.length=undefined;u.prototype.parent=undefined;function x(e,t,r){var n=false;t=t|0;r=r===undefined||r===Infinity?this.length:r|0;if(!e)e="utf8";if(t<0)t=0;if(r>this.length)r=this.length;if(r<=t)return"";while(true){switch(e){case"hex":return O(this,t,r);case"utf8":case"utf-8":return B(this,t,r);case"ascii":return P(this,t,r);case"binary":return F(this,t,r);case"base64":return L(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase();n=true}}}u.prototype.toString=function se(){var e=this.length|0;if(e===0)return"";if(arguments.length===0)return B(this,0,e);return x.apply(this,arguments)};u.prototype.equals=function oe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return true;return u.compare(this,e)===0};u.prototype.inspect=function ae(){var e="";var t=r.INSPECT_MAX_BYTES;if(this.length>0){e=this.toString("hex",0,t).match(/.{2}/g).join(" ");if(this.length>t)e+=" ... "}return""};u.prototype.compare=function fe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return 0;return u.compare(this,e)};u.prototype.indexOf=function ue(e,t){if(t>2147483647)t=2147483647;else if(t<-2147483648)t=-2147483648;t>>=0;if(this.length===0)return-1;if(t>=this.length)return-1;if(t<0)t=Math.max(this.length+t,0);if(typeof e==="string"){if(e.length===0)return-1;return String.prototype.indexOf.call(this,e,t)}if(u.isBuffer(e)){return r(this,e,t)}if(typeof e==="number"){if(u.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,e,t)}return r(this,[e],t)}function r(e,t,r){var n=-1;for(var i=0;r+ii){n=i}}var s=t.length;if(s%2!==0)throw new Error("Invalid hex string");if(n>s/2){n=s/2}for(var o=0;os)r=s;if(e.length>0&&(r<0||t<0)||t>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!n)n="utf8";var o=false;for(;;){switch(n){case"hex":return k(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":return A(this,e,t,r);case"binary":return U(this,e,t,r);case"base64":return T(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase();o=true}}};u.prototype.toJSON=function de(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function L(e,t,r){if(t===0&&r===e.length){return n.fromByteArray(e)}else{return n.fromByteArray(e.slice(t,r))}}function B(e,t,r){r=Math.min(e.length,r);var n=[];var i=t;while(i239?4:s>223?3:s>191?2:1;if(i+a<=r){var f,u,h,l;switch(a){case 1:if(s<128){o=s}break;case 2:f=e[i+1];if((f&192)===128){l=(s&31)<<6|f&63;if(l>127){o=l}}break;case 3:f=e[i+1];u=e[i+2];if((f&192)===128&&(u&192)===128){l=(s&15)<<12|(f&63)<<6|u&63;if(l>2047&&(l<55296||l>57343)){o=l}}break;case 4:f=e[i+1];u=e[i+2];h=e[i+3];if((f&192)===128&&(u&192)===128&&(h&192)===128){l=(s&15)<<18|(f&63)<<12|(u&63)<<6|h&63;if(l>65535&&l<1114112){o=l}}}}if(o===null){o=65533;a=1}else if(o>65535){o-=65536;n.push(o>>>10&1023|55296);o=56320|o&1023}n.push(o);i+=a}return R(n)}var C=4096;function R(e){var t=e.length;if(t<=C){return String.fromCharCode.apply(String,e)}var r="";var n=0;while(nn)r=n;var i="";for(var s=t;sr){e=r}if(t<0){t+=r;if(t<0)t=0}else if(t>r){t=r}if(tr)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUIntLE=function me(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s0&&(i*=256)){n+=this[e+--t]*i}return n};u.prototype.readUInt8=function ge(e,t){if(!t)D(e,1,this.length);return this[e]};u.prototype.readUInt16LE=function _e(e,t){if(!t)D(e,2,this.length);return this[e]|this[e+1]<<8};u.prototype.readUInt16BE=function ye(e,t){if(!t)D(e,2,this.length);return this[e]<<8|this[e+1]};u.prototype.readUInt32LE=function be(e,t){if(!t)D(e,4,this.length);return(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};u.prototype.readUInt32BE=function we(e,t){if(!t)D(e,4,this.length);return this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};u.prototype.readIntLE=function Se(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s=i)n-=Math.pow(2,8*t);return n};u.prototype.readIntBE=function xe(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=t;var i=1;var s=this[e+--n];while(n>0&&(i*=256)){s+=this[e+--n]*i}i*=128;if(s>=i)s-=Math.pow(2,8*t);return s};u.prototype.readInt8=function ke(e,t){if(!t)D(e,1,this.length);if(!(this[e]&128))return this[e];return(255-this[e]+1)*-1};u.prototype.readInt16LE=function Ee(e,t){if(!t)D(e,2,this.length);var r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};u.prototype.readInt16BE=function Ae(e,t){if(!t)D(e,2,this.length);var r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};u.prototype.readInt32LE=function Ue(e,t){if(!t)D(e,4,this.length);return this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};u.prototype.readInt32BE=function Te(e,t){if(!t)D(e,4,this.length);return this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};u.prototype.readFloatLE=function Ie(e,t){if(!t)D(e,4,this.length);return i.read(this,e,true,23,4)};u.prototype.readFloatBE=function Le(e,t){ if(!t)D(e,4,this.length);return i.read(this,e,false,23,4)};u.prototype.readDoubleLE=function Be(e,t){if(!t)D(e,8,this.length);return i.read(this,e,true,52,8)};u.prototype.readDoubleBE=function Ce(e,t){if(!t)D(e,8,this.length);return i.read(this,e,false,52,8)};function N(e,t,r,n,i,s){if(!u.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>i||te.length)throw new RangeError("index out of range")}u.prototype.writeUIntLE=function Re(e,t,r,n){e=+e;t=t|0;r=r|0;if(!n)N(this,e,t,r,Math.pow(2,8*r),0);var i=1;var s=0;this[t]=e&255;while(++s=0&&(s*=256)){this[t+i]=e/s&255}return t+r};u.prototype.writeUInt8=function Fe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,1,255,0);if(!u.TYPED_ARRAY_SUPPORT)e=Math.floor(e);this[t]=e&255;return t+1};function z(e,t,r,n){if(t<0)t=65535+t+1;for(var i=0,s=Math.min(e.length-r,2);i>>(n?i:1-i)*8}}u.prototype.writeUInt16LE=function Oe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8}else{z(this,e,t,true)}return t+2};u.prototype.writeUInt16BE=function Me(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e&255}else{z(this,e,t,false)}return t+2};function j(e,t,r,n){if(t<0)t=4294967295+t+1;for(var i=0,s=Math.min(e.length-r,4);i>>(n?i:3-i)*8&255}}u.prototype.writeUInt32LE=function De(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[t+3]=e>>>24;this[t+2]=e>>>16;this[t+1]=e>>>8;this[t]=e&255}else{j(this,e,t,true)}return t+4};u.prototype.writeUInt32BE=function Ne(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e&255}else{j(this,e,t,false)}return t+4};u.prototype.writeIntLE=function ze(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=0;var o=1;var a=e<0?1:0;this[t]=e&255;while(++s>0)-a&255}return t+r};u.prototype.writeIntBE=function je(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=r-1;var o=1;var a=e<0?1:0;this[t+s]=e&255;while(--s>=0&&(o*=256)){this[t+s]=(e/o>>0)-a&255}return t+r};u.prototype.writeInt8=function He(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,1,127,-128);if(!u.TYPED_ARRAY_SUPPORT)e=Math.floor(e);if(e<0)e=255+e+1;this[t]=e&255;return t+1};u.prototype.writeInt16LE=function qe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8}else{z(this,e,t,true)}return t+2};u.prototype.writeInt16BE=function Ge(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e&255}else{z(this,e,t,false)}return t+2};u.prototype.writeInt32LE=function We(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,2147483647,-2147483648);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8;this[t+2]=e>>>16;this[t+3]=e>>>24}else{j(this,e,t,true)}return t+4};u.prototype.writeInt32BE=function Ye(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,2147483647,-2147483648);if(e<0)e=4294967295+e+1;if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e&255}else{j(this,e,t,false)}return t+4};function H(e,t,r,n,i,s){if(t>i||te.length)throw new RangeError("index out of range");if(r<0)throw new RangeError("index out of range")}function q(e,t,r,n,s){if(!s){H(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38)}i.write(e,t,r,n,23,4);return r+4}u.prototype.writeFloatLE=function Ve(e,t,r){return q(this,e,t,true,r)};u.prototype.writeFloatBE=function Ke(e,t,r){return q(this,e,t,false,r)};function G(e,t,r,n,s){if(!s){H(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308)}i.write(e,t,r,n,52,8);return r+8}u.prototype.writeDoubleLE=function $e(e,t,r){return G(this,e,t,true,r)};u.prototype.writeDoubleBE=function Xe(e,t,r){return G(this,e,t,false,r)};u.prototype.copy=function Ze(e,t,r,n){if(!r)r=0;if(!n&&n!==0)n=this.length;if(t>=e.length)t=e.length;if(!t)t=0;if(n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");if(n>this.length)n=this.length;if(e.length-t=0;s--){e[s+t]=this[s+r]}}else if(i<1e3||!u.TYPED_ARRAY_SUPPORT){for(s=0;s=this.length)throw new RangeError("start out of bounds");if(r<0||r>this.length)throw new RangeError("end out of bounds");var n;if(typeof e==="number"){for(n=t;n55295&&r<57344){if(!i){if(r>56319){if((t-=3)>-1)s.push(239,191,189);continue}else if(o+1===n){if((t-=3)>-1)s.push(239,191,189);continue}i=r;continue}if(r<56320){if((t-=3)>-1)s.push(239,191,189);i=r;continue}r=(i-55296<<10|r-56320)+65536}else if(i){if((t-=3)>-1)s.push(239,191,189)}i=null;if(r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else{throw new Error("Invalid code point")}}return s}function Z(e){var t=[];for(var r=0;r>8;i=r%256;s.push(i);s.push(n)}return s}function Q(e){return n.toByteArray(V(e))}function ee(e,t,r,n){for(var i=0;i=t.length||i>=e.length)break;t[i+r]=e[i]}return i}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":10,ieee754:53,"is-array":56}],37:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Time-out",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Request Entity Too Large",414:"Request-URI Too Large",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Time-out",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],38:[function(e,t,r){t.exports=o;var n=e("block-stream2");var i=e("inherits");var s=e("stream");i(o,s.Writable);function o(e,t,r){var i=this;if(!(i instanceof o)){return new o(e,t,r)}s.Writable.call(i,r);if(!r)r={};if(!e||!e.put||!e.get){throw new Error("First argument must be an abstract-chunk-store compliant store")}t=Number(t);if(!t)throw new Error("Second argument must be a chunk length");i._blockstream=new n(t,{zeroPadding:false});i._blockstream.on("data",f).on("error",function(e){i.destroy(e)});var a=0;function f(t){if(i.destroyed)return;e.put(a,t);a+=1}i.on("finish",function(){this._blockstream.end()})}o.prototype._write=function(e,t,r){this._blockstream.write(e,t,r)};o.prototype.destroy=function(e){if(this.destroyed)return;this.destroyed=true;if(e)this.emit("error",e);this.emit("close")}},{"block-stream2":27,inherits:55,stream:108}],39:[function(e,t,r){t.exports=function(e,t){var r=Infinity;var n=0;var i=null;t.sort(function(e,t){return e-t});for(var s=0,o=t.length;s=r){break}r=n;i=t[s]}return i}},{}],40:[function(e,t,r){(function(e){function t(e){if(Array.isArray){return Array.isArray(e)}return v(e)==="[object Array]"}r.isArray=t;function n(e){return typeof e==="boolean"}r.isBoolean=n;function i(e){return e===null}r.isNull=i;function s(e){return e==null}r.isNullOrUndefined=s;function o(e){return typeof e==="number"}r.isNumber=o;function a(e){return typeof e==="string"}r.isString=a;function f(e){return typeof e==="symbol"}r.isSymbol=f;function u(e){return e===void 0}r.isUndefined=u;function h(e){return v(e)==="[object RegExp]"}r.isRegExp=h;function l(e){return typeof e==="object"&&e!==null}r.isObject=l;function c(e){return v(e)==="[object Date]"}r.isDate=c;function d(e){return v(e)==="[object Error]"||e instanceof Error}r.isError=d;function p(e){return typeof e==="function"}r.isFunction=p;function m(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}r.isPrimitive=m;r.isBuffer=e.isBuffer;function v(e){return Object.prototype.toString.call(e)}}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":57}],41:[function(e,t,r){(function(r,n){t.exports=y;t.exports.announceList=[["udp://tracker.openbittorrent.com:80"],["udp://tracker.internetwarriors.net:1337"],["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://exodus.desync.com:6969"],["wss://tracker.webtorrent.io"]];t.exports.parseInput=b;var i=e("bencode");var s=e("block-stream2");var o=e("piece-length");var a=e("path");var f=e("dezalgo");var u=e("filestream/read");var h=e("flatten");var l=e("fs");var c=e("is-file");var d=e("junk");var p=e("multistream");var m=e("once");var v=e("run-parallel");var g=e("simple-sha1");var _=e("stream");function y(e,t,r){if(typeof t==="function"){r=t;t={}}if(!t)t={};b(e,t,function(e,n,i){if(e)return r(e);t.singleFileTorrent=i;A(n,t,r)})}function b(e,t,r){if(typeof t==="function"){r=t;t={}}if(!t)t={};r=f(r);if(Array.isArray(e)&&e.length===0)throw new Error("invalid input type");if(I(e))e=Array.prototype.slice.call(e);if(!Array.isArray(e))e=[e];if(!t.name)t.name=e[0]&&e[0].name;if(!t.name)t.name=typeof e[0]==="string"&&a.basename(e[0]);if(t.name===undefined){throw new Error("missing option 'name' and unable to infer it from input[0].name")}if(e.length===1&&!e[0].name)e[0].name=t.name;var i=e.reduce(function(e,t){return e+Number(typeof t==="string")},0);var s=e.length===1;if(e.length===1&&typeof e[0]==="string"){c(e[0],function(e,t){if(e)return r(e);s=t;o()})}else{o()}function o(){v(e.map(function(e){return function(r){var o={};if(T(e)){o.getStream=B(e);o.length=e.size}else if(n.isBuffer(e)){o.getStream=C(e);o.length=e.length}else if(L(e)){if(!t.pieceLength){throw new Error("must specify `pieceLength` option if input is Stream")}o.getStream=P(e,o);o.length=0}else if(typeof e==="string"){if(typeof l.readdir!=="function"){throw new Error("filesystem paths do not work in the browser")}var f=i>1||s;w(e,f,r);return}else{throw new Error("invalid input type")}if(!e.name)throw new Error("missing requied `name` property on input");o.path=e.name.split(a.sep);r(null,o)}}),function(e,t){if(e)return r(e);t=h(t);r(null,t,s)})}}function w(e,t,r){x(e,S,function(n,i){if(n)return r(n);if(Array.isArray(i))i=h(i);else i=[i];e=a.normalize(e);if(t){e=e.slice(0,e.lastIndexOf(a.sep)+1)}if(e[e.length-1]!==a.sep)e+=a.sep;i.forEach(function(t){t.getStream=R(t.path);t.path=t.path.replace(e,"").split(a.sep)});r(null,i)})}function S(e,t){t=m(t);l.stat(e,function(r,n){if(r)return t(r);var i={length:n.size,path:e};t(null,i)})}function x(e,t,r){l.readdir(e,function(n,i){if(n&&n.code==="ENOTDIR"){t(e,r)}else if(n){r(n)}else{v(i.filter(k).filter(d.not).map(function(r){return function(n){x(a.join(e,r),t,n)}}),r)}})}function k(e){return e[0]!=="."}function E(e,t,r){r=m(r);var i=[];var o=0;var a=e.map(function(e){return e.getStream});var f=0;var u=0;var h=false;var l=new p(a);var c=new s(t,{zeroPadding:false});l.on("error",_);l.pipe(c).on("data",d).on("end",v).on("error",_);function d(e){o+=e.length;var t=u;g(e,function(e){i[t]=e;f-=1;b()});f+=1;u+=1}function v(){h=true;b()}function _(e){y();r(e)}function y(){l.removeListener("error",_);c.removeListener("data",d);c.removeListener("end",v);c.removeListener("error",_)}function b(){if(h&&f===0){y();r(null,new n(i.join(""),"hex"),o)}}}function A(e,n,s){var a=n.announceList;if(!a){if(typeof n.announce==="string")a=[[n.announce]];else if(Array.isArray(n.announce)){a=n.announce.map(function(e){return[e]})}}if(!a)a=[];if(r.WEBTORRENT_ANNOUNCE){if(typeof r.WEBTORRENT_ANNOUNCE==="string"){a.push([[r.WEBTORRENT_ANNOUNCE]])}else if(Array.isArray(r.WEBTORRENT_ANNOUNCE)){a=a.concat(r.WEBTORRENT_ANNOUNCE.map(function(e){return[e]}))}}if(a.length===0){a=a.concat(t.exports.announceList)}if(typeof n.urlList==="string")n.urlList=[n.urlList];var f={info:{name:n.name},announce:a[0][0],"announce-list":a,"creation date":Number(n.creationDate)||Date.now(),encoding:"UTF-8"};if(n.comment!==undefined)f.comment=n.comment;if(n.createdBy!==undefined)f["created by"]=n.createdBy;if(n.private!==undefined)f.info.private=Number(n.private);if(n.sslCert!==undefined)f.info["ssl-cert"]=n.sslCert;if(n.urlList!==undefined)f["url-list"]=n.urlList;var u=n.pieceLength||o(e.reduce(U,0));f.info["piece length"]=u;E(e,u,function(t,r,o){if(t)return s(t);f.info.pieces=r;e.forEach(function(e){delete e.getStream});if(n.singleFileTorrent){f.info.length=o}else{f.info.files=e}s(null,i.encode(f))})}function U(e,t){return e+t.length}function T(e){return typeof Blob!=="undefined"&&e instanceof Blob}function I(e){return typeof FileList==="function"&&e instanceof FileList}function L(e){return typeof e==="object"&&typeof e.pipe==="function"}function B(e){return function(){return new u(e)}}function C(e){return function(){var t=new _.PassThrough;t.end(e);return t}}function R(e){return function(){return l.createReadStream(e)}}function P(e,t){return function(){var r=new _.Transform;r._transform=function(e,r,n){t.length+=e.length;this.push(e);n()};e.pipe(r);return r}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{bencode:11,"block-stream2":27,buffer:36,dezalgo:45,"filestream/read":48,flatten:49,fs:35,"is-file":58,junk:61,multistream:72,once:73,path:77,"piece-length":79,"run-parallel":101,"simple-sha1":105,stream:108}],42:[function(e,t,r){r=t.exports=e("./debug");r.log=s;r.formatArgs=i;r.save=o;r.load=a;r.useColors=n;r.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:f();r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function n(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}r.formatters.j=function(e){return JSON.stringify(e)};function i(){var e=arguments;var t=this.useColors;e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+r.humanize(this.diff);if(!t)return e;var n="color: "+this.color;e=[e[0],n,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0;var s=0;e[0].replace(/%[a-z%]/g,function(e){if("%%"===e)return;i++;if("%c"===e){s=i}});e.splice(s,0,n);return e}function s(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function o(e){try{if(null==e){r.storage.removeItem("debug")}else{r.storage.debug=e}}catch(t){}}function a(){var e;try{e=r.storage.debug}catch(t){}return e}r.enable(a());function f(){try{return window.localStorage}catch(e){}}},{"./debug":43}],43:[function(e,t,r){r=t.exports=o;r.coerce=h;r.disable=f;r.enable=a;r.enabled=u;r.humanize=e("ms");r.names=[];r.skips=[];r.formatters={};var n=0;var i;function s(){return r.colors[n++%r.colors.length]}function o(e){function t(){}t.enabled=false;function n(){var e=n;var t=+new Date;var o=t-(i||t);e.diff=o;e.prev=i;e.curr=t;i=t;if(null==e.useColors)e.useColors=r.useColors();if(null==e.color&&e.useColors)e.color=s();var a=Array.prototype.slice.call(arguments);a[0]=r.coerce(a[0]);if("string"!==typeof a[0]){a=["%o"].concat(a)}var f=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,n){if(t==="%%")return t;f++;var i=r.formatters[n];if("function"===typeof i){var s=a[f];t=i.call(e,s);a.splice(f,1);f--}return t});if("function"===typeof r.formatArgs){a=r.formatArgs.apply(e,a)}var u=n.log||r.log||console.log.bind(console);u.apply(e,a)}n.enabled=true;var o=r.enabled(e)?n:t;o.namespace=e;return o}function a(e){r.save(e);var t=(e||"").split(/[\s,]+/);var n=t.length;for(var i=0;i0&&this._events[e].length>r){this._events[e].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[e].length);if(typeof console.trace==="function"){console.trace()}}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=false;function n(){this.removeListener(e,n);if(!r){r=true;t.apply(this,arguments)}}n.listener=t;this.on(e,n);return this};n.prototype.removeListener=function(e,t){var r,n,s,a;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;r=this._events[e];s=r.length;n=-1;if(r===t||i(r.listener)&&r.listener===t){delete this._events[e];if(this._events.removeListener)this.emit("removeListener",e,t)}else if(o(r)){for(a=s;a-- >0;){if(r[a]===t||r[a].listener&&r[a].listener===t){n=a;break}}if(n<0)return this;if(r.length===1){r.length=0;delete this._events[e]}else{r.splice(n,1)}if(this._events.removeListener)this.emit("removeListener",e,t)}return this};n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[e])delete this._events[e];return this}if(arguments.length===0){for(t in this._events){if(t==="removeListener")continue;this.removeAllListeners(t)}this.removeAllListeners("removeListener");this._events={};return this}r=this._events[e];if(i(r)){this.removeListener(e,r)}else if(r){while(r.length)this.removeListener(e,r[r.length-1])}delete this._events[e];return this};n.prototype.listeners=function(e){var t;if(!this._events||!this._events[e])t=[];else if(i(this._events[e]))t=[this._events[e]];else t=this._events[e].slice();return t};n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;else if(t)return t.length}return 0};n.listenerCount=function(e,t){return e.listenerCount(t)};function i(e){return typeof e==="function"}function s(e){return typeof e==="number"}function o(e){return typeof e==="object"&&e!==null}function a(e){return e===void 0}},{}],48:[function(e,t,r){var n=e("stream").Readable;var i=e("inherits");var s=/^.*\.(\w+)$/;var o=e("typedarray-to-buffer");function a(e,t){var r=this;if(!(this instanceof a)){return new a(e,t)}t=t||{};n.call(this,t);this._offset=0;this._ready=false;this._file=e;this._size=e.size;this._chunkSize=t.chunkSize||Math.max(this._size/1e3,200*1024);this.reader=new FileReader;this._generateHeaderBlocks(e,t,function(e,t){if(e){return r.emit("error",e)}if(Array.isArray(t)){t.forEach(function(e){r.push(e)})}r._ready=true;r.emit("_ready")})}i(a,n);t.exports=a;a.prototype._generateHeaderBlocks=function(e,t,r){r(null,[])};a.prototype._read=function(){if(!this._ready){this.once("_ready",this._read.bind(this));return}var e=this;var t=this.reader;var r=this._offset;var n=this._offset+this._chunkSize;if(n>this._size)n=this._size;if(r===this._size){this.destroy();this.push(null);return}t.onload=function(){e._offset=n;e.push(o(t.result))};t.onerror=function(){e.emit("error",t.error)};t.readAsArrayBuffer(this._file.slice(r,n))};a.prototype.destroy=function(){this._file=null;if(this.reader){this.reader.onload=null;this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}},{inherits:55,stream:108,"typedarray-to-buffer":118}],49:[function(e,t,r){t.exports=function n(e,t){t=typeof t=="number"?t:Infinity;return r(e,1);function r(e,n){return e.reduce(function(e,i){if(Array.isArray(i)&&n=Math.pow(2,e)){return n(e,t)}else return o};n.rack=function(e,t,r){var i=function(i){var o=0;do{if(o++>10){if(r)e+=r;else throw new Error("too many ID collisions, use more bits")}var a=n(e,t)}while(Object.hasOwnProperty.call(s,a));s[a]=i;return a};var s=i.hats={};i.get=function(e){return i.hats[e]};i.set=function(e,t){i.hats[e]=t;return i};i.bits=e||128;i.base=t||16;return i}},{}],52:[function(e,t,r){var n=e("http");var i=t.exports;for(var s in n){if(n.hasOwnProperty(s))i[s]=n[s]}i.request=function(e,t){if(!e)e={};e.scheme="https";e.protocol="https:";return n.request.call(this,e,t)}},{http:109}],53:[function(e,t,r){r.read=function(e,t,r,n,i){var s,o;var a=i*8-n-1;var f=(1<>1;var h=-7;var l=r?i-1:0;var c=r?-1:1;var d=e[t+l];l+=c;s=d&(1<<-h)-1;d>>=-h;h+=a;for(;h>0;s=s*256+e[t+l],l+=c,h-=8){}o=s&(1<<-h)-1;s>>=-h;h+=n;for(;h>0;o=o*256+e[t+l],l+=c,h-=8){}if(s===0){s=1-u}else if(s===f){return o?NaN:(d?-1:1)*Infinity}else{o=o+Math.pow(2,n);s=s-u}return(d?-1:1)*o*Math.pow(2,s-n)};r.write=function(e,t,r,n,i,s){var o,a,f;var u=s*8-i-1;var h=(1<>1;var c=i===23?Math.pow(2,-24)-Math.pow(2,-77):0;var d=n?0:s-1;var p=n?1:-1;var m=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){a=isNaN(t)?1:0;o=h}else{o=Math.floor(Math.log(t)/Math.LN2);if(t*(f=Math.pow(2,-o))<1){o--;f*=2}if(o+l>=1){t+=c/f}else{t+=c*Math.pow(2,1-l)}if(t*f>=2){o++;f/=2}if(o+l>=h){a=0;o=h}else if(o+l>=1){a=(t*f-1)*Math.pow(2,i);o=o+l}else{a=t*Math.pow(2,l-1)*Math.pow(2,i);o=0}}for(;i>=8;e[r+d]=a&255,d+=p,a/=256,i-=8){}o=o<0;e[r+d]=o&255,d+=p,o/=256,u-=8){}e[r+d-p]|=m*128}},{}],54:[function(e,t,r){(function(e){t.exports=r;function r(e){if(!(this instanceof r))return new r(e);this.store=e;if(!this.store||!this.store.get||!this.store.put){throw new Error("First argument must be abstract-chunk-store compliant")}this.mem=[]}r.prototype.put=function(e,t,r){var n=this;n.mem[e]=t;n.store.put(e,t,function(t){n.mem[e]=null;if(r)r(t)})};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);var i=t&&t.offset||0;var s=t&&t.length&&i+t.length;var o=this.mem[e];if(o)return n(r,null,t?o.slice(i,s):o);this.store.get(e,t,r)};r.prototype.close=function(e){this.store.close(e)};r.prototype.destroy=function(e){this.store.destroy(e)};function n(t,r,n){e.nextTick(function(){if(t)t(r,n)})}}).call(this,e("_process"))},{_process:83}],55:[function(e,t,r){if(typeof Object.create==="function"){t.exports=function n(e,t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}else{t.exports=function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype;e.prototype=new r;e.prototype.constructor=e}}},{}],56:[function(e,t,r){var n=Array.isArray;var i=Object.prototype.toString;t.exports=n||function(e){return!!e&&"[object Array]"==i.call(e)}},{}],57:[function(e,t,r){t.exports=function(e){return!!(e!=null&&(e._isBuffer||e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)))}},{}],58:[function(e,t,r){"use strict";var n=e("fs");t.exports=function s(e,t){if(!t)return i(e);n.stat(e,function(e,r){if(e)return t(e);return t(null,r.isFile())})};t.exports.sync=i;function i(e){return n.existsSync(e)&&n.statSync(e).isFile()}},{fs:35}],59:[function(e,t,r){t.exports=s;s.strict=o;s.loose=a;var n=Object.prototype.toString;var i={"[object Int8Array]":true,"[object Int16Array]":true,"[object Int32Array]":true,"[object Uint8Array]":true,"[object Uint8ClampedArray]":true,"[object Uint16Array]":true,"[object Uint32Array]":true,"[object Float32Array]":true,"[object Float64Array]":true};function s(e){return o(e)||a(e)}function o(e){return e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array}function a(e){return i[n.call(e)]}},{}],60:[function(e,t,r){t.exports=Array.isArray||function(e){return Object.prototype.toString.call(e)=="[object Array]"}},{}],61:[function(e,t,r){"use strict";r.re=/^npm-debug\.log$|^\..*\.swp$|^\.DS_Store$|^\.AppleDouble$|^\.LSOverride$|^Icon[\r\?]?|^\._.*|^\.Spotlight-V100$|\.Trashes|^__MACOSX$|~$|^Thumbs\.db$|^ehthumbs\.db$|^Desktop\.ini$/; r.is=function(e){return r.re.test(e)};r.not=r.isnt=function(e){return!r.is(e)}},{}],62:[function(e,t,r){(function(r){t.exports=o;t.exports.decode=o;t.exports.encode=a;var n=e("thirty-two");var i=e("xtend");var s=e("uniq");function o(e){var t={};var i=e.split("magnet:?")[1];var o=i&&i.length>=0?i.split("&"):[];o.forEach(function(e){var r=e.split("=");if(r.length!==2)return;var n=r[0];var i=r[1];if(n==="dn")i=decodeURIComponent(i).replace(/\+/g," ");if(n==="tr"||n==="xs"||n==="as"||n==="ws"){i=decodeURIComponent(i)}if(n==="kt")i=decodeURIComponent(i).split("+");if(t[n]){if(Array.isArray(t[n])){t[n].push(i)}else{var s=t[n];t[n]=[s,i]}}else{t[n]=i}});var a;if(t.xt){var f=Array.isArray(t.xt)?t.xt:[t.xt];f.forEach(function(e){if(a=e.match(/^urn:btih:(.{40})/)){t.infoHash=new r(a[1],"hex").toString("hex")}else if(a=e.match(/^urn:btih:(.{32})/)){var i=n.decode(a[1]);t.infoHash=new r(i,"binary").toString("hex")}})}if(t.dn)t.name=t.dn;if(t.kt)t.keywords=t.kt;if(typeof t.tr==="string")t.announce=[t.tr];else if(Array.isArray(t.tr))t.announce=t.tr;else t.announce=[];s(t.announce);t.urlList=[];if(typeof t.as==="string"||Array.isArray(t.as)){t.urlList=t.urlList.concat(t.as)}if(typeof t.ws==="string"||Array.isArray(t.ws)){t.urlList=t.urlList.concat(t.ws)}return t}function a(e){e=i(e);if(e.infoHash)e.xt="urn:btih:"+e.infoHash;if(e.name)e.dn=e.name;if(e.keywords)e.kt=e.keywords;if(e.announce)e.tr=e.announce;if(e.urlList){e.ws=e.urlList;delete e.as}var t="magnet:?";Object.keys(e).filter(function(e){return e.length===2}).forEach(function(r,n){var i=Array.isArray(e[r])?e[r]:[e[r]];i.forEach(function(e,i){if((n>0||i>0)&&(r!=="kt"||i===0))t+="&";if(r==="dn")e=encodeURIComponent(e).replace(/%20/g,"+");if(r==="tr"||r==="xs"||r==="as"||r==="ws"){e=encodeURIComponent(e)}if(r==="kt")e=encodeURIComponent(e);if(r==="kt"&&i>0)t+="+"+e;else t+=r+"="+e})});return t}}).call(this,e("buffer").Buffer)},{buffer:36,"thirty-two":114,uniq:119,xtend:126}],63:[function(e,t,r){t.exports=o;var n=e("inherits");var i=e("stream");var s=typeof window!=="undefined"&&window.MediaSource;n(o,i.Writable);function o(e,t){var r=this;if(!(r instanceof o))return new o(e,t);i.Writable.call(r,t);if(!s)throw new Error("web browser lacks MediaSource support");if(!t)t={};r._elem=e;r._mediaSource=new s;r._sourceBuffer=null;r._cb=null;r._type=t.type||a(t.extname);if(!r._type)throw new Error("missing `opts.type` or `opts.extname` options");r._elem.src=window.URL.createObjectURL(r._mediaSource);r._mediaSource.addEventListener("sourceopen",function(){if(s.isTypeSupported(r._type)){r._sourceBuffer=r._mediaSource.addSourceBuffer(r._type);r._sourceBuffer.addEventListener("updateend",r._flow.bind(r));r._flow()}else{r._mediaSource.endOfStream("decode")}});r.on("finish",function(){r._mediaSource.endOfStream()})}o.prototype._write=function(e,t,r){var n=this;if(!n._sourceBuffer){n._cb=function(i){if(i)return r(i);n._write(e,t,r)};return}if(n._sourceBuffer.updating){return r(new Error("Cannot append buffer while source buffer updating"))}n._sourceBuffer.appendBuffer(e);n._cb=r};o.prototype._flow=function(){var e=this;if(e._cb){e._cb(null)}};function a(e){if(!e)return null;if(e[0]!==".")e="."+e;return{".m4a":'audio/mp4; codecs="mp4a.40.5"',".m4v":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".mp3":"audio/mpeg",".mp4":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".webm":'video/webm; codecs="vorbis, vp8"'}[e]}},{inherits:55,stream:108}],64:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(!(this instanceof r))return new r(e,t);if(!t)t={};this.chunkLength=Number(e);if(!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[];this.closed=false;this.length=Number(t.length)||Infinity;if(this.length!==Infinity){this.lastChunkLength=this.length%this.chunkLength||this.chunkLength;this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1}}r.prototype.put=function(e,t,r){if(this.closed)return n(r,new Error("Storage is closed"));var i=e===this.lastChunkIndex;if(i&&t.length!==this.lastChunkLength){return n(r,new Error("Last chunk length must be "+this.lastChunkLength))}if(!i&&t.length!==this.chunkLength){return n(r,new Error("Chunk length must be "+this.chunkLength))}this.chunks[e]=t;n(r,null)};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);if(this.closed)return n(r,new Error("Storage is closed"));var i=this.chunks[e];if(!i)return n(r,new Error("Chunk not found"));if(!t)return n(r,null,i);var s=t.offset||0;var o=t.length||i.length-s;n(r,null,i.slice(s,o+s))};r.prototype.close=r.prototype.destroy=function(e){if(this.closed)return n(e,new Error("Storage is closed"));this.closed=true;this.chunks=null;n(e,null)};function n(t,r,n){e.nextTick(function(){if(t)t(r,n)})}}).call(this,e("_process"))},{_process:83}],65:[function(e,t,r){var n=function(e,t,r){this._byteOffset=t||0;if(e instanceof ArrayBuffer){this.buffer=e}else if(typeof e=="object"){this.dataView=e;if(t){this._byteOffset+=t}}else{this.buffer=new ArrayBuffer(e||0)}this.position=0;this.endianness=r==null?n.LITTLE_ENDIAN:r};t.exports=n;n.prototype={};n.prototype.save=function(e){var t=new Blob([this.buffer]);var r=window.webkitURL||window.URL;if(r&&r.createObjectURL){var n=r.createObjectURL(t);var i=document.createElement("a");i.setAttribute("href",n);i.setAttribute("download",e);i.click();r.revokeObjectURL(n)}else{throw"DataStream.save: Can't create object URL."}};n.BIG_ENDIAN=false;n.LITTLE_ENDIAN=true;n.prototype._dynamicSize=true;Object.defineProperty(n.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(e){if(!e){this._trimAlloc()}this._dynamicSize=e}});n.prototype._byteLength=0;Object.defineProperty(n.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}});Object.defineProperty(n.prototype,"buffer",{get:function(){this._trimAlloc();return this._buffer},set:function(e){this._buffer=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(n.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(n.prototype,"dataView",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset;this._buffer=e.buffer;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._byteOffset+e.byteLength}});n.prototype._realloc=function(e){if(!this._dynamicSize){return}var t=this._byteOffset+this.position+e;var r=this._buffer.byteLength;if(t<=r){if(t>this._byteLength){this._byteLength=t}return}if(r<1){r=1}while(t>r){r*=2}var n=new ArrayBuffer(r);var i=new Uint8Array(this._buffer);var s=new Uint8Array(n,0,i.length);s.set(i);this.buffer=n;this._byteLength=t};n.prototype._trimAlloc=function(){if(this._byteLength==this._buffer.byteLength){return}var e=new ArrayBuffer(this._byteLength);var t=new Uint8Array(e);var r=new Uint8Array(this._buffer,0,t.length);t.set(r);this.buffer=e};n.prototype.shift=function(e){var t=new ArrayBuffer(this._byteLength-e);var r=new Uint8Array(t);var n=new Uint8Array(this._buffer,e,r.length);r.set(n);this.buffer=t;this.position-=e};n.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t};n.prototype.isEof=function(){return this.position>=this._byteLength};n.prototype.mapInt32Array=function(e,t){this._realloc(e*4);var r=new Int32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.mapInt16Array=function(e,t){this._realloc(e*2);var r=new Int16Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};n.prototype.mapInt8Array=function(e){this._realloc(e*1);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};n.prototype.mapUint32Array=function(e,t){this._realloc(e*4);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.mapUint16Array=function(e,t){this._realloc(e*2);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};n.prototype.mapUint8Array=function(e){this._realloc(e*1);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};n.prototype.mapFloat64Array=function(e,t){this._realloc(e*8);var r=new Float64Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*8;return r};n.prototype.mapFloat32Array=function(e,t){this._realloc(e*4);var r=new Float32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.readInt32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Int32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readInt16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Int16Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readInt8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Int8Array(e);n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};n.prototype.readUint32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Uint32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readUint16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Uint16Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readUint8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Uint8Array(e);n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};n.prototype.readFloat64Array=function(e,t){e=e==null?this.byteLength-this.position/8:e;var r=new Float64Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readFloat32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Float32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.writeInt32Array=function(e,t){this._realloc(e.length*4);if(e instanceof Int32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0){n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength);this.mapInt32Array(e.length,t)}else{for(var r=0;r0;n.memcpy=function(e,t,r,n,i){var s=new Uint8Array(e,t,i);var o=new Uint8Array(r,n,i);s.set(o)};n.arrayToNative=function(e,t){if(t==this.endianness){return e}else{return this.flipArrayEndianness(e)}};n.nativeToEndian=function(e,t){if(this.endianness==t){return e}else{return this.flipArrayEndianness(e)}};n.flipArrayEndianness=function(e){var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(var r=0;ri;n--,i++){var s=t[i];t[i]=t[n];t[n]=s}}return e};n.prototype.failurePosition=0;n.prototype.readStruct=function(e){var t={},r,n,i;var s=this.position;for(var o=0;o>16);this.writeUint8((e&65280)>>8);this.writeUint8(e&255)};n.prototype.adjustUint32=function(e,t){var r=this.position;this.seek(e);this.writeUint32(t);this.seek(r)}},{}],66:[function(e,t,r){var n=e("./DataStream");var s=e("./descriptor");var o=e("./log");var a={ERR_NOT_ENOUGH_DATA:0,OK:1,boxCodes:["mdat","avcC","hvcC","ftyp","payl","vmhd","smhd","hmhd","dref","elst"],fullBoxCodes:["mvhd","tkhd","mdhd","hdlr","smhd","hmhd","nhmd","url ","urn ","ctts","cslg","stco","co64","stsc","stss","stsz","stz2","stts","stsh","mehd","trex","mfhd","tfhd","trun","tfdt","esds","subs","txtC"],containerBoxCodes:[["moov",["trak"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl"],["mvex",["trex"]],["moof",["traf"]],["traf",["trun"]],["vttc"],["tref"]],sampleEntryCodes:[{prefix:"Visual",types:["mp4v","avc1","avc2","avc3","avc4","avcp","drac","encv","mjp2","mvc1","mvc2","resv","s263","svc1","vc-1","hvc1","hev1"]},{prefix:"Audio",types:["mp4a","ac-3","alac","dra1","dtsc","dtse",,"dtsh","dtsl","ec-3","enca","g719","g726","m4ae","mlpa","raw ","samr","sawb","sawp","sevc","sqcp","ssmv","twos"]},{prefix:"Hint",types:["fdp ","m2ts","pm2t","prtp","rm2t","rrtp","rsrp","rtp ","sm2t","srtp"]},{prefix:"Metadata",types:["metx","mett","urim"]},{prefix:"Subtitle",types:["stpp","wvtt","sbtt","tx3g","stxt"]}],trackReferenceTypes:["scal"],initialize:function(){var e,t;var r;a.FullBox.prototype=new a.Box;a.ContainerBox.prototype=new a.Box;a.stsdBox.prototype=new a.FullBox;a.SampleEntry.prototype=new a.FullBox;a.TrackReferenceTypeBox.prototype=new a.Box;r=a.boxCodes.length;for(e=0;ee.byteLength){e.seek(n);o.w("BoxParser",'Not enough data in stream to parse the entire "'+f+'" box');return{code:a.ERR_NOT_ENOUGH_DATA,type:f,size:s,hdr_size:i}}if(a[f+"Box"]){r=new a[f+"Box"](s-i)}else{if(t){r=new a.SampleEntry(f,s-i)}else{r=new a.Box(f,s-i)}}r.hdr_size=i;r.start=n;r.fileStart=n+e.buffer.fileStart;r.parse(e);e.seek(n+s);return{code:a.OK,box:r,size:s}}};t.exports=a;a.initialize();a.Box.prototype.parse=function(e){if(this.type!="mdat"){this.data=e.readUint8Array(this.size)}else{e.seek(this.start+this.size+this.hdr_size)}};a.FullBox.prototype.parseFullHeader=function(e){this.version=e.readUint8();this.flags=e.readUint24();this.size-=4};a.ContainerBox.prototype.parse=function(e){var t;var r;var n;n=e.position;while(e.position=4){this.compatible_brands[t]=e.readString(4);this.size-=4;t++}};a.mvhdBox.prototype.parse=function(e){this.flags=0;this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.rate=e.readUint32();this.volume=e.readUint16()>>8;e.readUint16();e.readUint32Array(2);this.matrix=e.readUint32Array(9);e.readUint32Array(6);this.next_track_id=e.readUint32()};a.TKHD_FLAG_ENABLED=1;a.TKHD_FLAG_IN_MOVIE=2;a.TKHD_FLAG_IN_PREVIEW=4;a.tkhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint32()}e.readUint32Array(2);this.layer=e.readInt16();this.alternate_group=e.readInt16();this.volume=e.readInt16()>>8;e.readUint16();this.matrix=e.readInt32Array(9);this.width=e.readUint32();this.height=e.readUint32()};a.mdhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.language=e.readUint16();var t=[];t[0]=this.language>>10&31;t[1]=this.language>>5&31;t[2]=this.language&31;this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96);e.readUint16()};a.hdlrBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version===0){e.readUint32();this.handler=e.readString(4);e.readUint32Array(3);this.name=e.readCString()}else{this.data=e.readUint8Array(size)}};a.stsdBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);r=e.readUint32();for(i=1;i<=r;i++){t=a.parseOneBox(e,true);this.entries.push(t.box)}};a.avcCBox.prototype.parse=function(e){var t;var r;var n;this.configurationVersion=e.readUint8();this.AVCProfileIndication=e.readUint8();this.profile_compatibility=e.readUint8();this.AVCLevelIndication=e.readUint8();this.lengthSizeMinusOne=e.readUint8()&3;r=e.readUint8()&31;this.size-=6;this.SPS=new Array(r);for(t=0;t0){this.ext=e.readUint8Array(this.size)}};a.hvcCBox.prototype.parse=function(e){var t;var r;var n;var i;this.configurationVersion=e.readUint8();i=e.readUint8();this.general_profile_space=i>>6;this.general_tier_flag=(i&32)>>5;this.general_profile_idc=i&31;this.general_profile_compatibility=e.readUint32();this.general_constraint_indicator=e.readUint8Array(6);this.general_level_idc=e.readUint8();this.min_spatial_segmentation_idc=e.readUint16()&4095;this.parallelismType=e.readUint8()&3;this.chromaFormat=e.readUint8()&3;this.bitDepthLumaMinus8=e.readUint8()&7;this.bitDepthChromaMinus8=e.readUint8()&7;this.avgFrameRate=e.readUint16();i=e.readUint8();this.constantFrameRate=i>>6;this.numTemporalLayers=(i&13)>>3;this.temporalIdNested=(i&4)>>2;this.lengthSizeMinusOne=i&3;this.nalu_arrays=[];numOfArrays=e.readUint8();for(t=0;t>7;s.nalu_type=i&63;numNalus=e.readUint16();for(j=0;j>=1}t+=f(n,0);t+=".";if(this.hvcC.general_tier_flag===0){t+="L"}else{t+="H"}t+=this.hvcC.general_level_idc;var i=false;var s="";for(e=5;e>=0;e--){if(this.hvcC.general_constraint_indicator[e]||i){s="."+f(this.hvcC.general_constraint_indicator[e],0)+s;i=true}}t+=s}return t};a.mp4aBox.prototype.getCodec=function(){var e=a.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var t=this.esds.esd.getOTI();var r=this.esds.esd.getAudioConfig();return e+"."+f(t)+(r?"."+r:"")}else{return e}};a.esdsBox.prototype.parse=function(e){this.parseFullHeader(e);this.data=e.readUint8Array(this.size);this.size=0;var t=new s;this.esd=t.parseOneDescriptor(new n(this.data.buffer,0,n.BIG_ENDIAN))};a.txtCBox.prototype.parse=function(e){this.parseFullHeader(e);this.config=e.readCString()};a.cttsBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);t=e.readUint32();this.sample_counts=[];this.sample_offsets=[];if(this.version===0){for(r=0;rt&&this.flags&a.TFHD_FLAG_BASE_DATA_OFFSET){this.base_data_offset=e.readUint64();t+=8}else{this.base_data_offset=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_DESC){this.default_sample_description_index=e.readUint32();t+=4}else{this.default_sample_description_index=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_DUR){this.default_sample_duration=e.readUint32();t+=4}else{this.default_sample_duration=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_SIZE){this.default_sample_size=e.readUint32();t+=4}else{this.default_sample_size=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_FLAGS){this.default_sample_flags=e.readUint32();t+=4}else{this.default_sample_flags=0}};a.TRUN_FLAGS_DATA_OFFSET=1;a.TRUN_FLAGS_FIRST_FLAG=4;a.TRUN_FLAGS_DURATION=256;a.TRUN_FLAGS_SIZE=512;a.TRUN_FLAGS_FLAGS=1024;a.TRUN_FLAGS_CTS_OFFSET=2048;a.trunBox.prototype.parse=function(e){var t=0;this.parseFullHeader(e);this.sample_count=e.readUint32();t+=4;if(this.size>t&&this.flags&a.TRUN_FLAGS_DATA_OFFSET){this.data_offset=e.readInt32();t+=4}else{this.data_offset=0}if(this.size>t&&this.flags&a.TRUN_FLAGS_FIRST_FLAG){this.first_sample_flags=e.readUint32();t+=4}else{this.first_sample_flags=0}this.sample_duration=[];this.sample_size=[];this.sample_flags=[];this.sample_composition_time_offset=[];if(this.size>t){for(var r=0;r0){for(r=0;rn.MAX_SIZE){this.size+=8}o.d("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.position+(t||""));if(this.size>n.MAX_SIZE){e.writeUint32(1)}else{this.sizePosition=e.position;e.writeUint32(this.size)}e.writeString(this.type,null,4);if(this.size>n.MAX_SIZE){e.writeUint64(this.size)}};a.FullBox.prototype.writeHeader=function(e){this.size+=4;a.Box.prototype.writeHeader.call(this,e," v="+this.version+" f="+this.flags);e.writeUint8(this.version);e.writeUint24(this.flags)};a.Box.prototype.write=function(e){if(this.type==="mdat"){if(this.data){this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}}else{this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}};a.ContainerBox.prototype.write=function(e){this.size=0;this.writeHeader(e);for(var t=0;t>3}else{return null}};a.DecoderConfigDescriptor=function(e){a.Descriptor.call(this,t,e)};a.DecoderConfigDescriptor.prototype=new a.Descriptor;a.DecoderConfigDescriptor.prototype.parse=function(e){this.oti=e.readUint8();this.streamType=e.readUint8();this.bufferSize=e.readUint24();this.maxBitrate=e.readUint32();this.avgBitrate=e.readUint32();this.size-=13;this.parseRemainingDescriptors(e)};a.DecoderSpecificInfo=function(e){a.Descriptor.call(this,r,e)};a.DecoderSpecificInfo.prototype=new a.Descriptor;a.SLConfigDescriptor=function(e){a.Descriptor.call(this,i,e)};a.SLConfigDescriptor.prototype=new a.Descriptor;return this};t.exports=i},{"./log":69}],68:[function(e,t,r){var n=e("./box");var i=e("./DataStream");var s=e("./log");var o=function(e){this.stream=e;this.boxes=[];this.mdats=[];this.moofs=[];this.isProgressive=false;this.lastMoofIndex=0;this.lastBoxStartPosition=0;this.parsingMdat=null;this.moovStartFound=false;this.samplesDataSize=0;this.nextParsePosition=0};t.exports=o;o.prototype.mergeNextBuffer=function(){var e;if(this.stream.bufferIndex+1"+this.stream.buffer.byteLength+")");return true}else{return false}}else{return false}};o.prototype.parse=function(){var e;var t;var r;s.d("ISOFile","Starting parsing with buffer #"+this.stream.bufferIndex+" (fileStart: "+this.stream.buffer.fileStart+" - Length: "+this.stream.buffer.byteLength+") from position "+this.lastBoxStartPosition+" ("+(this.stream.buffer.fileStart+this.lastBoxStartPosition)+" in the file)");this.stream.seek(this.lastBoxStartPosition);while(true){if(this.parsingMdat!==null){r=this.parsingMdat;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){s.d("ISOFile","Found 'mdat' end in buffer #"+this.stream.bufferIndex);this.parsingMdat=null;continue}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex);return}}else{this.lastBoxStartPosition=this.stream.position;t=n.parseOneBox(this.stream);if(t.code===n.ERR_NOT_ENOUGH_DATA){if(t.type==="mdat"){r=new n[t.type+"Box"](t.size-t.hdr_size);this.parsingMdat=r;this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+this.stream.position;r.hdr_size=t.hdr_size;this.stream.buffer.usedBytes+=t.hdr_size;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){this.parsingMdat=null;continue}else{if(!this.moovStartFound){this.nextParsePosition=r.fileStart+r.size+r.hdr_size}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex)}return}}else{if(t.type==="moov"){this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}}else if(t.type==="free"){e=this.reposition(false,this.stream.buffer.fileStart+this.stream.position+t.size);if(e){continue}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size;return}}merged=this.mergeNextBuffer();if(merged){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength;continue}else{if(!t.type){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{if(this.moovStartFound){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size}}return}}}else{r=t.box;this.boxes.push(r);switch(r.type){case"mdat":this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+r.start;break;case"moof":this.moofs.push(r);break;case"moov":this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}default:if(this[r.type]!==undefined){s.w("ISOFile","Duplicate Box of type: "+r.type+", overriding previous occurrence")}this[r.type]=r;break}if(r.type==="mdat"){this.stream.buffer.usedBytes+=r.hdr_size}else{this.stream.buffer.usedBytes+=t.size}}}}};o.prototype.reposition=function(e,t){var r;r=this.findPosition(e,t);if(r!==-1){this.stream.buffer=this.stream.nextBuffers[r];this.stream.bufferIndex=r;this.stream.position=t-this.stream.buffer.fileStart;s.d("ISOFile","Repositioning parser at buffer position: "+this.stream.position);return true}else{return false}};o.prototype.findPosition=function(e,t){var r;var n=null;var i=-1;if(e===true){r=0}else{r=this.stream.bufferIndex}while(r=t){s.d("ISOFile","Found position in existing buffer #"+i);return i}else{return-1}}else{return-1}};o.prototype.findEndContiguousBuf=function(e){var t;var r;var n;r=this.stream.nextBuffers[e];if(this.stream.nextBuffers.length>e+1){for(t=e+1;t-1){this.moov.boxes.splice(r,1)}this.moov.mvex=null}this.moov.mvex=new n.mvexBox;this.moov.boxes.push(this.moov.mvex);this.moov.mvex.mehd=new n.mehdBox;this.moov.mvex.boxes.push(this.moov.mvex.mehd);this.moov.mvex.mehd.fragment_duration=this.initial_duration;for(t=0;t0?this.moov.traks[t].samples[0].duration:0;o.default_sample_size=0;o.default_sample_flags=1<<16}this.moov.write(e)};o.prototype.resetTables=function(){var e;var t,r,n,i,s,o,a,f;this.initial_duration=this.moov.mvhd.duration;this.moov.mvhd.duration=0;for(e=0;eg){_++;if(g<0){g=0}g+=a.sample_counts[_]}if(t>0){n.samples[t-1].duration=a.sample_deltas[_];x.dts=n.samples[t-1].dts+n.samples[t-1].duration}else{x.dts=0}if(f){if(t>y){b++;y+=f.sample_counts[b]}x.cts=n.samples[t].dts+f.sample_offsets[b]}else{x.cts=x.dts}if(u){if(t==u.sample_numbers[w]-1){x.is_rap=true;w++}else{x.is_rap=false}}else{x.is_rap=true}if(l){if(l.samples[subs_entry_index].sample_delta+last_subs_sample_index==t){x.subsamples=l.samples[subs_entry_index].subsamples;last_subs_sample_index+=l.samples[subs_entry_index].sample_delta}}}if(t>0)n.samples[t-1].duration=n.mdia.mdhd.duration-n.samples[t-1].dts}};o.prototype.updateSampleLists=function(){var e,t,r;var i,s,o,a;var f;var u,h,l,c,d;var p;while(this.lastMoofIndex0){p.dts=c.samples[c.samples.length-2].dts+c.samples[c.samples.length-2].duration}else{if(l.tfdt){p.dts=l.tfdt.baseMediaDecodeTime}else{p.dts=0}c.first_traf_merged=true}p.cts=p.dts;if(m.flags&n.TRUN_FLAGS_CTS_OFFSET){p.cts=p.dts+m.sample_composition_time_offset[r]}sample_flags=a;if(m.flags&n.TRUN_FLAGS_FLAGS){sample_flags=m.sample_flags[r]}else if(r===0&&m.flags&n.TRUN_FLAGS_FIRST_FLAG){sample_flags=m.first_sample_flags}p.is_rap=sample_flags>>16&1?false:true;var v=l.tfhd.flags&n.TFHD_FLAG_BASE_DATA_OFFSET?true:false;var g=l.tfhd.flags&n.TFHD_FLAG_DEFAULT_BASE_IS_MOOF?true:false;var _=m.flags&n.TRUN_FLAGS_DATA_OFFSET?true:false;var y=0;if(!v){if(!g){if(t===0){y=h.fileStart}else{y=f}}else{y=h.fileStart}}else{y=l.tfhd.base_data_offset}if(t===0&&r===0){if(_){p.offset=y+m.data_offset}else{p.offset=y}}else{p.offset=f}f=p.offset+p.size}}if(l.subs){var b=l.first_sample_index;for(t=0;t0){t+=","}t+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return t};o.prototype.getTrexById=function(e){var t;if(!this.originalMvex)return null;for(t=0;t=r.fileStart&&o.offset+o.alreadyRead=o){console.debug("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},i:function(t,r){if(i>=o){console.info("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},w:function(t,i){if(r>=o){console.warn("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",i)}},e:function(r,i){if(t>=o){console.error("["+n.getDurationString(new Date-e,1e3)+"]","["+r+"]",i)}}};return a}();t.exports=n;n.getDurationString=function(e,t){function r(e,t){var r=""+e;var n=r.split(".");while(n[0].length0){var r="";for(var i=0;i0)r+=",";r+="["+n.getDurationString(e.start(i))+","+n.getDurationString(e.end(i))+"]"}return r}else{return"(empty)"}}},{}],70:[function(e,t,r){var n=e("./box");var s=e("./DataStream");var o=e("./isofile");var a=e("./log");var f=function(){this.inputStream=null;this.nextBuffers=[];this.inputIsoFile=null;this.onMoovStart=null;this.moovStartSent=false;this.onReady=null;this.readySent=false;this.onSegment=null;this.onSamples=null;this.onError=null;this.sampleListBuilt=false;this.fragmentedTracks=[];this.extractedTracks=[];this.isFragmentationStarted=false;this.nextMoofNumber=0};t.exports=f;f.prototype.setSegmentOptions=function(e,t,r){var n=this.inputIsoFile.getTrackById(e);if(n){var i={};this.fragmentedTracks.push(i);i.id=e;i.user=t;i.trak=n;n.nextSample=0;i.segmentStream=null;i.nb_samples=1e3;i.rapAlignement=true;if(r){if(r.nbSamples)i.nb_samples=r.nbSamples;if(r.rapAlignement)i.rapAlignement=r.rapAlignement}}};f.prototype.unsetSegmentOptions=function(e){var t=-1;for(var r=0;r-1){this.fragmentedTracks.splice(t,1)}};f.prototype.setExtractionOptions=function(e,t,r){var n=this.inputIsoFile.getTrackById(e);if(n){var i={};this.extractedTracks.push(i);i.id=e;i.user=t;i.trak=n;n.nextSample=0;i.nb_samples=1e3;i.samples=[];if(r){if(r.nbSamples)i.nb_samples=r.nbSamples}}};f.prototype.unsetExtractionOptions=function(e){var t=-1;for(var r=0;r-1){this.extractedTracks.splice(t,1)}};f.prototype.createSingleSampleMoof=function(e){var t=new n.moofBox;var r=new n.mfhdBox;r.sequence_number=this.nextMoofNumber;this.nextMoofNumber++;t.boxes.push(r);var i=new n.trafBox;t.boxes.push(i);var s=new n.tfhdBox;i.boxes.push(s);s.track_id=e.track_id;s.flags=n.TFHD_FLAG_DEFAULT_BASE_IS_MOOF;var o=new n.tfdtBox;i.boxes.push(o);o.baseMediaDecodeTime=e.dts;var a=new n.trunBox;i.boxes.push(a);t.trun=a;a.flags=n.TRUN_FLAGS_DATA_OFFSET|n.TRUN_FLAGS_DURATION|n.TRUN_FLAGS_SIZE|n.TRUN_FLAGS_FLAGS|n.TRUN_FLAGS_CTS_OFFSET;a.data_offset=0;a.first_sample_flags=0;a.sample_count=1;a.sample_duration=[];a.sample_duration[0]=e.duration;a.sample_size=[];a.sample_size[0]=e.size;a.sample_flags=[];a.sample_flags[0]=0;a.sample_composition_time_offset=[];a.sample_composition_time_offset[0]=e.cts-e.dts;return t};f.prototype.createFragment=function(e,t,r,i){var o=this.inputIsoFile.getTrackById(t);var f=this.inputIsoFile.getSample(o,r);if(f==null){if(this.nextSeekPosition){this.nextSeekPosition=Math.min(o.samples[r].offset,this.nextSeekPosition)}else{this.nextSeekPosition=o.samples[r].offset}return null}var u=i||new s;u.endianness=s.BIG_ENDIAN;var h=this.createSingleSampleMoof(f);h.write(u);h.trun.data_offset=h.size+8;a.d("BoxWriter","Adjusting data_offset with new value "+h.trun.data_offset);u.adjustUint32(h.trun.data_offset_position,h.trun.data_offset);var l=new n.mdatBox;l.data=f.data;l.write(u);return u};ArrayBuffer.concat=function(e,t){a.d("ArrayBuffer","Trying to create a new buffer of size: "+(e.byteLength+t.byteLength));var r=new Uint8Array(e.byteLength+t.byteLength);r.set(new Uint8Array(e),0);r.set(new Uint8Array(t),e.byteLength);return r.buffer};f.prototype.reduceBuffer=function(e,t,r){var n;n=new Uint8Array(r);n.set(new Uint8Array(e,t,r));n.buffer.fileStart=e.fileStart+t;n.buffer.usedBytes=0;return n.buffer};f.prototype.insertBuffer=function(e){var t=true;for(var r=0;rn.byteLength){this.nextBuffers.splice(r,1);r--;continue}else{a.w("MP4Box","Buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+") already appended, ignoring")}}else{if(e.fileStart+e.byteLength<=n.fileStart){}else{e=this.reduceBuffer(e,0,n.fileStart-e.fileStart)}a.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.splice(r,0,e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}t=false;break}else if(e.fileStart0){e=this.reduceBuffer(e,i,s)}else{t=false;break}}}if(t){a.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.push(e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}};f.prototype.processSamples=function(){var e;var t;if(this.isFragmentationStarted&&this.onSegment!==null){for(e=0;e=t.samples.length){a.i("MP4Box","Sending fragmented data on track #"+r.id+" for samples ["+(t.nextSample-r.nb_samples)+","+(t.nextSample-1)+"]");if(this.onSegment){this.onSegment(r.id,r.user,r.segmentStream.buffer,t.nextSample)}r.segmentStream=null;if(r!==this.fragmentedTracks[e]){break}}}}}if(this.onSamples!==null){for(e=0;e=t.samples.length){a.d("MP4Box","Sending samples on track #"+i.id+" for sample "+t.nextSample);if(this.onSamples){this.onSamples(i.id,i.user,i.samples)}i.samples=[];if(i!==this.extractedTracks[e]){break}}}}}};f.prototype.appendBuffer=function(e){var t;var r;if(e===null||e===undefined){throw"Buffer must be defined and non empty"}if(e.fileStart===undefined){throw"Buffer must have a fileStart property"}if(e.byteLength===0){a.w("MP4Box","Ignoring empty buffer (fileStart: "+e.fileStart+")");return}e.usedBytes=0;this.insertBuffer(e);if(!this.inputStream){if(this.nextBuffers.length>0){r=this.nextBuffers[0];if(r.fileStart===0){this.inputStream=new s(r,0,s.BIG_ENDIAN);this.inputStream.nextBuffers=this.nextBuffers;this.inputStream.bufferIndex=0}else{a.w("MP4Box","The first buffer should have a fileStart of 0");return}}else{a.w("MP4Box","No buffer to start parsing from");return}}if(!this.inputIsoFile){this.inputIsoFile=new o(this.inputStream)}this.inputIsoFile.parse();if(this.inputIsoFile.moovStartFound&&!this.moovStartSent){this.moovStartSent=true;if(this.onMoovStart)this.onMoovStart()}if(this.inputIsoFile.moov){if(!this.sampleListBuilt){this.inputIsoFile.buildSampleLists();this.sampleListBuilt=true}this.inputIsoFile.updateSampleLists();if(this.onReady&&!this.readySent){var n=this.getInfo();this.readySent=true;this.onReady(n)}this.processSamples();if(this.nextSeekPosition){t=this.nextSeekPosition;this.nextSeekPosition=undefined}else{t=this.inputIsoFile.nextParsePosition}var i=this.inputIsoFile.findPosition(true,t);if(i!==-1){t=this.inputIsoFile.findEndContiguousBuf(i)}a.i("MP4Box","Next buffer to fetch should have a fileStart position of "+t);return t}else{if(this.inputIsoFile!==null){return this.inputIsoFile.nextParsePosition}else{return 0}}};f.prototype.getInfo=function(){var e={};var t;var r;var n;var s=new Date(4,0,1,0,0,0,0).getTime();e.duration=this.inputIsoFile.moov.mvhd.duration;e.timescale=this.inputIsoFile.moov.mvhd.timescale;e.isFragmented=this.inputIsoFile.moov.mvex!=null;if(e.isFragmented&&this.inputIsoFile.moov.mvex.mehd){e.fragment_duration=this.inputIsoFile.moov.mvex.mehd.fragment_duration}else{e.fragment_duration=0}e.isProgressive=this.inputIsoFile.isProgressive;e.hasIOD=this.inputIsoFile.moov.iods!=null;e.brands=[];e.brands.push(this.inputIsoFile.ftyp.major_brand);e.brands=e.brands.concat(this.inputIsoFile.ftyp.compatible_brands);e.created=new Date(s+this.inputIsoFile.moov.mvhd.creation_time*1e3);e.modified=new Date(s+this.inputIsoFile.moov.mvhd.modification_time*1e3);e.tracks=[];e.audioTracks=[];e.videoTracks=[];e.subtitleTracks=[];e.metadataTracks=[];e.hintTracks=[];e.otherTracks=[];for(i=0;ie*i.timescale){f=r.samples[n-1].offset;h=n-1;break}if(t&&i.is_rap){s=i.offset;o=i.cts;u=n}}if(t){r.nextSample=u;a.i("MP4Box","Seeking to RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+a.getDurationString(o,l)+" and offset: "+s);return{offset:s,time:o/l}}else{r.nextSample=h;a.i("MP4Box","Seeking to non-RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+a.getDurationString(e)+" and offset: "+s);return{offset:f,time:e}}};f.prototype.seek=function(e,t){var r=this.inputIsoFile.moov;var n;var i;var s;var o={offset:Infinity,time:Infinity};if(!this.inputIsoFile.moov){throw"Cannot seek: moov not received!"}else{for(s=0;s1e4)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);var f=(t[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return r*a;case"days":case"day":case"d":return r*o;case"hours":case"hour":case"hrs":case"hr":case"h":return r*s;case"minutes":case"minute":case"mins":case"min":case"m":return r*i;case"seconds":case"second":case"secs":case"sec":case"s":return r*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r}}function u(e){if(e>=o)return Math.round(e/o)+"d";if(e>=s)return Math.round(e/s)+"h";if(e>=i)return Math.round(e/i)+"m";if(e>=n)return Math.round(e/n)+"s";return e+"ms"}function h(e){return l(e,o,"day")||l(e,s,"hour")||l(e,i,"minute")||l(e,n,"second")||e+" ms"}function l(e,t,r){if(e0?[e["url-list"]]:[]}t.urlList=(e["url-list"]||[]).map(function(e){return e.toString()});var a=e.info.files||[e.info];t.files=a.map(function(e,r){var n=[].concat(t.name,e["path.utf-8"]||e.path||[]).map(function(e){return e.toString()});return{path:i.join.apply(null,[i.sep].concat(n)).slice(1),name:n[n.length-1],length:e.length,offset:a.slice(0,r).reduce(u,0)}});t.length=a.reduce(u,0);var f=t.files[t.files.length-1];t.pieceLength=e.info["piece length"];t.lastPieceLength=(f.offset+f.length)%t.pieceLength||t.pieceLength;t.pieces=h(e.info.pieces);return t}function f(e){var t={info:e.info};t["announce-list"]=e.announce.map(function(e){if(!t.announce)t.announce=e;e=new r(e,"utf8");return[e]});if(e.created){t["creation date"]=e.created.getTime()/1e3|0}if(e.urlList){t["url-list"]=e.urlList}return n.encode(t)}function u(e,t){return e+t.length}function h(e){var t=[];for(var r=0;r=0;n--){var i=e[n];if(i==="."){e.splice(n,1)}else if(i===".."){e.splice(n,1);r++}else if(r){e.splice(n,1);r--}}if(t){for(;r--;r){e.unshift("..")}}return e}var n=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var i=function(e){return n.exec(e).slice(1)};r.resolve=function(){var r="",n=false;for(var i=arguments.length-1;i>=-1&&!n;i--){var o=i>=0?arguments[i]:e.cwd();if(typeof o!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!o){continue}r=o+"/"+r;n=o.charAt(0)==="/"}r=t(s(r.split("/"),function(e){return!!e}),!n).join("/");return(n?"/":"")+r||"."};r.normalize=function(e){var n=r.isAbsolute(e),i=o(e,-1)==="/";e=t(s(e.split("/"),function(e){return!!e}),!n).join("/");if(!e&&!n){e="."}if(e&&i){e+="/"}return(n?"/":"")+e};r.isAbsolute=function(e){return e.charAt(0)==="/"};r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(s(e,function(e,t){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))};r.relative=function(e,t){e=r.resolve(e).substr(1);t=r.resolve(t).substr(1);function n(e){var t=0;for(;t=0;r--){if(e[r]!=="")break}if(t>r)return[];return e.slice(t,r-t+1)}var i=n(e.split("/"));var s=n(t.split("/"));var o=Math.min(i.length,s.length);var a=o;for(var f=0;f1){for(var r=1;r0;return h(i,o,a,function(e){if(!r)r=e;if(e)n.forEach(l);if(o)return;n.forEach(l);t(r)})});return e.reduce(c)};t.exports=d},{"end-of-stream":46,fs:35,once:73}],85:[function(t,r,n){(function(t){(function(i){var s=typeof n=="object"&&n&&!n.nodeType&&n;var o=typeof r=="object"&&r&&!r.nodeType&&r;var a=typeof t=="object"&&t;if(a.global===a||a.window===a||a.self===a){i=a}var f,u=2147483647,h=36,l=1,c=26,d=38,p=700,m=72,v=128,g="-",_=/^xn--/,y=/[^\x20-\x7E]/,b=/[\x2E\u3002\uFF0E\uFF61]/g,w={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},S=h-l,x=Math.floor,k=String.fromCharCode,E;function A(e){throw RangeError(w[e])}function U(e,t){var r=e.length;var n=[];while(r--){n[r]=t(e[r])}return n}function T(e,t){var r=e.split("@");var n="";if(r.length>1){n=r[0]+"@";e=r[1]}e=e.replace(b,".");var i=e.split(".");var s=U(i,t).join(".");return n+s}function I(e){var t=[],r=0,n=e.length,i,s;while(r=55296&&i<=56319&&r65535){e-=65536;t+=k(e>>>10&1023|55296);e=56320|e&1023}t+=k(e);return t}).join("")}function B(e){if(e-48<10){return e-22}if(e-65<26){return e-65}if(e-97<26){return e-97}return h}function C(e,t){return e+22+75*(e<26)-((t!=0)<<5)}function R(e,t,r){var n=0;e=r?x(e/p):e>>1;e+=x(e/t);for(;e>S*c>>1;n+=h){e=x(e/S)}return x(n+(S+1)*e/(e+d))}function P(e){var t=[],r=e.length,n,i=0,s=v,o=m,a,f,d,p,_,y,b,w,S;a=e.lastIndexOf(g);if(a<0){a=0}for(f=0;f=128){A("not-basic")}t.push(e.charCodeAt(f))}for(d=a>0?a+1:0;d=r){A("invalid-input")}b=B(e.charCodeAt(d++));if(b>=h||b>x((u-i)/_)){A("overflow")}i+=b*_;w=y<=o?l:y>=o+c?c:y-o;if(bx(u/S)){A("overflow")}_*=S}n=t.length+1;o=R(i-p,n,p==0);if(x(i/n)>u-s){A("overflow")}s+=x(i/n);i%=n;t.splice(i++,0,s)}return L(t)}function F(e){var t,r,n,i,s,o,a,f,d,p,_,y=[],b,w,S,E;e=I(e);b=e.length;t=v;r=0;s=m;for(o=0;o=t&&_x((u-r)/w)){A("overflow")}r+=(a-t)*w;t=a;for(o=0;ou){A("overflow")}if(_==t){for(f=r,d=h;;d+=h){p=d<=s?l:d>=s+c?c:d-s;if(f0&&u>f){u=f}for(var h=0;h=0){d=l.substr(0,c);p=l.substr(c+1)}else{d=l;p=""}m=decodeURIComponent(d);v=decodeURIComponent(p);if(!n(o,m)){o[m]=v}else if(i(o[m])){o[m].push(v)}else{o[m]=[o[m],v]}}return o};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}},{}],87:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,a){t=t||"&";r=r||"=";if(e===null){e=undefined}if(typeof e==="object"){return s(o(e),function(o){var a=encodeURIComponent(n(o))+r;if(i(e[o])){return s(e[o],function(e){return a+encodeURIComponent(n(e))}).join(t)}else{return a+encodeURIComponent(n(e[o]))}}).join(t)}if(!a)return"";return encodeURIComponent(n(a))+r+encodeURIComponent(n(e))};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};function s(e,t){if(e.map)return e.map(t);var r=[];for(var n=0;n0){if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var o=new Error("stream.unshift() after end event");e.emit("error",o)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)S(e)}k(e,t)}}else if(!i){t.reading=false}return v(t)}function v(e){return!e.ended&&(e.needReadable||e.length=g){e=g}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function y(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(e===null||isNaN(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=_(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else{return t.length}}return e}p.prototype.read=function(e){l("read",e);var t=this._readableState;var r=e;if(typeof e!=="number"||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){l("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)C(this);else S(this);return null}e=y(e,t);if(e===0&&t.ended){if(t.length===0)C(this);return null}var n=t.needReadable;l("need readable",n);if(t.length===0||t.length-e0)i=B(e,t);else i=null;if(i===null){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)C(this);if(i!==null)this.emit("data",i);return i};function b(e,t){var r=null;if(!s.isBuffer(t)&&typeof t!=="string"&&t!==null&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function w(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;S(e)}function S(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){l("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)n(x,e);else x(e)}}function x(e){l("emit readable");e.emit("readable");L(e)}function k(e,t){if(!t.readingMore){t.readingMore=true;n(E,e,t)}}function E(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(i)a=r.join("");else if(r.length===1)a=r[0];else a=s.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;n(R,t,e)}}function R(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function P(e,t){for(var r=0,n=e.length;r-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e};function p(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=new i(t,r)}return t}function m(e,t,r,n,s){r=p(t,r,n);if(i.isBuffer(r))n="buffer";var o=t.objectMode?1:r.length;t.length+=o;var a=t.length0;e+=1);return e};var o=function(e,t){for(var r=t>>2;r>2]|=128<<24-(t%4<<3);e[((t>>2)+2&~15)+14]=r>>29;e[((t>>2)+2&~15)+15]=r<<3};var f=function(e,t,r,n,i){var s=this,o,a=i%4,f=n%4,u=n-f;if(u>0){switch(a){case 0:e[i+3|0]=s.charCodeAt(r);case 1:e[i+2|0]=s.charCodeAt(r+1);case 2:e[i+1|0]=s.charCodeAt(r+2);case 3:e[i|0]=s.charCodeAt(r+3)}}for(o=a;o>2]=s.charCodeAt(r+o)<<24|s.charCodeAt(r+o+1)<<16|s.charCodeAt(r+o+2)<<8|s.charCodeAt(r+o+3)}switch(f){case 3:e[i+u+1|0]=s.charCodeAt(r+u+2);case 2:e[i+u+2|0]=s.charCodeAt(r+u+1);case 1:e[i+u+3|0]=s.charCodeAt(r+u)}};var u=function(e,t,r,n,i){var s=this,o,a=i%4,f=n%4,u=n-f;if(u>0){switch(a){case 0:e[i+3|0]=s[r];case 1:e[i+2|0]=s[r+1];case 2:e[i+1|0]=s[r+2];case 3:e[i|0]=s[r+3]}}for(o=4-a;o>2]=s[r+o]<<24|s[r+o+1]<<16|s[r+o+2]<<8|s[r+o+3]}switch(f){case 3:e[i+u+1|0]=s[r+u+2];case 2:e[i+u+2|0]=s[r+u+1];case 1:e[i+u+3|0]=s[r+u]}};var h=function(e,t,r,n,s){var o=this,a,f=s%4,u=n%4,h=n-u;var l=new Uint8Array(i.readAsArrayBuffer(o.slice(r,r+n)));if(h>0){switch(f){case 0:e[s+3|0]=l[0];case 1:e[s+2|0]=l[1];case 2:e[s+1|0]=l[2];case 3:e[s|0]=l[3]}}for(a=4-f;a>2]=l[a]<<24|l[a+1]<<16|l[a+2]<<8|l[a+3]}switch(u){case 3:e[s+h+1|0]=l[h+2];case 2:e[s+h+2|0]=l[h+1];case 1:e[s+h+3|0]=l[h]}};var l=function(e){switch(r.getDataType(e)){case"string":return f.bind(e);case"array":return u.bind(e);case"buffer":return u.bind(e);case"arraybuffer":return u.bind(new Uint8Array(e));case"view":return u.bind(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));case"blob":return h.bind(e)}};var c=function(e,t){switch(r.getDataType(e)){case"string":return e.slice(t);case"array":return e.slice(t);case"buffer":return e.slice(t);case"arraybuffer":return e.slice(t);case"view":return e.buffer.slice(t)}};var d=function(e){var t,r,n="0123456789abcdef",i=[],s=new Uint8Array(e);for(t=0;t>4&15)+n.charAt(r>>0&15)}return i.join("")};var p=function(e){var t;if(e<=65536)return 65536;if(e<16777216){for(t=1;t0){throw new Error("Chunk size must be a multiple of 128 bit")}t.maxChunkLen=e;t.padMaxChunkLen=s(e);t.heap=new ArrayBuffer(p(t.padMaxChunkLen+320+20));t.h32=new Int32Array(t.heap);t.h8=new Int8Array(t.heap);t.core=new n._core({Int32Array:Int32Array,DataView:DataView},{},t.heap);t.buffer=null};m(e||64*1024);var v=function(e,t){var r=new Int32Array(e,t+320,5);r[0]=1732584193;r[1]=-271733879;r[2]=-1732584194;r[3]=271733878;r[4]=-1009589776};var g=function(e,r){ var n=s(e);var i=new Int32Array(t.heap,0,n>>2);o(i,e);a(i,e,r);return n};var _=function(e,r,n){l(e)(t.h8,t.h32,r,n,0)};var y=function(e,r,n,i,s){var o=n;if(s){o=g(n,i)}_(e,r,n);t.core.hash(o,t.padMaxChunkLen)};var b=function(e,t){var r=new Int32Array(e,t+320,5);var n=new Int32Array(5);var i=new DataView(n.buffer);i.setInt32(0,r[0],false);i.setInt32(4,r[1],false);i.setInt32(8,r[2],false);i.setInt32(12,r[3],false);i.setInt32(16,r[4],false);return n};var w=this.rawDigest=function(e){var r=e.byteLength||e.length||e.size||0;v(t.heap,t.padMaxChunkLen);var n=0,i=t.maxChunkLen,s;for(n=0;r>n+i;n+=i){y(e,n,i,r,false)}y(e,n,r-n,r,true);return b(t.heap,t.padMaxChunkLen)};this.digest=this.digestFromString=this.digestFromBuffer=this.digestFromArrayBuffer=function(e){return d(w(e).buffer)}}n._core=function o(e,t,r){"use asm";var n=new e.Int32Array(r);function i(e,t){e=e|0;t=t|0;var r=0,i=0,s=0,o=0,a=0,f=0,u=0,h=0,l=0,c=0,d=0,p=0,m=0,v=0;s=n[t+320>>2]|0;a=n[t+324>>2]|0;u=n[t+328>>2]|0;l=n[t+332>>2]|0;d=n[t+336>>2]|0;for(r=0;(r|0)<(e|0);r=r+64|0){o=s;f=a;h=u;c=l;p=d;for(i=0;(i|0)<64;i=i+4|0){v=n[r+i>>2]|0;m=((s<<5|s>>>27)+(a&u|~a&l)|0)+((v+d|0)+1518500249|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[e+i>>2]=v}for(i=e+64|0;(i|0)<(e+80|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a&u|~a&l)|0)+((v+d|0)+1518500249|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+80|0;(i|0)<(e+160|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a^u^l)|0)+((v+d|0)+1859775393|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+160|0;(i|0)<(e+240|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a&u|a&l|u&l)|0)+((v+d|0)-1894007588|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+240|0;(i|0)<(e+320|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a^u^l)|0)+((v+d|0)-899497514|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}s=s+o|0;a=a+f|0;u=u+h|0;l=l+c|0;d=d+p|0}n[t+320>>2]=s;n[t+324>>2]=a;n[t+328>>2]=u;n[t+332>>2]=l;n[t+336>>2]=d}return{hash:i}};if(typeof t!=="undefined"){t.exports=n}else if(typeof window!=="undefined"){window.Rusha=n}if(typeof FileReaderSync!=="undefined"){var i=new FileReaderSync,s=new n(4*1024*1024);self.onmessage=function a(e){var t,r=e.data.data;try{t=s.digest(r);self.postMessage({id:e.data.id,hash:t})}catch(n){self.postMessage({id:e.data.id,error:n.name})}}}})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],103:[function(e,t,r){(function(r){t.exports=u;var n=e("xtend");var i=e("http");var s=e("https");var o=e("once");var a=e("unzip-response");var f=e("url");function u(e,t){e=typeof e==="string"?{url:e}:n(e);t=o(t);if(e.url)h(e);if(e.headers==null)e.headers={};if(e.maxRedirects==null)e.maxRedirects=10;var r=e.body;e.body=undefined;if(r&&!e.method)e.method="POST";var f=Object.keys(e.headers).some(function(e){return e.toLowerCase()==="accept-encoding"});if(!f)e.headers["accept-encoding"]="gzip, deflate";var l=e.protocol==="https:"?s:i;var c=l.request(e,function(r){if(r.statusCode>=300&&r.statusCode<400&&"location"in r.headers){e.url=r.headers.location;h(e);r.resume();e.maxRedirects-=1;if(e.maxRedirects>0)u(e,t);else t(new Error("too many redirects"));return}t(null,typeof a==="function"?a(r):r)});c.on("error",t);c.end(r);return c}t.exports.concat=function(e,t){return u(e,function(e,n){if(e)return t(e);var i=[];n.on("data",function(e){i.push(e)});n.on("end",function(){t(null,r.concat(i),n)})})};["get","post","put","patch","head","delete"].forEach(function(e){t.exports[e]=function(t,r){if(typeof t==="string")t={url:t};t.method=e.toUpperCase();return u(t,r)}});function h(e){var t=f.parse(e.url);if(t.hostname)e.hostname=t.hostname;if(t.port)e.port=t.port;if(t.protocol)e.protocol=t.protocol;e.path=t.path;delete e.url}}).call(this,e("buffer").Buffer)},{buffer:36,http:109,https:52,once:73,"unzip-response":34,url:120,xtend:126}],104:[function(e,t,r){(function(r){t.exports=l;var n=e("debug")("simple-peer");var i=e("get-browser-rtc");var s=e("hat");var o=e("inherits");var a=e("is-typedarray");var f=e("once");var u=e("stream");var h=e("typedarray-to-buffer");o(l,u.Duplex);function l(e){var t=this;if(!(t instanceof l))return new l(e);t._debug("new peer %o",e);if(!e)e={};e.allowHalfOpen=false;if(e.highWaterMark==null)e.highWaterMark=1024*1024;u.Duplex.call(t,e);t.initiator=e.initiator||false;t.channelConfig=e.channelConfig||l.channelConfig;t.channelName=e.channelName||s(160);if(!e.initiator)t.channelName=null;t.config=e.config||l.config;t.constraints=e.constraints||l.constraints;t.reconnectTimer=e.reconnectTimer||0;t.sdpTransform=e.sdpTransform||function(e){return e};t.stream=e.stream||false;t.trickle=e.trickle!==undefined?e.trickle:true;t.destroyed=false;t.connected=false;t.remoteAddress=undefined;t.remoteFamily=undefined;t.remotePort=undefined;t.localAddress=undefined;t.localPort=undefined;t._wrtc=e.wrtc||i();if(!t._wrtc){if(typeof window==="undefined"){throw new Error("No WebRTC support: Specify `opts.wrtc` option in this environment")}else{throw new Error("No WebRTC support: Not a supported browser")}}t._maxBufferedAmount=e.highWaterMark;t._pcReady=false;t._channelReady=false;t._iceComplete=false;t._channel=null;t._pendingCandidates=[];t._chunk=null;t._cb=null;t._interval=null;t._reconnectTimeout=null;t._pc=new t._wrtc.RTCPeerConnection(t.config,t.constraints);t._pc.oniceconnectionstatechange=t._onIceConnectionStateChange.bind(t);t._pc.onsignalingstatechange=t._onSignalingStateChange.bind(t);t._pc.onicecandidate=t._onIceCandidate.bind(t);if(t.stream)t._pc.addStream(t.stream);t._pc.onaddstream=t._onAddStream.bind(t);if(t.initiator){t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)});t._pc.onnegotiationneeded=f(t._createOffer.bind(t));if(typeof window==="undefined"||!window.webkitRTCPeerConnection){t._pc.onnegotiationneeded()}}else{t._pc.ondatachannel=t._setupData.bind(t)}t.on("finish",function(){if(t.connected){setTimeout(function(){t._destroy()},100)}else{t.once("connect",function(){setTimeout(function(){t._destroy()},100)})}})}l.WEBRTC_SUPPORT=!!i();l.config={iceServers:[{url:"stun:23.21.150.121",urls:"stun:23.21.150.121"}]};l.constraints={};l.channelConfig={};Object.defineProperty(l.prototype,"bufferSize",{get:function(){var e=this;return e._channel&&e._channel.bufferedAmount||0}});l.prototype.address=function(){var e=this;return{port:e.localPort,family:"IPv4",address:e.localAddress}};l.prototype.signal=function(e){var t=this;if(t.destroyed)throw new Error("cannot signal after peer is destroyed");if(typeof e==="string"){try{e=JSON.parse(e)}catch(r){e={}}}t._debug("signal()");function n(e){try{t._pc.addIceCandidate(new t._wrtc.RTCIceCandidate(e),c,t._onError.bind(t))}catch(r){t._destroy(new Error("error adding candidate: "+r.message))}}if(e.sdp){t._pc.setRemoteDescription(new t._wrtc.RTCSessionDescription(e),function(){if(t.destroyed)return;if(t._pc.remoteDescription.type==="offer")t._createAnswer();t._pendingCandidates.forEach(n);t._pendingCandidates=[]},t._onError.bind(t))}if(e.candidate){if(t._pc.remoteDescription)n(e.candidate);else t._pendingCandidates.push(e.candidate)}if(!e.sdp&&!e.candidate){t._destroy(new Error("signal() called with invalid signal data"))}};l.prototype.send=function(e){var t=this;if(!a.strict(e)&&!(e instanceof ArrayBuffer)&&!r.isBuffer(e)&&typeof e!=="string"&&(typeof Blob==="undefined"||!(e instanceof Blob))){e=JSON.stringify(e)}if(r.isBuffer(e)&&!a.strict(e)){e=new Uint8Array(e)}var n=e.length||e.byteLength||e.size;t._channel.send(e);t._debug("write: %d bytes",n)};l.prototype.destroy=function(e){var t=this;t._destroy(null,e)};l.prototype._destroy=function(e,t){var r=this;if(r.destroyed)return;if(t)r.once("close",t);r._debug("destroy (error: %s)",e&&e.message);r.readable=r.writable=false;if(!r._readableState.ended)r.push(null);if(!r._writableState.finished)r.end();r.destroyed=true;r.connected=false;r._pcReady=false;r._channelReady=false;r._chunk=null;r._cb=null;clearInterval(r._interval);clearTimeout(r._reconnectTimeout);if(r._pc){try{r._pc.close()}catch(e){}r._pc.oniceconnectionstatechange=null;r._pc.onsignalingstatechange=null;r._pc.onicecandidate=null}if(r._channel){try{r._channel.close()}catch(e){}r._channel.onmessage=null;r._channel.onopen=null;r._channel.onclose=null}r._pc=null;r._channel=null;if(e)r.emit("error",e);r.emit("close")};l.prototype._setupData=function(e){var t=this;t._channel=e.channel;t.channelName=t._channel.label;t._channel.binaryType="arraybuffer";t._channel.onmessage=t._onChannelMessage.bind(t);t._channel.onopen=t._onChannelOpen.bind(t);t._channel.onclose=t._onChannelClose.bind(t)};l.prototype._read=function(){};l.prototype._write=function(e,t,r){var n=this;if(n.destroyed)return r(new Error("cannot write after peer is destroyed"));if(n.connected){try{n.send(e)}catch(i){return n._onError(i)}if(n._channel.bufferedAmount>n._maxBufferedAmount){n._debug("start backpressure: bufferedAmount %d",n._channel.bufferedAmount);n._cb=r}else{r(null)}}else{n._debug("write before connect");n._chunk=e;n._cb=r}};l.prototype._createOffer=function(){var e=this;if(e.destroyed)return;e._pc.createOffer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,c,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.offerConstraints)};l.prototype._createAnswer=function(){var e=this;if(e.destroyed)return;e._pc.createAnswer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,c,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.answerConstraints)};l.prototype._onIceConnectionStateChange=function(){var e=this;if(e.destroyed)return;var t=e._pc.iceGatheringState;var r=e._pc.iceConnectionState;e._debug("iceConnectionStateChange %s %s",t,r);e.emit("iceConnectionStateChange",t,r);if(r==="connected"||r==="completed"){clearTimeout(e._reconnectTimeout);e._pcReady=true;e._maybeReady()}if(r==="disconnected"){if(e.reconnectTimer){clearTimeout(e._reconnectTimeout);e._reconnectTimeout=setTimeout(function(){e._destroy()},e.reconnectTimer)}else{e._destroy()}}if(r==="closed"){e._destroy()}};l.prototype._maybeReady=function(){var e=this;e._debug("maybeReady pc %s channel %s",e._pcReady,e._channelReady);if(e.connected||e._connecting||!e._pcReady||!e._channelReady)return;e._connecting=true;if(typeof window!=="undefined"&&!!window.mozRTCPeerConnection){e._pc.getStats(null,function(e){var r=[];e.forEach(function(e){r.push(e)});t(r)},e._onError.bind(e))}else{e._pc.getStats(function(e){var r=[];e.result().forEach(function(e){var t={};e.names().forEach(function(r){t[r]=e.stat(r)});t.id=e.id;t.type=e.type;t.timestamp=e.timestamp;r.push(t)});t(r)})}function t(t){t.forEach(function(t){if(t.type==="remotecandidate"){e.remoteAddress=t.ipAddress;e.remotePort=Number(t.portNumber);e.remoteFamily="IPv4";e._debug("connect remote: %s:%s (%s)",e.remoteAddress,e.remotePort,e.remoteFamily)}else if(t.type==="localcandidate"&&t.candidateType==="host"){e.localAddress=t.ipAddress;e.localPort=Number(t.portNumber);e._debug("connect local: %s:%s",e.localAddress,e.localPort)}});e._connecting=false;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(r){return e._onError(r)}e._chunk=null;e._debug('sent chunk from "write before connect"');var n=e._cb;e._cb=null;n(null)}e._interval=setInterval(function(){if(!e._cb||!e._channel||e._channel.bufferedAmount>e._maxBufferedAmount)return;e._debug("ending backpressure: bufferedAmount %d",e._channel.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref();e._debug("connect");e.emit("connect")}};l.prototype._onSignalingStateChange=function(){var e=this;if(e.destroyed)return;e._debug("signalingStateChange %s",e._pc.signalingState);e.emit("signalingStateChange",e._pc.signalingState)};l.prototype._onIceCandidate=function(e){var t=this;if(t.destroyed)return;if(e.candidate&&t.trickle){t.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}})}else if(!e.candidate){t._iceComplete=true;t.emit("_iceComplete")}};l.prototype._onChannelMessage=function(e){var t=this;if(t.destroyed)return;var r=e.data;t._debug("read: %d bytes",r.byteLength||r.length);if(r instanceof ArrayBuffer){r=h(new Uint8Array(r));t.push(r)}else{try{r=JSON.parse(r)}catch(n){}t.emit("data",r)}};l.prototype._onChannelOpen=function(){var e=this;if(e.connected||e.destroyed)return;e._debug("on channel open");e._channelReady=true;e._maybeReady()};l.prototype._onChannelClose=function(){var e=this;if(e.destroyed)return;e._debug("on channel close");e._destroy()};l.prototype._onAddStream=function(e){var t=this;if(t.destroyed)return;t._debug("on add stream");t.emit("stream",e.stream)};l.prototype._onError=function(e){var t=this;if(t.destroyed)return;t._debug("error %s",e.message||e);t._destroy(e)};l.prototype._debug=function(){var e=this;var t=[].slice.call(arguments);var r=e.channelName&&e.channelName.substring(0,7);t[0]="["+r+"] "+t[0];n.apply(null,t)};function c(){}}).call(this,{isBuffer:e("../is-buffer/index.js")})},{"../is-buffer/index.js":57,debug:42,"get-browser-rtc":50,hat:51,inherits:55,"is-typedarray":59,once:73,stream:108,"typedarray-to-buffer":118}],105:[function(e,t,r){var n=e("rusha");var i=new n;var s=window.crypto||window.msCrypto||{};var o=s.subtle||s.webkitSubtle;var a=i.digest.bind(i);try{o.digest({name:"sha-1"},new Uint8Array).catch(function(){o=false})}catch(f){o=false}function u(e,t){if(!o){setTimeout(t,0,a(e));return}if(typeof e==="string"){e=h(e)}o.digest({name:"sha-1"},e).then(function r(e){t(l(new Uint8Array(e)))},function n(r){t(a(e))})}function h(e){var t=e.length;var r=new Uint8Array(t);for(var n=0;n>>4).toString(16));r.push((i&15).toString(16))}return r.join("")}t.exports=u;t.exports.sync=a},{rusha:102}],106:[function(e,t,r){(function(r){t.exports=h;var n=e("debug")("simple-websocket");var i=e("inherits");var s=e("is-typedarray");var o=e("stream");var a=e("typedarray-to-buffer");var f=e("ws");var u=typeof window!=="undefined"?window.WebSocket:f;i(h,o.Duplex);function h(e,t){var r=this;if(!(r instanceof h))return new h(e,t);if(!t)t={};n("new websocket: %s %o",e,t);t.allowHalfOpen=false;if(t.highWaterMark==null)t.highWaterMark=1024*1024;o.Duplex.call(r,t);r.url=e;r.connected=false;r.destroyed=false;r._maxBufferedAmount=t.highWaterMark;r._chunk=null;r._cb=null;r._interval=null;r._ws=new u(r.url);r._ws.binaryType="arraybuffer";r._ws.onopen=r._onOpen.bind(r);r._ws.onmessage=r._onMessage.bind(r);r._ws.onclose=r._onClose.bind(r);r._ws.onerror=function(){r._onError(new Error("connection error to "+r.url))};r.on("finish",function(){if(r.connected){setTimeout(function(){r._destroy()},100)}else{r.once("connect",function(){setTimeout(function(){r._destroy()},100)})}})}h.WEBSOCKET_SUPPORT=!!u;h.prototype.send=function(e){var t=this;if(!s.strict(e)&&!(e instanceof ArrayBuffer)&&!r.isBuffer(e)&&typeof e!=="string"&&(typeof Blob==="undefined"||!(e instanceof Blob))){e=JSON.stringify(e)}var i=e.length||e.byteLength||e.size;t._ws.send(e);n("write: %d bytes",i)};h.prototype.destroy=function(e){var t=this;t._destroy(null,e)};h.prototype._destroy=function(e,t){var r=this;if(r.destroyed)return;if(t)r.once("close",t);n("destroy (error: %s)",e&&e.message);this.readable=this.writable=false;if(!r._readableState.ended)r.push(null);if(!r._writableState.finished)r.end();r.connected=false;r.destroyed=true;clearInterval(r._interval);r._interval=null;r._chunk=null;r._cb=null;if(r._ws){var i=r._ws;var s=function(){i.onclose=null;r.emit("close")};if(i.readyState===u.CLOSED){s()}else{try{i.onclose=s;i.close()}catch(e){s()}}i.onopen=null;i.onmessage=null;i.onerror=null}r._ws=null;if(e)r.emit("error",e)};h.prototype._read=function(){};h.prototype._write=function(e,t,r){var i=this;if(i.destroyed)return r(new Error("cannot write after socket is destroyed"));if(i.connected){try{i.send(e)}catch(s){return i._onError(s)}if(typeof f!=="function"&&i._ws.bufferedAmount>i._maxBufferedAmount){n("start backpressure: bufferedAmount %d",i._ws.bufferedAmount);i._cb=r}else{r(null)}}else{n("write before connect");i._chunk=e;i._cb=r}};h.prototype._onMessage=function(e){var t=this;if(t.destroyed)return;var i=e.data;n("read: %d bytes",i.byteLength||i.length);if(i instanceof ArrayBuffer){i=a(new Uint8Array(i));t.push(i)}else if(r.isBuffer(i)){t.push(i)}else{try{i=JSON.parse(i)}catch(s){}t.emit("data",i)}};h.prototype._onOpen=function(){var e=this;if(e.connected||e.destroyed)return;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(t){return e._onError(t)}e._chunk=null;n('sent chunk from "write before connect"');var r=e._cb;e._cb=null;r(null)}if(typeof f!=="function"){e._interval=setInterval(function(){if(!e._cb||!e._ws||e._ws.bufferedAmount>e._maxBufferedAmount){return}n("ending backpressure: bufferedAmount %d",e._ws.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref()}n("connect");e.emit("connect")};h.prototype._onClose=function(){var e=this;if(e.destroyed)return;n("on close");e._destroy()};h.prototype._onError=function(e){var t=this;if(t.destroyed)return;n("error: %s",e.message||e);t._destroy(e)}}).call(this,{isBuffer:e("../is-buffer/index.js")})},{"../is-buffer/index.js":57,debug:42,inherits:55,"is-typedarray":59,stream:108,"typedarray-to-buffer":118,ws:34}],107:[function(e,t,r){var n=1;var i=65535;var s=4;var o=function(){n=n+1&i};var a=setInterval(o,1e3/s|0);if(a.unref)a.unref();t.exports=function(e){var t=s*(e||5);var r=[0];var o=1;var a=n-1&i;return function(e){var f=n-a&i;if(f>t)f=t;a=n;while(f--){if(o===t)o=0;r[o]=r[o===0?t-1:o-1];o++}if(e)r[o-1]+=e;var u=r[o-1];var h=r.lengthe._pos){var o=r.substr(e._pos);if(e._charset==="x-user-defined"){var a=new i(o.length);for(var u=0;ue._pos){e.push(new i(new Uint8Array(h.result.slice(e._pos))));e._pos=h.result.byteLength}};h.onload=function(){e.push(null)};h.readAsArrayBuffer(r);break}if(e._xhr.readyState===f.DONE&&e._mode!=="ms-stream"){e.push(null)}}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{"./capability":110,_process:83,buffer:36,inherits:55,stream:108}],113:[function(e,t,r){var n=e("buffer").Buffer;var i=n.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function s(e){if(e&&!i(e)){throw new Error("Unknown encoding: "+e)}}var o=r.StringDecoder=function(e){this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,"");s(e);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=f;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=u;break;default:this.write=a;return}this.charBuffer=new n(6);this.charReceived=0;this.charLength=0};o.prototype.write=function(e){var t="";while(this.charLength){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;e.copy(this.charBuffer,this.charReceived,0,r);this.charReceived+=r;if(this.charReceived=55296&&n<=56319){this.charLength+=this.surrogateSize;t="";continue}this.charReceived=this.charLength=0;if(e.length===0){return t}break}this.detectIncompleteChar(e);var i=e.length;if(this.charLength){e.copy(this.charBuffer,0,e.length-this.charReceived,i);i-=this.charReceived}t+=e.toString(this.encoding,0,i);var i=t.length-1;var n=t.charCodeAt(i);if(n>=55296&&n<=56319){var s=this.surrogateSize;this.charLength+=s;this.charReceived+=s;this.charBuffer.copy(this.charBuffer,s,0,s);e.copy(this.charBuffer,0,0,s);return t.substring(0,i)}return t};o.prototype.detectIncompleteChar=function(e){var t=e.length>=3?3:e.length;for(;t>0;t--){var r=e[e.length-t];if(t==1&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t};o.prototype.end=function(e){var t="";if(e&&e.length)t=this.write(e);if(this.charReceived){var r=this.charReceived;var n=this.charBuffer;var i=this.encoding;t+=n.slice(0,r).toString(i)}return t};function a(e){return e.toString(this.encoding)}function f(e){this.charReceived=e.length%2;this.charLength=this.charReceived?2:0}function u(e){this.charReceived=e.length%3;this.charLength=this.charReceived?3:0}},{buffer:36}],114:[function(e,t,r){var n=e("./thirty-two");r.encode=n.encode;r.decode=n.decode},{"./thirty-two":115}],115:[function(e,t,r){(function(e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";var n=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,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,255,255,255,255,255,255,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,255,255,255,255,255];function i(e){var t=Math.floor(e.length/5);return e.length%5==0?t:t+1}r.encode=function(r){var n=0;var s=0;var o=0;var a=0;var f=new e(i(r)*8);if(!e.isBuffer(r)){r=new e(r)}while(n3){a=u&255>>o;o=(o+5)%8;a=a<>8-o;n++}else{a=u>>8-(o+5)&31;o=(o+5)%8;if(o==0)n++}f[s]=t.charCodeAt(a);s++}for(n=s;n>>r;a[o]=s;o++;s=255&i<<8-r}}else{throw new Error("Invalid input - it is not base32 encoded string")}}return a.slice(0,o)}}).call(this,e("buffer").Buffer)},{buffer:36}],116:[function(e,t,r){(function(r,n){t.exports=c;var i=e("debug")("torrent-discovery");var s=e("bittorrent-dht/client");var o=e("events").EventEmitter;var a=e("xtend/mutable");var f=e("inherits");var u=e("run-parallel");var h=e("re-emitter"); -var l=e("bittorrent-tracker/client");f(c,o);function c(e){var t=this;if(!(t instanceof c))return new c(e);o.call(t);a(t,{announce:[],dht:typeof s==="function",rtcConfig:null,peerId:null,port:0,tracker:true,wrtc:null},e);t.infoHash=null;t.infoHashHex=null;t.torrent=null;t._externalDHT=typeof t.dht==="object";t._performedDHTLookup=false;if(!t.peerId)throw new Error("peerId required");if(!r.browser&&!t.port)throw new Error("port required");if(t.dht)t._createDHT(t.dhtPort)}c.prototype.setTorrent=function(e){var t=this;if(!t.infoHash&&n.isBuffer(e)||typeof e==="string"){t.infoHash=typeof e==="string"?new n(e,"hex"):e}else if(!t.torrent&&e&&e.infoHash){t.torrent=e;t.infoHash=typeof e.infoHash==="string"?new n(e.infoHash,"hex"):e.infoHash}else{return}t.infoHashHex=t.infoHash.toString("hex");i("setTorrent %s",t.infoHashHex);if(t.tracker&&t.tracker!==true){t.tracker.torrentLength=e.length}else{t._createTracker()}if(t.dht){if(t.dht.ready)t._dhtLookupAndAnnounce();else t.dht.on("ready",t._dhtLookupAndAnnounce.bind(t))}};c.prototype.updatePort=function(e){var t=this;if(e===t.port)return;t.port=e;if(t.dht&&t.infoHash){t._performedDHTLookup=false;t._dhtLookupAndAnnounce()}if(t.tracker&&t.tracker!==true){t.tracker.stop();t.tracker.destroy(function(){t._createTracker()})}};c.prototype.stop=function(e){var t=this;var r=[];if(t.tracker&&t.tracker!==true){t.tracker.stop();r.push(function(e){t.tracker.destroy(e)})}if(!t._externalDHT&&t.dht&&t.dht!==true){r.push(function(e){t.dht.destroy(e)})}u(r,e)};c.prototype._createDHT=function(e){var t=this;if(!t._externalDHT)t.dht=new s;h(t.dht,t,["error","warning"]);t.dht.on("peer",function(e,r){if(r===t.infoHashHex)t.emit("peer",e)});if(!t._externalDHT)t.dht.listen(e)};c.prototype._createTracker=function(){var e=this;if(!e.tracker)return;var t=e.torrent?a({announce:[]},e.torrent):{infoHash:e.infoHashHex,announce:[]};if(e.announce)t.announce=t.announce.concat(e.announce);var r={rtcConfig:e.rtcConfig,wrtc:e.wrtc};e.tracker=new l(e.peerId,e.port,t,r);h(e.tracker,e,["peer","warning","error"]);e.tracker.on("update",function(t){e.emit("trackerAnnounce",t)});e.tracker.start()};c.prototype._dhtLookupAndAnnounce=function(){var e=this;if(e._performedDHTLookup)return;e._performedDHTLookup=true;i("dht lookup");e.dht.lookup(e.infoHash,function(t){if(t||!e.port)return;i("dht announce");e.dht.announce(e.infoHash,e.port,function(){i("dht announce complete");e.emit("dhtAnnounce")})})}}).call(this,e("_process"),e("buffer").Buffer)},{_process:83,"bittorrent-dht/client":34,"bittorrent-tracker/client":23,buffer:36,debug:42,events:47,inherits:55,"re-emitter":90,"run-parallel":101,"xtend/mutable":127}],117:[function(e,t,r){(function(e){t.exports=n;var r=1<<14;function n(e){if(!(this instanceof n))return new n(e);this.length=e;this.missing=e;this.sources=null;this._chunks=Math.ceil(e/r);this._remainder=e%r||r;this._buffered=0;this._buffer=null;this._cancellations=null;this._reservations=0;this._flushed=false}n.BLOCK_LENGTH=r;n.prototype.chunkLength=function(e){return e===this._chunks-1?this._remainder:r};n.prototype.chunkOffset=function(e){return e*r};n.prototype.reserve=function(){if(!this.init())return-1;if(this._cancellations.length)return this._cancellations.pop();if(this._reservations",'"',"`"," ","\r","\n"," "],h=["{","}","|","\\","^","`"].concat(u),l=["'"].concat(h),c=["%","/","?",";","#"].concat(l),d=["/","?","#"],p=255,m=/^[+a-z0-9A-Z_-]{0,63}$/,v=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:true,"javascript:":true},_={javascript:true,"javascript:":true},y={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},b=e("querystring");function w(e,t,r){if(e&&i.isObject(e)&&e instanceof s)return e;var n=new s;n.parse(e,t,r);return n}s.prototype.parse=function(e,t,r){if(!i.isString(e)){throw new TypeError("Parameter 'url' must be a string, not "+typeof e)}var s=e.indexOf("?"),a=s!==-1&&s127){F+="x"}else{F+=P[O]}}if(!F.match(m)){var D=C.slice(0,U);var N=C.slice(U+1);var z=P.match(v);if(z){D.push(z[1]);N.unshift(z[2])}if(N.length){w="/"+N.join(".")+w}this.hostname=D.join(".");break}}}}if(this.hostname.length>p){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!B){this.hostname=n.toASCII(this.hostname)}var j=this.port?":"+this.port:"";var H=this.hostname||"";this.host=H+j;this.href+=this.host;if(B){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(w[0]!=="/"){w="/"+w}}}if(!g[k]){for(var U=0,R=l.length;U0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}r.search=e.search;r.query=e.query;if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.href=r.format();return r}if(!x.length){r.pathname=null;if(r.search){r.path="/"+r.search}else{r.path=null}r.href=r.format();return r}var A=x.slice(-1)[0];var U=(r.host||e.host||x.length>1)&&(A==="."||A==="..")||A==="";var T=0;for(var I=x.length;I>=0;I--){A=x[I];if(A==="."){x.splice(I,1)}else if(A===".."){x.splice(I,1);T++}else if(T){x.splice(I,1);T--}}if(!w&&!S){for(;T--;T){x.unshift("..")}}if(w&&x[0]!==""&&(!x[0]||x[0].charAt(0)!=="/")){x.unshift("")}if(U&&x.join("/").substr(-1)!=="/"){x.push("")}var L=x[0]===""||x[0]&&x[0].charAt(0)==="/";if(k){r.hostname=r.host=L?"":x.length?x.shift():"";var E=r.host&&r.host.indexOf("@")>0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}w=w||r.host&&x.length;if(w&&!L){x.unshift("")}if(!x.length){r.pathname=null;r.path=null}else{r.pathname=x.join("/")}if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.auth=e.auth||r.auth;r.slashes=r.slashes||e.slashes;r.href=r.format();return r};s.prototype.parseHost=function(){var e=this.host;var t=a.exec(e);if(t){t=t[0];if(t!==":"){this.port=t.substr(1)}e=e.substr(0,e.length-t.length)}if(e)this.hostname=e}},{"./util":121,punycode:85,querystring:88}],121:[function(e,t,r){"use strict";t.exports={isString:function(e){return typeof e==="string"},isObject:function(e){return typeof e==="object"&&e!==null},isNull:function(e){return e===null},isNullOrUndefined:function(e){return e==null}}},{}],122:[function(e,t,r){(function(r){var n=e("bencode");var i=e("bitfield");var s=e("events").EventEmitter;var o=e("inherits");var a=e("simple-sha1");var f=1e7;var u=1e3;var h=16*1024;t.exports=function(e){o(t,s);function t(t){s.call(this);this._wire=t;this._metadataComplete=false;this._metadataSize=null;this._remainingRejects=null;this._fetching=false;this._bitfield=new i(0,{grow:u});if(r.isBuffer(e)){this.setMetadata(e)}}t.prototype.name="ut_metadata";t.prototype.onHandshake=function(e,t,r){this._infoHash=e;this._infoHashHex=e.toString("hex")};t.prototype.onExtendedHandshake=function(e){if(!e.m||!e.m.ut_metadata){return this.emit("warning",new Error("Peer does not support ut_metadata"))}if(!e.metadata_size){return this.emit("warning",new Error("Peer does not have metadata"))}if(e.metadata_size>f){return this.emit("warning",new Error("Peer gave maliciously large metadata size"))}this._metadataSize=e.metadata_size;this._numPieces=Math.ceil(this._metadataSize/h);this._remainingRejects=this._numPieces*2;if(this._fetching){this._requestPieces()}};t.prototype.onMessage=function(e){var t,r;try{var i=e.toString();var s=i.indexOf("ee")+2;t=n.decode(i.substring(0,s));r=e.slice(s)}catch(o){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,r,t.total_size);break;case 2:this._onReject(t.piece);break}};t.prototype.fetch=function(){if(this._metadataComplete){return}this._fetching=true;if(this._metadataSize){this._requestPieces()}};t.prototype.cancel=function(){this._fetching=false};t.prototype.setMetadata=function(e){if(this._metadataComplete)return true;try{var t=n.decode(e).info;if(t){e=n.encode(t)}}catch(r){}if(this._infoHashHex&&this._infoHashHex!==a.sync(e)){return false}this.cancel();this.metadata=e;this._metadataComplete=true;this._metadataSize=this.metadata.length;this._wire.extendedHandshake.metadata_size=this._metadataSize;this.emit("metadata",n.encode({info:n.decode(this.metadata)}));return true};t.prototype._send=function(e,t){var i=n.encode(e);if(r.isBuffer(t)){i=r.concat([i,t])}this._wire.extended("ut_metadata",i)};t.prototype._request=function(e){this._send({msg_type:0,piece:e})};t.prototype._data=function(e,t,r){var n={msg_type:1,piece:e};if(typeof r==="number"){n.total_size=r}this._send(n,t)};t.prototype._reject=function(e){this._send({msg_type:2,piece:e})};t.prototype._onRequest=function(e){if(!this._metadataComplete){this._reject(e);return}var t=e*h;var r=t+h;if(r>this._metadataSize){r=this._metadataSize}var n=this.metadata.slice(t,r);this._data(e,n,this._metadataSize)};t.prototype._onData=function(e,t,r){if(t.length>h){return}t.copy(this.metadata,e*h);this._bitfield.set(e);this._checkDone()};t.prototype._onReject=function(e){if(this._remainingRejects>0&&this._fetching){this._request(e);this._remainingRejects-=1}else{this.emit("warning",new Error('Peer sent "reject" too much'))}};t.prototype._requestPieces=function(){this.metadata=new r(this._metadataSize);for(var e=0;e0){this._requestPieces()}else{this.emit("warning",new Error("Peer sent invalid metadata"))}};return t}}).call(this,e("buffer").Buffer)},{bencode:11,bitfield:15,buffer:36,events:47,inherits:55,"simple-sha1":105}],123:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(n("noDeprecation")){return e}var r=false;function i(){if(!r){if(n("throwDeprecation")){throw new Error(t)}else if(n("traceDeprecation")){console.trace(t)}else{console.warn(t)}r=true}return e.apply(this,arguments)}return i}function n(t){try{if(!e.localStorage)return false}catch(r){return false}var n=e.localStorage[t];if(null==n)return false;return String(n).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],124:[function(e,t,r){var n=e("debug")("videostream");var i=e("mp4box");var s=.01;var o=60;t.exports=function(e,t,r){r=r||{};var f=r.debugTrack||-1;var u=[];function h(){t.addEventListener("waiting",S);t.addEventListener("timeupdate",E)}h();var l=false;function c(e){l=true;t.removeEventListener("waiting",S);t.removeEventListener("timeupdate",E);if(p.readyState==="open")p.endOfStream(e)}function d(e){var r=e.buffer.buffered;var i=t.currentTime;var a=-1;for(var f=0;fi){break}else if(a>=0||i<=h){a=h}}var l=a-i;if(l<0)l=0;n("Buffer length: %f",l);return l<=o}var p=new MediaSource;p.addEventListener("sourceopen",function(){w(0)});t.src=window.URL.createObjectURL(p);var m=new i;m.onError=function(e){n("MP4Box error: %s",e.message);if(b){b()}if(p.readyState==="open"){c("decode")}};var v=false;var g={};m.onReady=function(e){n("MP4 info: %o",e);e.tracks.forEach(function(e){var t;if(e.video){t="video/mp4"}else if(e.audio){t="audio/mp4"}else{return}t+='; codecs="'+e.codec+'"';if(MediaSource.isTypeSupported(t)){var r=p.addSourceBuffer(t);var n={buffer:r,arrayBuffers:[],meta:e,ended:false};r.addEventListener("updateend",A.bind(null,n));m.setSegmentOptions(e.id,null,{nbSamples:e.video?1:100});g[e.id]=n}});if(Object.keys(g).length===0){c("decode");return}var t=m.initializeSegmentation();t.forEach(function(e){k(g[e.id],e.buffer);if(e.id===f){a("init-track-"+f+".mp4",[e.buffer]);u.push(e.buffer)}});v=true};m.onSegment=function(e,t,r,n){var i=g[e];k(i,r,n===i.meta.nb_samples);if(e===f&&u){u.push(r);if(n>1e3){a("track-"+f+".mp4",u);u=null}}};var _;var y=null;var b=null;function w(t){if(t===e.length){m.flush();return}if(y&&t===_){var r=y;setTimeout(function(){if(y===r)y.resume()});return}if(y){y.destroy();b()}_=t;var i={start:_,end:e.length-1};y=e.createReadStream(i);function s(e){y.pause();var t=e.toArrayBuffer();t.fileStart=_;_+=t.byteLength;var r;try{r=m.appendBuffer(t)}catch(i){n("MP4Box threw exception: %s",i.message);if(p.readyState==="open"){c("decode")}y.destroy();b();return}w(r)}y.on("data",s);function o(){b();w(_)}y.on("end",o);function a(e){n("Stream error: %s",e.message);if(p.readyState==="open"){c("network")}}y.on("error",a);b=function(){y.removeListener("data",s);y.removeListener("end",o);y.removeListener("error",a);y=null;b=null}}function S(){if(v){x(t.currentTime)}}function x(e){if(l)h();var t=m.seek(e,true);n("Seeking to time: %d",e);n("Seeked file offset: %d",t.offset);w(t.offset)}function k(e,t,r){e.arrayBuffers.push({buffer:t,ended:r||false});A(e)}function E(){Object.keys(g).forEach(function(e){var t=g[e];if(t.blocked){A(t)}})}function A(e){if(e.buffer.updating)return;e.blocked=!d(e);if(e.blocked)return;if(e.arrayBuffers.length===0)return;var t=e.arrayBuffers.shift();var r=false;try{e.buffer.appendBuffer(t.buffer);e.ended=t.ended;r=true}catch(i){n("SourceBuffer error: %s",i.message);c("decode");return}if(r){U()}}function U(){if(p.readyState!=="open"){return}var e=Object.keys(g).every(function(e){var t=g[e];return t.ended&&!t.buffer.updating});if(e){c()}}};function a(e,t){var r=new Blob(t);var n=URL.createObjectURL(r);var i=document.createElement("a");i.setAttribute("href",n);i.setAttribute("download",e);i.click()}},{debug:42,mp4box:70}],125:[function(e,t,r){t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=="function")throw new TypeError("need wrapper function");Object.keys(e).forEach(function(t){r[t]=e[t]});return r;function r(){var t=new Array(arguments.length);for(var r=0;r0)return new Array(e+(/\./.test(t)?2:1)).join(r)+t;return t+""}},{}],129:[function(e,t,r){t.exports={name:"webtorrent",description:"Streaming torrent client",version:"0.63.0",author:{name:"Feross Aboukhadijeh",email:"feross@feross.org",url:"http://feross.org/"},bin:{webtorrent:"./bin/cmd.js"},browser:{"./lib/server.js":false,"bittorrent-dht/client":false,"fs-chunk-store":"memory-chunk-store","load-ip-set":false,ut_pex:false},bugs:{url:"https://github.com/feross/webtorrent/issues"},dependencies:{"addr-to-ip-port":"^1.0.1",bitfield:"^1.0.2","bittorrent-dht":"^4.0.4","bittorrent-swarm":"^5.0.0","chunk-store-stream":"^2.0.0",clivas:"^0.2.0","create-torrent":"^3.4.0","cross-spawn-async":"^2.0.0",debug:"^2.1.0","end-of-stream":"^1.0.0",executable:"^2.1.0","fs-chunk-store":"^1.3.4",hat:"0.0.3","immediate-chunk-store":"^1.0.7",inherits:"^2.0.1",inquirer:"^0.11.0","load-ip-set":"^1.0.3",mediasource:"^1.0.0","memory-chunk-store":"^1.2.0",mime:"^1.2.11",minimist:"^1.1.0",moment:"^2.8.3",multistream:"^2.0.2","network-address":"^1.0.0","parse-torrent":"^5.1.0","path-exists":"^2.1.0","pretty-bytes":"^2.0.1",pump:"^1.0.0","random-iterate":"^1.0.1","range-parser":"^1.0.2","re-emitter":"^1.0.0","run-parallel":"^1.0.0","simple-sha1":"^2.0.0",speedometer:"^1.0.0",thunky:"^0.1.0","torrent-discovery":"^3.0.0","torrent-piece":"^1.0.0",uniq:"^1.0.1",ut_metadata:"^2.1.0",ut_pex:"^1.0.1",videostream:"^1.1.4","windows-no-runnable":"0.0.6",xtend:"^4.0.0","zero-fill":"^2.2.0"},devDependencies:{"bittorrent-tracker":"^6.0.0",brfs:"^1.2.0",browserify:"^12.0.1",finalhandler:"^0.4.0","run-auto":"^1.0.0","serve-static":"^1.9.3","simple-get":"^1.0.0",standard:"^5.1.0",tape:"^4.0.0","uglify-js":"^2.4.15",zelda:"^2.0.0",zuul:"^3.0.0"},homepage:"http://webtorrent.io",keywords:["torrent","bittorrent","bittorrent client","streaming","download","webrtc","webrtc data","webtorrent","mad science"],license:"MIT",main:"index.js",optionalDependencies:{"airplay-js":"^0.2.3",chromecasts:"^1.5.3",nodebmc:"0.0.5"},repository:{type:"git",url:"git://github.com/feross/webtorrent.git"},scripts:{build:"browserify -s WebTorrent -e ./ | uglifyjs -m > webtorrent.min.js","build-debug":"browserify -s WebTorrent -e ./ > webtorrent.debug.js",size:"npm run build && cat webtorrent.min.js | gzip | wc -c",test:"standard && node ./bin/test.js","test-browser":"zuul -- test/basic.js","test-browser-local":"zuul --local -- test/basic.js","test-node":"tape test/*.js"}}},{}],130:[function(e,t,r){(function(r,n,i){t.exports=w;var s=e("create-torrent");var o=e("debug")("webtorrent");var a=e("bittorrent-dht/client");var f=e("events").EventEmitter;var u=e("xtend");var h=e("hat");var l=e("inherits");var c=e("load-ip-set");var d=e("run-parallel");var p=e("parse-torrent");var m=e("speedometer");var v=e("zero-fill");var g=e("path");var _=e("./lib/torrent");l(w,f);var y=e("./package.json").version;var b=y.match(/([0-9]+)/g).slice(0,2).map(v(2)).join("");function w(e){var t=this;if(!(t instanceof w))return new w(e);if(!e)e={};f.call(t);if(!o.enabled)t.setMaxListeners(0);t.destroyed=false;t.torrentPort=e.torrentPort||0;t.tracker=e.tracker!==undefined?e.tracker:true;t._rtcConfig=e.rtcConfig;t._wrtc=e.wrtc||n.WRTC;t.torrents=[];t.downloadSpeed=m();t.uploadSpeed=m();t.peerId=e.peerId===undefined?new i("-WW"+b+"-"+h(48),"utf8"):typeof e.peerId==="string"?new i(e.peerId,"hex"):e.peerId;t.peerIdHex=t.peerId.toString("hex");t.nodeId=e.nodeId===undefined?new i(h(160),"hex"):typeof e.nodeId==="string"?new i(e.nodeId,"hex"):e.nodeId;t.nodeIdHex=t.nodeId.toString("hex");if(e.dht!==false&&typeof a==="function"){t.dht=new a(u({nodeId:t.nodeId},e.dht));t.dht.listen(e.dhtPort)}o("new webtorrent (peerId %s, nodeId %s)",t.peerIdHex,t.nodeIdHex);if(typeof c==="function"){c(e.blocklist,{headers:{"user-agent":"WebTorrent/"+y+" (http://webtorrent.io)"}},function(e,r){if(e)return t.error("Failed to load blocklist: "+e.message);t.blocked=r;s()})}else r.nextTick(s);function s(){if(t.destroyed)return;t.ready=true;t.emit("ready")}}Object.defineProperty(w.prototype,"ratio",{get:function(){var e=this;var t=e.torrents.reduce(function(e,t){return e+t.uploaded},0);var r=e.torrents.reduce(function(e,t){return e+t.downloaded},0)||1;return t/r}});w.prototype.get=function(e){var t=this;if(e instanceof _)return e;var r;try{r=p(e)}catch(n){}if(!r)return null;if(!r.infoHash)throw new Error("Invalid torrent identifier");for(var i=0,s=t.torrents.length;i",'"',"`"," ","\r","\n"," "],h=["{","}","|","\\","^","`"].concat(u),l=["'"].concat(h),c=["%","/","?",";","#"].concat(l),d=["/","?","#"],p=255,m=/^[+a-z0-9A-Z_-]{0,63}$/,v=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:true,"javascript:":true},_={javascript:true,"javascript:":true},y={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},b=e("querystring");function w(e,t,r){if(e&&i.isObject(e)&&e instanceof s)return e;var n=new s;n.parse(e,t,r);return n}s.prototype.parse=function(e,t,r){if(!i.isString(e)){throw new TypeError("Parameter 'url' must be a string, not "+typeof e)}var s=e.indexOf("?"),a=s!==-1&&s127){F+="x"}else{F+=P[O]}}if(!F.match(m)){var D=C.slice(0,U);var N=C.slice(U+1);var z=P.match(v);if(z){D.push(z[1]);N.unshift(z[2])}if(N.length){w="/"+N.join(".")+w}this.hostname=D.join(".");break}}}}if(this.hostname.length>p){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!B){this.hostname=n.toASCII(this.hostname)}var j=this.port?":"+this.port:"";var H=this.hostname||"";this.host=H+j;this.href+=this.host;if(B){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(w[0]!=="/"){w="/"+w}}}if(!g[k]){for(var U=0,R=l.length;U0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}r.search=e.search;r.query=e.query;if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.href=r.format();return r}if(!x.length){r.pathname=null;if(r.search){r.path="/"+r.search}else{r.path=null}r.href=r.format();return r}var A=x.slice(-1)[0];var U=(r.host||e.host||x.length>1)&&(A==="."||A==="..")||A==="";var T=0;for(var I=x.length;I>=0;I--){A=x[I];if(A==="."){x.splice(I,1)}else if(A===".."){x.splice(I,1);T++}else if(T){x.splice(I,1);T--}}if(!w&&!S){for(;T--;T){x.unshift("..")}}if(w&&x[0]!==""&&(!x[0]||x[0].charAt(0)!=="/")){x.unshift("")}if(U&&x.join("/").substr(-1)!=="/"){x.push("")}var L=x[0]===""||x[0]&&x[0].charAt(0)==="/";if(k){r.hostname=r.host=L?"":x.length?x.shift():"";var E=r.host&&r.host.indexOf("@")>0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}w=w||r.host&&x.length;if(w&&!L){x.unshift("")}if(!x.length){r.pathname=null;r.path=null}else{r.pathname=x.join("/")}if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.auth=e.auth||r.auth;r.slashes=r.slashes||e.slashes;r.href=r.format();return r};s.prototype.parseHost=function(){var e=this.host;var t=a.exec(e);if(t){t=t[0];if(t!==":"){this.port=t.substr(1)}e=e.substr(0,e.length-t.length)}if(e)this.hostname=e}},{"./util":121,punycode:85,querystring:88}],121:[function(e,t,r){"use strict";t.exports={isString:function(e){return typeof e==="string"},isObject:function(e){return typeof e==="object"&&e!==null},isNull:function(e){return e===null},isNullOrUndefined:function(e){return e==null}}},{}],122:[function(e,t,r){(function(r){var n=e("bencode");var i=e("bitfield");var s=e("events").EventEmitter;var o=e("inherits");var a=e("simple-sha1");var f=1e7;var u=1e3;var h=16*1024;t.exports=function(e){o(t,s);function t(t){s.call(this);this._wire=t;this._metadataComplete=false;this._metadataSize=null;this._remainingRejects=null;this._fetching=false;this._bitfield=new i(0,{grow:u});if(r.isBuffer(e)){this.setMetadata(e)}}t.prototype.name="ut_metadata";t.prototype.onHandshake=function(e,t,r){this._infoHash=e;this._infoHashHex=e.toString("hex")};t.prototype.onExtendedHandshake=function(e){if(!e.m||!e.m.ut_metadata){return this.emit("warning",new Error("Peer does not support ut_metadata"))}if(!e.metadata_size){return this.emit("warning",new Error("Peer does not have metadata"))}if(e.metadata_size>f){return this.emit("warning",new Error("Peer gave maliciously large metadata size"))}this._metadataSize=e.metadata_size;this._numPieces=Math.ceil(this._metadataSize/h);this._remainingRejects=this._numPieces*2;if(this._fetching){this._requestPieces()}};t.prototype.onMessage=function(e){var t,r;try{var i=e.toString();var s=i.indexOf("ee")+2;t=n.decode(i.substring(0,s));r=e.slice(s)}catch(o){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,r,t.total_size);break;case 2:this._onReject(t.piece);break}};t.prototype.fetch=function(){if(this._metadataComplete){return}this._fetching=true;if(this._metadataSize){this._requestPieces()}};t.prototype.cancel=function(){this._fetching=false};t.prototype.setMetadata=function(e){if(this._metadataComplete)return true;try{var t=n.decode(e).info;if(t){e=n.encode(t)}}catch(r){}if(this._infoHashHex&&this._infoHashHex!==a.sync(e)){return false}this.cancel();this.metadata=e;this._metadataComplete=true;this._metadataSize=this.metadata.length;this._wire.extendedHandshake.metadata_size=this._metadataSize;this.emit("metadata",n.encode({info:n.decode(this.metadata)}));return true};t.prototype._send=function(e,t){var i=n.encode(e);if(r.isBuffer(t)){i=r.concat([i,t])}this._wire.extended("ut_metadata",i)};t.prototype._request=function(e){this._send({msg_type:0,piece:e})};t.prototype._data=function(e,t,r){var n={msg_type:1,piece:e};if(typeof r==="number"){n.total_size=r}this._send(n,t)};t.prototype._reject=function(e){this._send({msg_type:2,piece:e})};t.prototype._onRequest=function(e){if(!this._metadataComplete){this._reject(e);return}var t=e*h;var r=t+h;if(r>this._metadataSize){r=this._metadataSize}var n=this.metadata.slice(t,r);this._data(e,n,this._metadataSize)};t.prototype._onData=function(e,t,r){if(t.length>h){return}t.copy(this.metadata,e*h);this._bitfield.set(e);this._checkDone()};t.prototype._onReject=function(e){if(this._remainingRejects>0&&this._fetching){this._request(e);this._remainingRejects-=1}else{this.emit("warning",new Error('Peer sent "reject" too much'))}};t.prototype._requestPieces=function(){this.metadata=new r(this._metadataSize);for(var e=0;e0){this._requestPieces()}else{this.emit("warning",new Error("Peer sent invalid metadata"))}};return t}}).call(this,e("buffer").Buffer)},{bencode:11,bitfield:15,buffer:36,events:47,inherits:55,"simple-sha1":105}],123:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(n("noDeprecation")){return e}var r=false;function i(){if(!r){if(n("throwDeprecation")){throw new Error(t)}else if(n("traceDeprecation")){console.trace(t)}else{console.warn(t)}r=true}return e.apply(this,arguments)}return i}function n(t){try{if(!e.localStorage)return false}catch(r){return false}var n=e.localStorage[t];if(null==n)return false;return String(n).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],124:[function(e,t,r){var n=e("debug")("videostream");var i=e("mp4box");var s=.01;var o=60;t.exports=function(e,t,r){r=r||{};var f=r.debugTrack||-1;var u=[];function h(){t.addEventListener("waiting",S);t.addEventListener("timeupdate",E)}h();var l=false;function c(e){l=true;t.removeEventListener("waiting",S);t.removeEventListener("timeupdate",E);if(p.readyState==="open")p.endOfStream(e)}function d(e){var r=e.buffer.buffered;var i=t.currentTime;var a=-1;for(var f=0;fi){break}else if(a>=0||i<=h){a=h}}var l=a-i;if(l<0)l=0;n("Buffer length: %f",l);return l<=o}var p=new MediaSource;p.addEventListener("sourceopen",function(){w(0)});t.src=window.URL.createObjectURL(p);var m=new i;m.onError=function(e){n("MP4Box error: %s",e.message);if(b){b()}if(p.readyState==="open"){c("decode")}};var v=false;var g={};m.onReady=function(e){n("MP4 info: %o",e);e.tracks.forEach(function(e){var t;if(e.video){t="video/mp4"}else if(e.audio){t="audio/mp4"}else{return}t+='; codecs="'+e.codec+'"';if(MediaSource.isTypeSupported(t)){var r=p.addSourceBuffer(t);var n={buffer:r,arrayBuffers:[],meta:e,ended:false};r.addEventListener("updateend",A.bind(null,n));m.setSegmentOptions(e.id,null,{nbSamples:e.video?1:100});g[e.id]=n}});if(Object.keys(g).length===0){c("decode");return}var t=m.initializeSegmentation();t.forEach(function(e){k(g[e.id],e.buffer);if(e.id===f){a("init-track-"+f+".mp4",[e.buffer]);u.push(e.buffer)}});v=true};m.onSegment=function(e,t,r,n){var i=g[e];k(i,r,n===i.meta.nb_samples);if(e===f&&u){u.push(r);if(n>1e3){a("track-"+f+".mp4",u);u=null}}};var _;var y=null;var b=null;function w(t){if(t===e.length){m.flush();return}if(y&&t===_){var r=y;setTimeout(function(){if(y===r)y.resume()});return}if(y){y.destroy();b()}_=t;var i={start:_,end:e.length-1};y=e.createReadStream(i);function s(e){y.pause();var t=e.toArrayBuffer();t.fileStart=_;_+=t.byteLength;var r;try{r=m.appendBuffer(t)}catch(i){n("MP4Box threw exception: %s",i.message);if(p.readyState==="open"){c("decode")}y.destroy();b();return}w(r)}y.on("data",s);function o(){b();w(_)}y.on("end",o);function a(e){n("Stream error: %s",e.message);if(p.readyState==="open"){c("network")}}y.on("error",a);b=function(){y.removeListener("data",s);y.removeListener("end",o);y.removeListener("error",a);y=null;b=null}}function S(){if(v){x(t.currentTime)}}function x(e){if(l)h();var t=m.seek(e,true);n("Seeking to time: %d",e);n("Seeked file offset: %d",t.offset);w(t.offset)}function k(e,t,r){e.arrayBuffers.push({buffer:t,ended:r||false});A(e)}function E(){Object.keys(g).forEach(function(e){var t=g[e];if(t.blocked){A(t)}})}function A(e){if(e.buffer.updating)return;e.blocked=!d(e);if(e.blocked)return;if(e.arrayBuffers.length===0)return;var t=e.arrayBuffers.shift();var r=false;try{e.buffer.appendBuffer(t.buffer);e.ended=t.ended;r=true}catch(i){n("SourceBuffer error: %s",i.message);c("decode");return}if(r){U()}}function U(){if(p.readyState!=="open"){return}var e=Object.keys(g).every(function(e){var t=g[e];return t.ended&&!t.buffer.updating});if(e){c()}}};function a(e,t){var r=new Blob(t);var n=URL.createObjectURL(r);var i=document.createElement("a");i.setAttribute("href",n);i.setAttribute("download",e);i.click()}},{debug:42,mp4box:70}],125:[function(e,t,r){t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=="function")throw new TypeError("need wrapper function");Object.keys(e).forEach(function(t){r[t]=e[t]});return r;function r(){var t=new Array(arguments.length);for(var r=0;r0)return new Array(e+(/\./.test(t)?2:1)).join(r)+t;return t+""}},{}],129:[function(e,t,r){t.exports={name:"webtorrent",description:"Streaming torrent client",version:"0.63.1",author:{name:"Feross Aboukhadijeh",email:"feross@feross.org",url:"http://feross.org/"},bin:{webtorrent:"./bin/cmd.js"},browser:{"./lib/server.js":false,"bittorrent-dht/client":false,"fs-chunk-store":"memory-chunk-store","load-ip-set":false,ut_pex:false},bugs:{url:"https://github.com/feross/webtorrent/issues"},dependencies:{"addr-to-ip-port":"^1.0.1",bitfield:"^1.0.2","bittorrent-dht":"^4.0.4","bittorrent-swarm":"^5.0.0","chunk-store-stream":"^2.0.0",clivas:"^0.2.0","create-torrent":"^3.4.0","cross-spawn-async":"^2.0.0",debug:"^2.1.0","end-of-stream":"^1.0.0",executable:"^2.1.0","fs-chunk-store":"^1.3.4",hat:"0.0.3","immediate-chunk-store":"^1.0.7",inherits:"^2.0.1",inquirer:"^0.11.0","load-ip-set":"^1.0.3",mediasource:"^1.0.0","memory-chunk-store":"^1.2.0",mime:"^1.2.11",minimist:"^1.1.0",moment:"^2.8.3",multistream:"^2.0.2","network-address":"^1.0.0","parse-torrent":"^5.1.0","path-exists":"^2.1.0","pretty-bytes":"^2.0.1",pump:"^1.0.0","random-iterate":"^1.0.1","range-parser":"^1.0.2","re-emitter":"^1.0.0","run-parallel":"^1.0.0","simple-sha1":"^2.0.0",speedometer:"^1.0.0",thunky:"^0.1.0","torrent-discovery":"^3.0.0","torrent-piece":"^1.0.0",uniq:"^1.0.1",ut_metadata:"^2.1.0",ut_pex:"^1.0.1",videostream:"^1.1.4","windows-no-runnable":"0.0.6",xtend:"^4.0.0","zero-fill":"^2.2.0"},devDependencies:{"bittorrent-tracker":"^6.0.0",brfs:"^1.2.0",browserify:"^12.0.1",finalhandler:"^0.4.0","run-auto":"^1.0.0","serve-static":"^1.9.3","simple-get":"^1.0.0",standard:"^5.1.0",tape:"^4.0.0","uglify-js":"^2.4.15",zelda:"^2.0.0",zuul:"^3.0.0"},homepage:"http://webtorrent.io",keywords:["torrent","bittorrent","bittorrent client","streaming","download","webrtc","webrtc data","webtorrent","mad science"],license:"MIT",main:"index.js",optionalDependencies:{"airplay-js":"^0.2.3",chromecasts:"^1.5.3",nodebmc:"0.0.5"},repository:{type:"git",url:"git://github.com/feross/webtorrent.git"},scripts:{build:"browserify -s WebTorrent -e ./ | uglifyjs -m > webtorrent.min.js","build-debug":"browserify -s WebTorrent -e ./ > webtorrent.debug.js",size:"npm run build && cat webtorrent.min.js | gzip | wc -c",test:"standard && node ./bin/test.js","test-browser":"zuul -- test/basic.js","test-browser-local":"zuul --local -- test/basic.js","test-node":"tape test/*.js"}}},{}],130:[function(e,t,r){(function(r,n,i){t.exports=w;var s=e("create-torrent");var o=e("debug")("webtorrent");var a=e("bittorrent-dht/client");var f=e("events").EventEmitter;var u=e("xtend");var h=e("hat");var l=e("inherits");var c=e("load-ip-set");var d=e("run-parallel");var p=e("parse-torrent");var m=e("speedometer");var v=e("zero-fill");var g=e("path");var _=e("./lib/torrent");l(w,f);var y=e("./package.json").version;var b=y.match(/([0-9]+)/g).slice(0,2).map(v(2)).join("");function w(e){var t=this;if(!(t instanceof w))return new w(e);if(!e)e={};f.call(t);if(!o.enabled)t.setMaxListeners(0);t.destroyed=false;t.torrentPort=e.torrentPort||0;t.tracker=e.tracker!==undefined?e.tracker:true;t._rtcConfig=e.rtcConfig;t._wrtc=e.wrtc||n.WRTC;t.torrents=[];t.downloadSpeed=m();t.uploadSpeed=m();t.peerId=e.peerId===undefined?new i("-WW"+b+"-"+h(48),"utf8"):typeof e.peerId==="string"?new i(e.peerId,"hex"):e.peerId;t.peerIdHex=t.peerId.toString("hex");t.nodeId=e.nodeId===undefined?new i(h(160),"hex"):typeof e.nodeId==="string"?new i(e.nodeId,"hex"):e.nodeId;t.nodeIdHex=t.nodeId.toString("hex");if(e.dht!==false&&typeof a==="function"){t.dht=new a(u({nodeId:t.nodeId},e.dht));t.dht.listen(e.dhtPort)}o("new webtorrent (peerId %s, nodeId %s)",t.peerIdHex,t.nodeIdHex);if(typeof c==="function"){c(e.blocklist,{headers:{"user-agent":"WebTorrent/"+y+" (http://webtorrent.io)"}},function(e,r){if(e)return t.error("Failed to load blocklist: "+e.message);t.blocked=r;s()})}else r.nextTick(s);function s(){if(t.destroyed)return;t.ready=true;t.emit("ready")}}Object.defineProperty(w.prototype,"ratio",{get:function(){var e=this;var t=e.torrents.reduce(function(e,t){return e+t.uploaded},0);var r=e.torrents.reduce(function(e,t){return e+t.downloaded},0)||1;return t/r}});w.prototype.get=function(e){var t=this;if(e instanceof _)return e;var r;try{r=p(e)}catch(n){}if(!r)return null;if(!r.infoHash)throw new Error("Invalid torrent identifier");for(var i=0,s=t.torrents.length;i Date: Wed, 2 Dec 2015 16:54:04 -0500 Subject: [PATCH 14/44] Update README (Fix #495) The path to file/folder only works in Node.js --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a277900c70..0f597a243a 100644 --- a/README.md +++ b/README.md @@ -273,7 +273,7 @@ Start seeding a new torrent. `input` can be any of the following: -- path to the file or folder on filesystem (string) +- path to the file or folder on filesystem (string) (Node.js only) - W3C [File](https://developer.mozilla.org/en-US/docs/Web/API/File) object (from an `` or drag and drop) - W3C [FileList](https://developer.mozilla.org/en-US/docs/Web/API/FileList) object (basically an array of `File` objects) - Node [Buffer](http://nodejs.org/api/buffer.html) object (works in [the browser](https://www.npmjs.org/package/buffer)) From c06529d0e3837f45a58354f6d9e005adabed654e Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 14:32:22 -0800 Subject: [PATCH 15/44] fix tests --- test/basic-node.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/basic-node.js b/test/basic-node.js index 70e96163ce..cff40ebd86 100644 --- a/test/basic-node.js +++ b/test/basic-node.js @@ -114,7 +114,10 @@ test('client.seed: filesystem path to folder with multiple files, string', funct // match what transmission generated, since we use // a different algo for picking piece length - private: false // also force `private: false` to match transmission + private: false, // also force `private: false` to match transmission + announce: [ + 'udp://tracker.webtorrent.io:80' + ] } var client = new WebTorrent({ dht: false, tracker: false }) @@ -124,7 +127,7 @@ test('client.seed: filesystem path to folder with multiple files, string', funct client.seed(numbersPath, opts, function (torrent) { t.equal(torrent.infoHash, '80562f38656b385ea78959010e51a2cc9db41ea0') - t.equal(torrent.magnetURI, 'magnet:?xt=urn:btih:80562f38656b385ea78959010e51a2cc9db41ea0&dn=numbers&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.internetwarriors.net%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=wss%3A%2F%2Ftracker.webtorrent.io') + t.equal(torrent.magnetURI, 'magnet:?xt=urn:btih:80562f38656b385ea78959010e51a2cc9db41ea0&dn=numbers&tr=udp%3A%2F%2Ftracker.webtorrent.io%3A80') client.destroy() }) }) From 6fee6b29b4edd2af8c218b8c6398a2eec50be092 Mon Sep 17 00:00:00 2001 From: "Anders D. Johnson" Date: Wed, 2 Dec 2015 20:30:53 -0600 Subject: [PATCH 16/44] Capitalize "p2p" in README. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f597a243a..792daa29cf 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ on your page to start fetching files over WebRTC using the BitTorrent protocol, `require('webtorrent')` with [browserify](http://browserify.org/). See [demo apps ](#webtorrent-in-production) and [code examples](#usage) below. -To make BitTorrent work over WebRTC (which is the only p2p transport that works on the +To make BitTorrent work over WebRTC (which is the only P2P transport that works on the web) we made some protocol changes. Therefore, a browser-based WebTorrent client or **"web peer"** can only connect to other clients that support WebTorrent/WebRTC. From eaf085b36b5a5ac78369210fc39ba272d033d829 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 22:38:25 -0800 Subject: [PATCH 17/44] Standardize hash variable names (fix #374) --- index.js | 41 +++++++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/index.js b/index.js index 9e783bee61..dbf91f0e99 100644 --- a/index.js +++ b/index.js @@ -18,16 +18,28 @@ var Torrent = require('./lib/torrent') inherits(WebTorrent, EventEmitter) +/** + * WebTorrent version. + */ var VERSION = require('./package.json').version /** - * BitTorrent client version string (used in peer ID). - * Generated from package.json major and minor version. For example: + * Version number in Azureus-style. Generated from major and minor semver version. + * For example: * '0.16.1' -> '0016' * '1.2.5' -> '0102' */ var VERSION_STR = VERSION.match(/([0-9]+)/g).slice(0, 2).map(zeroFill(2)).join('') +/** + * Version prefix string (used in peer ID). WebTorrent uses the Azureus-style + * encoding: '-', two characters for client id ('WW'), four ascii digits for version + * number, '-', followed by random numbers. + * For example: + * '-WW0102-'... + */ +var VERSION_PREFIX = '-WW' + VERSION_STR + '-' + /** * WebTorrent Client * @param {Object} opts @@ -35,8 +47,9 @@ var VERSION_STR = VERSION.match(/([0-9]+)/g).slice(0, 2).map(zeroFill(2)).join(' function WebTorrent (opts) { var self = this if (!(self instanceof WebTorrent)) return new WebTorrent(opts) - if (!opts) opts = {} EventEmitter.call(self) + + if (!opts) opts = {} if (!debug.enabled) self.setMaxListeners(0) self.destroyed = false @@ -51,19 +64,15 @@ function WebTorrent (opts) { self.downloadSpeed = speedometer() self.uploadSpeed = speedometer() - self.peerId = opts.peerId === undefined - ? new Buffer('-WW' + VERSION_STR + '-' + hat(48), 'utf8') - : typeof opts.peerId === 'string' - ? new Buffer(opts.peerId, 'hex') - : opts.peerId - self.peerIdHex = self.peerId.toString('hex') + self.peerId = typeof opts.peerId === 'string' + ? opts.peerId + : (opts.peerId || new Buffer(VERSION_PREFIX + hat(48))).toString('hex') + self.peerIdBuffer = new Buffer(self.peerId, 'hex') - self.nodeId = opts.nodeId === undefined - ? new Buffer(hat(160), 'hex') - : typeof opts.nodeId === 'string' - ? new Buffer(opts.nodeId, 'hex') - : opts.nodeId - self.nodeIdHex = self.nodeId.toString('hex') + self.nodeId = typeof opts.nodeId === 'string' + ? opts.nodeId + : (opts.nodeId && opts.nodeId.toString('hex')) || hat(160) + self.nodeIdBuffer = new Buffer(self.nodeId, 'hex') if (opts.dht !== false && typeof DHT === 'function' /* browser exclude */) { // use a single DHT instance for all torrents, so the routing table can be reused @@ -71,7 +80,7 @@ function WebTorrent (opts) { self.dht.listen(opts.dhtPort) } - debug('new webtorrent (peerId %s, nodeId %s)', self.peerIdHex, self.nodeIdHex) + debug('new webtorrent (peerId %s, nodeId %s)', self.peerId, self.nodeId) if (typeof loadIPSet === 'function') { loadIPSet(opts.blocklist, { From b4f2040bbf6968c28bb20367ed895310b8e04fa3 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 22:47:34 -0800 Subject: [PATCH 18/44] browser: exclude two unused packages --- lib/torrent.js | 8 +++++--- package.json | 2 ++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/torrent.js b/lib/torrent.js index 64d38ffea7..6d50b5ca66 100644 --- a/lib/torrent.js +++ b/lib/torrent.js @@ -12,11 +12,11 @@ var FSChunkStore = require('fs-chunk-store') // browser: `memory-chunk-store` var ImmediateChunkStore = require('immediate-chunk-store') var inherits = require('inherits') var MultiStream = require('multistream') -var os = require('os') +var os = require('os') // browser exclude var parallel = require('run-parallel') var parseTorrent = require('parse-torrent') var path = require('path') -var pathExists = require('path-exists') +var pathExists = require('path-exists') // browser exclude var Piece = require('torrent-piece') var pump = require('pump') var randomIterate = require('random-iterate') @@ -42,7 +42,9 @@ var PIPELINE_MAX_DURATION = 1 var RECHOKE_INTERVAL = 10000 // 10 seconds var RECHOKE_OPTIMISTIC_DURATION = 2 // 30 seconds -var TMP = path.join(pathExists.sync('/tmp') ? '/tmp' : os.tmpDir(), 'webtorrent') +var TMP = typeof pathExists.sync === 'function' + ? path.join(pathExists.sync('/tmp') ? '/tmp' : os.tmpDir(), 'webtorrent') + : '/tmp/webtorrent' inherits(Torrent, EventEmitter) diff --git a/package.json b/package.json index bc060b905c..02b9b5d419 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,8 @@ "bittorrent-dht/client": false, "fs-chunk-store": "memory-chunk-store", "load-ip-set": false, + "os": false, + "path-exists": false, "ut_pex": false }, "bugs": { From 8e88e4a514d34df0d9f5aa38e6d92383ee4b9ad6 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 22:49:43 -0800 Subject: [PATCH 19/44] torrent-discovery@4 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index bc060b905c..f713e67d4f 100644 --- a/package.json +++ b/package.json @@ -56,7 +56,7 @@ "simple-sha1": "^2.0.0", "speedometer": "^1.0.0", "thunky": "^0.1.0", - "torrent-discovery": "^3.0.0", + "torrent-discovery": "^4.0.0", "torrent-piece": "^1.0.0", "uniq": "^1.0.1", "ut_metadata": "^2.1.0", From 3c3a06a145fa4b2d0cd3f39fd277c305e6c445bc Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 22:54:05 -0800 Subject: [PATCH 20/44] bittorrent-dht@5 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index f713e67d4f..3413984cc2 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "dependencies": { "addr-to-ip-port": "^1.0.1", "bitfield": "^1.0.2", - "bittorrent-dht": "^4.0.4", + "bittorrent-dht": "^5.0.0", "bittorrent-swarm": "^5.0.0", "chunk-store-stream": "^2.0.0", "clivas": "^0.2.0", From 0e513474f721ade53c7e30fb0277fd822fbe7a4a Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 22:59:06 -0800 Subject: [PATCH 21/44] bittorrent-swarm@6 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 3413984cc2..8cc8ffd0dc 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "addr-to-ip-port": "^1.0.1", "bitfield": "^1.0.2", "bittorrent-dht": "^5.0.0", - "bittorrent-swarm": "^5.0.0", + "bittorrent-swarm": "^6.0.0", "chunk-store-stream": "^2.0.0", "clivas": "^0.2.0", "create-torrent": "^3.4.0", From f0570b32596b9ca9840a56df03b87ead72ef12af Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Wed, 2 Dec 2015 23:02:40 -0800 Subject: [PATCH 22/44] ut_metadata@3 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8cc8ffd0dc..7d0c23de71 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "torrent-discovery": "^4.0.0", "torrent-piece": "^1.0.0", "uniq": "^1.0.1", - "ut_metadata": "^2.1.0", + "ut_metadata": "^3.0.1", "ut_pex": "^1.0.1", "videostream": "^1.1.4", "windows-no-runnable": "0.0.6", From 1bd5fa676a8480cdbe0d11ed5661a49a63288fb9 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Thu, 3 Dec 2015 19:53:42 -0800 Subject: [PATCH 23/44] self -> this --- lib/torrent.js | 53 +++++++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/lib/torrent.js b/lib/torrent.js index 6d50b5ca66..e61b59c472 100644 --- a/lib/torrent.js +++ b/lib/torrent.js @@ -53,44 +53,43 @@ inherits(Torrent, EventEmitter) * @param {Object} opts */ function Torrent (torrentId, opts) { - var self = this - EventEmitter.call(self) - if (!debug.enabled) self.setMaxListeners(0) + EventEmitter.call(this) + if (!debug.enabled) this.setMaxListeners(0) debug('new torrent') - self.client = opts.client + this.client = opts.client - self.announce = opts.announce - self.urlList = opts.urlList + this.announce = opts.announce + this.urlList = opts.urlList - self.path = opts.path - self._store = opts.store || FSChunkStore + this.path = opts.path + this._store = opts.store || FSChunkStore - self.strategy = opts.strategy || 'sequential' + this.strategy = opts.strategy || 'sequential' - self._rechokeNumSlots = (opts.uploads === false || opts.uploads === 0) + this._rechokeNumSlots = (opts.uploads === false || opts.uploads === 0) ? 0 : (+opts.uploads || 10) - self._rechokeOptimisticWire = null - self._rechokeOptimisticTime = 0 - self._rechokeIntervalId = null - - self.ready = false - self.destroyed = false - self.metadata = null - self.store = null - self.numBlockedPeers = 0 - self.files = null - self.done = false - - self._amInterested = false - self._selections = [] - self._critical = [] + this._rechokeOptimisticWire = null + this._rechokeOptimisticTime = 0 + this._rechokeIntervalId = null + + this.ready = false + this.destroyed = false + this.metadata = null + this.store = null + this.numBlockedPeers = 0 + this.files = null + this.done = false + + this._amInterested = false + this._selections = [] + this._critical = [] // for cleanup - self._servers = [] + this._servers = [] - if (torrentId) self._onTorrentId(torrentId) + if (torrentId) this._onTorrentId(torrentId) } // Time remaining (in milliseconds) From 87ff0039b99f44f290838187164756eaed48c522 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Thu, 3 Dec 2015 19:53:50 -0800 Subject: [PATCH 24/44] code style --- index.js | 4 ++-- lib/torrent.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index dbf91f0e99..9a0c46a451 100644 --- a/index.js +++ b/index.js @@ -154,7 +154,7 @@ WebTorrent.prototype.download = function (torrentId, opts, ontorrent) { if (typeof opts === 'function') return self.add(torrentId, null, opts) debug('add') if (!opts) opts = {} - else opts = extend({}, opts) + else opts = extend(opts) opts.client = self @@ -202,7 +202,7 @@ WebTorrent.prototype.seed = function (input, opts, onseed) { if (typeof opts === 'function') return self.seed(input, null, opts) debug('seed') if (!opts) opts = {} - else opts = extend({}, opts) + else opts = extend(opts) // When seeding from filesystem, initialize store from that path (avoids a copy) if (typeof input === 'string') opts.path = path.dirname(input) diff --git a/lib/torrent.js b/lib/torrent.js index e61b59c472..fc6fa19962 100644 --- a/lib/torrent.js +++ b/lib/torrent.js @@ -7,7 +7,7 @@ var createTorrent = require('create-torrent') var debug = require('debug')('webtorrent:torrent') var Discovery = require('torrent-discovery') var EventEmitter = require('events').EventEmitter -var extend = require('xtend/mutable') +var extendMutable = require('xtend/mutable') var FSChunkStore = require('fs-chunk-store') // browser: `memory-chunk-store` var ImmediateChunkStore = require('immediate-chunk-store') var inherits = require('inherits') @@ -252,7 +252,7 @@ Torrent.prototype._processParsedTorrent = function (parsedTorrent) { uniq(parsedTorrent.announce) - extend(this, parsedTorrent) + extendMutable(this, parsedTorrent) this.magnetURI = parseTorrent.toMagnetURI(parsedTorrent) this.torrentFile = parseTorrent.toTorrentFile(parsedTorrent) From 3f148aa2ff6e791432b235f9b0a20ad8196f3efd Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Thu, 3 Dec 2015 20:14:39 -0800 Subject: [PATCH 25/44] remove debug statement --- index.js | 1 - 1 file changed, 1 deletion(-) diff --git a/index.js b/index.js index 9a0c46a451..72d6f7ab40 100644 --- a/index.js +++ b/index.js @@ -161,7 +161,6 @@ WebTorrent.prototype.download = function (torrentId, opts, ontorrent) { var torrent = self.get(torrentId) function _ontorrent () { - debug('on torrent %s', torrent.infoHash) if (typeof ontorrent === 'function') ontorrent(torrent) } From 55266e16228d83a81d14bde004e959d3f2aa8753 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Thu, 3 Dec 2015 20:17:06 -0800 Subject: [PATCH 26/44] dedupe urlList Fixes https://github.com/feross/instant.io/issues/92 --- lib/torrent.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/torrent.js b/lib/torrent.js index fc6fa19962..ba13d8e604 100644 --- a/lib/torrent.js +++ b/lib/torrent.js @@ -251,6 +251,7 @@ Torrent.prototype._processParsedTorrent = function (parsedTorrent) { } uniq(parsedTorrent.announce) + uniq(parsedTorrent.urlList) extendMutable(this, parsedTorrent) From 2ff3820f7b8ec57ea02ad8a4242ec4c4bc989f52 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Thu, 3 Dec 2015 20:20:47 -0800 Subject: [PATCH 27/44] 0.63.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index a2b8584615..a4d2ea6bb3 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "webtorrent", "description": "Streaming torrent client", - "version": "0.63.1", + "version": "0.63.2", "author": { "name": "Feross Aboukhadijeh", "email": "feross@feross.org", From 074836e955e7aed7bce9a931233029d2dedda82f Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Thu, 3 Dec 2015 20:21:07 -0800 Subject: [PATCH 28/44] build --- webtorrent.min.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/webtorrent.min.js b/webtorrent.min.js index 8c970488c9..fd4711d262 100644 --- a/webtorrent.min.js +++ b/webtorrent.min.js @@ -1,10 +1,10 @@ -(function(e){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=e()}else if(typeof define==="function"&&define.amd){define([],e)}else{var t;if(typeof window!=="undefined"){t=window}else if(typeof global!=="undefined"){t=global}else if(typeof self!=="undefined"){t=self}else{t=this}t.WebTorrent=e()}})(function(){var e,t,r;return function n(e,t,r){function i(o,a){if(!t[o]){if(!e[o]){var f=typeof require=="function"&&require;if(!a&&f)return f(o,!0);if(s)return s(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var h=t[o]={exports:{}};e[o][0].call(h.exports,function(t){var r=e[o][1][t];return i(r?r:t)},h,h.exports,n,e,t,r)}return t[o].exports}var s=typeof require=="function"&&require;for(var o=0;o=0)y();else if(l.indexOf(g)>=0)w();else if(c.indexOf(g)>=0)S();else if(d.indexOf(g)>=0)x();else v(r,new Error('Unsupported file type "'+g+'": Cannot append to DOM'));function y(){if(!p){return v(r,new Error("Video/audio streaming is not supported in your browser. You can still share "+"or download "+e.name+" (once it's fully downloaded). Use Chrome for "+"MediaSource support."))}var s=f.indexOf(g)>=0?"video":"audio";if(a.indexOf(g)>=0)h();else l();function h(){n("Use `videostream` package for "+e.name);y();u.addEventListener("error",d);u.addEventListener("playing",b);o(e,u)}function l(){n("Use MediaSource API for "+e.name);y();u.addEventListener("error",m);u.addEventListener("playing",b);e.createReadStream().pipe(new i(u,{extname:g}));if(_)u.currentTime=_}function c(){n("Use Blob URL for "+e.name);y();u.addEventListener("error",k);u.addEventListener("playing",b);e.getBlobURL(function(e,t){if(e)return k(e);u.src=t;if(_)u.currentTime=_})}function d(e){n("videostream error: fallback to MediaSource API: %o",e.message||e);u.removeEventListener("error",d);u.removeEventListener("playing",b);l()}function m(e){n("MediaSource API error: fallback to Blob URL: %o",e.message||e);u.removeEventListener("error",m);u.removeEventListener("playing",b);c()}function y(e){if(!u){u=document.createElement(s);u.controls=true;u.autoplay=true;u.play();u.addEventListener("progress",function(){_=u.currentTime});t.appendChild(u)}}}function b(){u.removeEventListener("playing",b);r(null,u)}function w(){u=document.createElement("audio");u.controls=true;u.autoplay=true;t.appendChild(u);e.getBlobURL(function(e,t){if(e)return k(e);u.addEventListener("error",k);u.addEventListener("playing",b);u.src=t;u.play()})}function S(){e.getBlobURL(function(n,i){if(n)return k(n);u=document.createElement("img");u.src=i;u.alt=e.name;t.appendChild(u);r(null,u)})}function x(){e.getBlobURL(function(e,n){if(e)return k(e);u=document.createElement("iframe");u.src=n;if(g!==".pdf")u.sandbox="allow-forms allow-scripts";t.appendChild(u);r(null,u)})}function k(t){if(u)u.remove();t.message='Error appending file "'+e.name+'" to DOM: '+t.message;n(t.message);if(r)r(t)}};function m(){}function v(e,t,n){r.nextTick(function(){if(e)e(t,n)})}}).call(this,e("_process"))},{_process:83,debug:42,mediasource:63,path:77,videostream:124}],2:[function(e,t,r){t.exports=o;var n=e("debug")("webtorrent:file-stream");var i=e("inherits");var s=e("stream");i(o,s.Readable);function o(e,t){s.Readable.call(this,t);this.destroyed=false;this._torrent=e._torrent;var r=t&&t.start||0;var n=t&&t.end||e.length-1;var i=e._torrent.pieceLength;this._startPiece=(r+e.offset)/i|0;this._endPiece=(n+e.offset)/i|0;this._piece=this._startPiece;this._offset=r+e.offset-this._startPiece*i;this._missing=n-r+1;this._reading=false;this._notifying=false;this._criticalLength=Math.min(1024*1024/i|0,2)}o.prototype._read=function(){if(this._reading)return;this._reading=true;this._notify()};o.prototype._notify=function(){var e=this;if(!e._reading||e._missing===0)return;if(!e._torrent.bitfield.get(e._piece)){return e._torrent.critical(e._piece,e._piece+e._criticalLength)}if(e._notifying)return;e._notifying=true;var t=e._piece;e._torrent.store.get(t,function(r,i){e._notifying=false;if(e.destroyed)return;if(r)return e.destroy(r);n("read %s (length %s) (err %s)",t,i.length,r&&r.message);if(e._offset){i=i.slice(e._offset);e._offset=0}if(e._missing0){return r[Math.random()*r.length|0]}else{return-1}}},{}],6:[function(e,t,r){(function(r,n){t.exports=H;var i=e("addr-to-ip-port");var s=e("bitfield");var o=e("chunk-store-stream/write");var a=e("create-torrent");var f=e("debug")("webtorrent:torrent");var u=e("torrent-discovery");var h=e("events").EventEmitter;var l=e("xtend/mutable");var c=e("fs-chunk-store");var d=e("immediate-chunk-store");var p=e("inherits");var m=e("multistream");var v=e("os");var g=e("run-parallel");var _=e("parse-torrent");var y=e("path");var b=e("path-exists");var w=e("torrent-piece");var S=e("pump");var x=e("random-iterate");var k=e("re-emitter");var E=e("simple-sha1");var A=e("bittorrent-swarm");var U=e("uniq");var T=e("ut_metadata");var I=e("ut_pex");var L=e("./file");var B=e("./rarity-map");var C=e("./server");var R=128*1024;var P=3e4;var F=5e3;var O=3*w.BLOCK_LENGTH;var M=.5;var D=1;var N=1e4;var z=2;var j=y.join(b.sync("/tmp")?"/tmp":v.tmpDir(),"webtorrent");p(H,h);function H(e,t){var r=this;h.call(r);if(!f.enabled)r.setMaxListeners(0);f("new torrent");r.client=t.client;r.announce=t.announce;r.urlList=t.urlList;r.path=t.path;r._store=t.store||c;r.strategy=t.strategy||"sequential";r._rechokeNumSlots=t.uploads===false||t.uploads===0?0:+t.uploads||10;r._rechokeOptimisticWire=null;r._rechokeOptimisticTime=0;r._rechokeIntervalId=null;r.ready=false;r.destroyed=false;r.metadata=null;r.store=null;r.numBlockedPeers=0;r.files=null;r.done=false;r._amInterested=false;r._selections=[];r._critical=[];r._servers=[];if(e)r._onTorrentId(e)}Object.defineProperty(H.prototype,"timeRemaining",{get:function(){if(this.done)return 0;if(this.swarm.downloadSpeed()===0)return Infinity;else return(this.length-this.downloaded)/this.swarm.downloadSpeed()*1e3}});Object.defineProperty(H.prototype,"downloaded",{get:function(){var e=0;for(var t=0,r=this.pieces.length;tt||e<0||t>=i.pieces.length){throw new Error("invalid selection ",e,":",t)}r=Number(r)||0;f("select %s-%s (priority %s)",e,t,r);i._selections.push({from:e,to:t,offset:0,priority:r,notify:n||W});i._selections.sort(function(e,t){return t.priority-e.priority});i._updateSelections()};H.prototype.deselect=function(e,t,r){var n=this;r=Number(r)||0;f("deselect %s-%s (priority %s)",e,t,r);for(var i=0;i2*(t.swarm.numConns-t.swarm.numPeers)&&e.amInterested){e.destroy()}else{r=setTimeout(n,F);if(r.unref)r.unref()}}var i=0;function s(){if(e.peerPieces.length!==t.pieces.length)return;for(;iR){return e.destroy()}if(t.pieces[r])return;t.store.get(r,{offset:n,length:i},s)});e.bitfield(t.bitfield);e.interested();r=setTimeout(n,F);if(r.unref)r.unref();e.isSeeder=false;s()};H.prototype._updateSelections=function(){var e=this;if(!e.swarm||e.destroyed)return;if(!e.metadata)return e.once("metadata",e._updateSelections.bind(e));r.nextTick(e._gcSelections.bind(e));e._updateInterest();e._update()};H.prototype._gcSelections=function(){var e=this;for(var t=0;t=r)return;var n=q(e,D);f(false)||f(true);function i(t,r,n,i){return function(s){return s>=t&&s<=r&&!(s in n)&&e.peerPieces.get(s)&&(!i||i(s))}}function s(){if(e.requests.length)return;var r=t._selections.length;while(r--){var n=t._selections[r];var s;if(t.strategy==="rarest"){var o=n.from+n.offset;var a=n.to;var f=a-o+1;var u={};var h=0;var l=i(o,a,u);while(h=n.from+n.offset;--s){if(!e.peerPieces.get(s))continue;if(t._request(e,s,false))return}}}}function o(){var r=e.downloadSpeed()||1;if(r>O)return function(){return true};var n=Math.max(1,e.requests.length)*w.BLOCK_LENGTH/r;var i=10;var s=0;return function(e){if(!i||t.bitfield.get(e))return true;var o=t.pieces[e].missing;for(;s0)continue;i--;return false}return true}}function a(e){var r=e;for(var n=e;n=n)return true;var s=o();for(var f=0;f0)e._rechokeOptimisticTime-=1;else e._rechokeOptimisticWire=null;var t=[];e.swarm.wires.forEach(function(r){if(!r.isSeeder&&r!==e._rechokeOptimisticWire){t.push({wire:r,downloadSpeed:r.downloadSpeed(),uploadSpeed:r.uploadSpeed(),salt:Math.random(),isChoked:true})}});t.sort(o);var r=0;var n=0;for(;n=O)continue;if(2*u>n||u>s)continue;o=f;s=u}if(!o)return false;for(a=0;a=o)return false;var a=i.pieces[t];var u=a.reserve();if(u===-1&&n&&i._hotswap(e,t)){u=a.reserve()}if(u===-1)return false;var h=i._reservations[t];if(!h)h=i._reservations[t]=[];var l=h.indexOf(null);if(l===-1)l=h.length;h[l]=e;var c=a.chunkOffset(u);var d=a.chunkLength(u);e.request(t,c,d,function m(r,n){if(!i.ready)return i.once("ready",function(){m(r,n)});if(h[l]===e)h[l]=null;if(a!==i.pieces[t])return p();if(r){f("error getting piece %s (offset: %s length: %s) from %s: %s",t,c,d,e.remoteAddress+":"+e.remotePort,r.message);a.cancel(u);p();return}f("got piece %s (offset: %s length: %s) from %s",t,c,d,e.remoteAddress+":"+e.remotePort);if(!a.set(u,n,e))return p();var s=a.flush();E(s,function(e){if(e===i._hashes[t]){if(!i.pieces[t])return;f("piece verified %s",t);i.pieces[t]=null;i._reservations[t]=null;i.bitfield.set(t,true);i.store.put(t,s);i.swarm.wires.forEach(function(e){e.have(t)});i._checkDone()}else{i.pieces[t]=new w(a.length);i.emit("warning",new Error("Piece "+t+" failed verification"))}p()})});function p(){r.nextTick(function(){i._update()})}return true};H.prototype._checkDone=function(){var e=this;if(e.destroyed)return;e.files.forEach(function(t){if(t.done)return;for(var r=t._startPiece;r<=t._endPiece;++r){if(!e.bitfield.get(r))return}t.done=true;t.emit("done");f("file done: "+t.name)});if(e.files.every(function(e){return e.done})){e.done=true;e.emit("done");f("torrent done: "+e.infoHash);if(e.discovery.tracker)e.discovery.tracker.complete()}e._gcSelections()};H.prototype.load=function(e,t){var r=this;if(!Array.isArray(e))e=[e];if(!t)t=W;var n=new m(e);var i=new o(r.store,r.pieceLength);S(n,i,function(e){if(e)return t(e);r.pieces.forEach(function(e,t){r.pieces[t]=null;r._reservations[t]=null;r.bitfield.set(t,true)});r._checkDone();t(null)})};H.prototype.createServer=function(e){var t=this;if(typeof C!=="function")return;var r=new C(t,e);t._servers.push(r);return r};H.prototype._onError=function(e){var t=this;f("torrent error: %s",e.message||e);t.emit("error",e);t.destroy()};function q(e,t){return Math.ceil(2+t*e.downloadSpeed()/w.BLOCK_LENGTH)}function G(e){return Math.random()*e|0}function W(){}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./file":3,"./rarity-map":5,"./server":34,_process:83,"addr-to-ip-port":7,bitfield:15,"bittorrent-swarm":18,"chunk-store-stream/write":38,"create-torrent":41,debug:42,events:47,"fs-chunk-store":64,"immediate-chunk-store":54,inherits:55,multistream:72,os:74,"parse-torrent":76,path:77,"path-exists":78,pump:84,"random-iterate":89,"re-emitter":90,"run-parallel":101,"simple-sha1":105,"torrent-discovery":116,"torrent-piece":117,uniq:119,ut_metadata:122,ut_pex:34,"xtend/mutable":127}],7:[function(e,t,r){var n=/^\[?([^\]]+)\]?:(\d+)$/;var i={};var s=0;t.exports=function o(e){if(s===1e5)t.exports.reset();if(!i[e]){var r=n.exec(e);if(!r)throw new Error("invalid addr: "+e);i[e]=[r[1],Number(r[2])];s+=1}return i[e]};t.exports.reset=function a(){i={};s=0}},{}],8:[function(e,t,r){"use strict";var n=e("./raw");var i=[];var s=[];var o=n.makeRequestCallFromTimer(a);function a(){if(s.length){throw s.shift()}}t.exports=f;function f(e){var t;if(i.length){t=i.pop()}else{t=new u}t.task=e;n(t)}function u(){this.task=null}u.prototype.call=function(){try{this.task.call()}catch(e){if(f.onerror){f.onerror(e)}else{s.push(e);o()}}finally{this.task=null;i[i.length]=this}}},{"./raw":9}],9:[function(e,t,r){(function(e){"use strict";t.exports=r;function r(e){if(!n.length){s();i=true}n[n.length]=e}var n=[];var i=false;var s;var o=0;var a=1024;function f(){while(oa){for(var t=0,r=n.length-o;t0){throw new Error("Invalid string. Length must be a multiple of 4")}var f=e.length;o="="===e.charAt(f-2)?2:"="===e.charAt(f-1)?1:0;a=new t(e.length*3/4-o);i=o>0?e.length-4:e.length;var u=0;function l(e){a[u++]=e}for(r=0,n=0;r>16);l((s&65280)>>8);l(s&255)}if(o===2){s=h(e.charAt(r))<<2|h(e.charAt(r+1))>>4;l(s&255)}else if(o===1){s=h(e.charAt(r))<<10|h(e.charAt(r+1))<<4|h(e.charAt(r+2))>>2;l(s>>8&255);l(s&255)}return a}function c(e){var t,r=e.length%3,i="",s,o;function a(e){return n.charAt(e)}function f(e){return a(e>>18&63)+a(e>>12&63)+a(e>>6&63)+a(e&63)}for(t=0,o=e.length-r;t>2);i+=a(s<<4&63);i+="==";break;case 2:s=(e[e.length-2]<<8)+e[e.length-1];i+=a(s>>10);i+=a(s>>4&63);i+=a(s<<2&63);i+="=";break}return i}e.toByteArray=l;e.fromByteArray=c})(typeof r==="undefined"?this.base64js={}:r)},{}],11:[function(e,t,r){t.exports={encode:e("./lib/encode"),decode:e("./lib/decode")}},{"./lib/decode":12,"./lib/encode":14}],12:[function(e,t,r){(function(r){var n=e("./dict");function i(e,t){i.position=0;i.encoding=t||null;i.data=!r.isBuffer(e)?new r(e):e;return i.next()}i.position=0;i.data=null;i.encoding=null;i.next=function(){switch(i.data[i.position]){case 100:return i.dictionary();break;case 108:return i.list();break;case 105:return i.integer();break;default:return i.bytes();break}};i.find=function(e){var t=i.position;var r=i.data.length;var n=i.data;while(t>3;if(e%8!==0)t++;return t; -}n.prototype.get=function(e){var t=e>>3;return t>e%8)};n.prototype.set=function(e,t){var r=e>>3;if(t||arguments.length===1){if(this.buffer.length>e%8}else if(r>e%8)}};n.prototype._grow=function(e){if(this.buffer.length=this._parserSize){var i=this._buffer.length===1?this._buffer[0]:r.concat(this._buffer);this._bufferSize-=this._parserSize;this._buffer=this._bufferSize?[i.slice(this._parserSize)]:[];this._parser(i.slice(0,this._parserSize))}n(null)};w.prototype._read=function(){};w.prototype._callback=function(e,t,r){if(!e)return;this._clearTimeout();if(!this.peerChoking&&!this._finished)this._updateTimeout();e.callback(t,r)};w.prototype._clearTimeout=function(){if(!this._timeout)return;clearTimeout(this._timeout);this._timeout=null};w.prototype._updateTimeout=function(){if(!this._timeoutMs||!this.requests.length||this._timeout)return;this._timeout=setTimeout(this._onTimeout.bind(this),this._timeoutMs);if(this._timeoutUnref&&this._timeout.unref)this._timeout.unref()};w.prototype._parse=function(e,t){this._parserSize=e;this._parser=t};w.prototype._message=function(e,t,n){var i=n?n.length:0;var s=new r(5+4*t.length);s.writeUInt32BE(s.length+i-4,0);s[4]=e;for(var o=0;o0){this._parse(t,this._onmessage)}else{this._onKeepAlive();this._parse(4,this._onmessagelength)}};w.prototype._onmessage=function(e){this._parse(4,this._onmessagelength);switch(e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:this._debug("got unknown message");return this.emit("unknownmessage",e)}};w.prototype._parseHandshake=function(){this._parse(1,function(e){var t=e.readUInt8(0);this._parse(t+48,function(e){var r=e.slice(0,t);if(r.toString()!=="BitTorrent protocol"){this._debug("Error: wire not speaking BitTorrent protocol (%s)",r.toString());this.end();return}e=e.slice(t);this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(e[7]&1),extended:!!(e[5]&16)});this._parse(4,this._onmessagelength)}.bind(this))}.bind(this))};w.prototype._onfinish=function(){this._finished=true;this.push(null);while(this.read()){}clearInterval(this._keepAliveInterval);this._parse(Number.MAX_VALUE,function(){});this.peerRequests=[];while(this.requests.length){this._callback(this.requests.shift(),new Error("wire was closed"),null)}};w.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._debugId+"] "+e[0];s.apply(null,e)};function S(e,t,r,n){for(var i=0;it)f=t;a=n;while(f--){if(o===t)o=0;r[o]=r[o===0?t-1:o-1];o++}if(e)r[o-1]+=e;var u=r[o-1];var h=r.length=e.maxConns){return}s("drain (%s queued, %s/%s peers)",e.numQueued,e.numPeers,e.maxConns);var t=e._queue.shift();if(!t)return;s("tcp connect attempt to %s",t.addr);var r=i(t.addr);var n={host:r[0],port:r[1]};if(e._hostname)n.localAddress=e._hostname;var o=t.conn=u.connect(n);o.once("connect",function(){t.onConnect()});o.once("error",function(e){t.destroy(e)});t.setConnectTimeout();o.on("close",function(){if(e.destroyed)return;if(t.retries>=p.length){s("conn %s closed: will not re-add (max %s attempts)",t.addr,p.length);return}var r=p[t.retries];s("conn %s closed: will re-add to queue in %sms (attempt %s)",t.addr,r,t.retries+1);var n=setTimeout(function i(){var r=e._addPeer(t.addr);if(r)r.retries=t.retries+1},r);if(n.unref)n.unref()})};m.prototype._onError=function(e){var t=this;t.emit("error",e);t.destroy()};m.prototype._validAddr=function(e){var t=this;var r=i(e);var n=r[0];var s=r[1];return s>0&&s<65535&&!(n==="127.0.0.1"&&s===t._port)}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/peer":19,"./lib/tcp-pool":20,_process:83,"addr-to-ip-port":34,buffer:36,debug:42,dezalgo:45,events:47,inherits:55,net:34,speedometer:22}],19:[function(e,t,r){var n=e("debug")("bittorrent-swarm:peer");var i=e("./webconn");var s=e("bittorrent-protocol");var o=25e3;var a=25e3;r.createWebRTCPeer=function(e,t){var r=new f(e.id);r.conn=e;r.swarm=t;if(r.conn.connected){r.onConnect()}else{r.conn.once("connect",function(){r.onConnect()});r.conn.once("error",function(e){r.destroy(e)});r.setConnectTimeout()}return r};r.createIncomingTCPPeer=function(e){var t=e.remoteAddress+":"+e.remotePort;var r=new f(t);r.conn=e;r.addr=t;r.onConnect();return r};r.createOutgoingTCPPeer=function(e,t){var r=new f(e);r.addr=e;r.swarm=t;return r};r.createWebPeer=function(e,t,r){var n=new f(e);n.swarm=r;n.conn=new i(e,t);n.onConnect();return n};function f(e){var t=this;t.id=e;n("new Peer %s",e);t.addr=null;t.conn=null;t.swarm=null;t.wire=null;t.connected=false;t.destroyed=false;t.timeout=null;t.retries=0;t.sentHandshake=false}f.prototype.onConnect=function(){var e=this;if(e.destroyed)return;e.connected=true;n("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 r=e.wire=new s;r.once("end",function(){e.destroy()});r.once("close",function(){e.destroy()});r.once("finish",function(){e.destroy()});r.once("error",function(t){e.destroy(t)});r.once("handshake",function(t,r){e.onHandshake(t,r)});e.setHandshakeTimeout();t.pipe(r).pipe(t);if(e.swarm&&!e.sentHandshake)e.handshake()};f.prototype.onHandshake=function(e,t){var r=this;if(!r.swarm)return;var i=e.toString("hex");var s=t.toString("hex");if(r.swarm.destroyed)return r.destroy(new Error("swarm already destroyed"));if(i!==r.swarm.infoHashHex){return r.destroy(new Error("unexpected handshake info hash for this swarm"))}if(s===r.swarm.peerIdHex){return r.destroy(new Error("refusing to handshake with self"))}n("Peer %s got handshake %s",r.id,i);clearTimeout(r.handshakeTimeout);r.retries=0;r.wire.on("download",function(e){if(r.destroyed)return;r.swarm.downloaded+=e;r.swarm.downloadSpeed(e);r.swarm.emit("download",e)});r.wire.on("upload",function(e){if(r.destroyed)return;r.swarm.uploaded+=e;r.swarm.uploadSpeed(e);r.swarm.emit("upload",e)});if(!r.sentHandshake)r.handshake();r.swarm.wires.push(r.wire);var o=r.addr;if(!o&&r.conn.remoteAddress){o=r.conn.remoteAddress+":"+r.conn.remotePort}r.swarm.emit("wire",r.wire,o)};f.prototype.handshake=function(){var e=this;e.wire.handshake(e.swarm.infoHash,e.swarm.peerId,e.swarm.handshakeOpts);e.sentHandshake=true};f.prototype.setConnectTimeout=function(){var e=this;clearTimeout(e.connectTimeout);e.connectTimeout=setTimeout(function(){e.destroy(new Error("connect timeout"))},o);if(e.connectTimeout.unref)e.connectTimeout.unref()};f.prototype.setHandshakeTimeout=function(){var e=this;clearTimeout(e.handshakeTimeout);e.handshakeTimeout=setTimeout(function(){e.destroy(new Error("handshake timeout"))},a);if(e.handshakeTimeout.unref)e.handshakeTimeout.unref()};f.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;t.connected=false;n("destroy %s (error: %s)",t.id,e&&(e.message||e));clearTimeout(t.connectTimeout);clearTimeout(t.handshakeTimeout);var r=t.swarm;var i=t.conn;var s=t.wire;t.conn=null;t.swarm=null;t.wire=null;if(r&&s){var o=r.wires.indexOf(s);if(o>=0)r.wires.splice(o,1)}if(i)i.destroy();if(s)s.destroy();if(r)r.removePeer(t.id)}},{"./webconn":21,"bittorrent-protocol":16,debug:42}],20:[function(e,t,r){(function(r){t.exports=f;var n=e("debug")("bittorrent-swarm:tcp-pool");var i=e("dezalgo");var s=e("net");var o=e("./peer");var a={};function f(e,t){var r=this;r.port=e;r.listening=false;r.swarms={};n("new TCPPool (port: %s, hostname: %s)",e,t);r.pendingConns=[];r.server=s.createServer();r.server.on("connection",function(e){r._onConnection(e)});r.server.on("error",function(e){r._onError(e)});r.server.on("listening",function(){r._onListening()});r.server.listen(r.port,t)}f.addSwarm=function(e){var t=a[e._port];if(!t)t=a[e._port]=new f(e._port,e._hostname);t.addSwarm(e);return t};f.removeSwarm=function(e,t){var n=a[e._port];if(!n)return t();n.removeSwarm(e);var i=0;for(var s in n.swarms){var o=n.swarms[s];if(o)i+=1}if(i===0)n.destroy(t);else r.nextTick(t)};f.getDefaultListenPort=function(e){for(var t in a){var r=a[t];if(r&&!r.swarms[e])return r.port}return 0};f.prototype.addSwarm=function(e){var t=this;if(t.swarms[e.infoHashHex]){r.nextTick(function(){e._onError(new Error("There is already a swarm with info hash "+e.infoHashHex+" "+"listening on port "+e._port))});return}t.swarms[e.infoHashHex]=e;if(t.listening){r.nextTick(function(){e._onListening(t.port)})}n("add swarm %s to tcp pool %s",e.infoHashHex,t.port)};f.prototype.removeSwarm=function(e){var t=this;n("remove swarm %s from tcp pool %s",e.infoHashHex,t.port);t.swarms[e.infoHashHex]=null};f.prototype.destroy=function(e){var t=this;if(e)e=i(e);n("destroy tcp pool %s",t.port);t.listening=false;t.pendingConns.forEach(function(e){e.destroy()});a[t.port]=null;try{t.server.close(e)}catch(r){if(e)e(null)}};f.prototype._onListening=function(){var e=this;var t=e.server.address()||{port:0};var r=t.port;n("tcp pool listening on %s",r);if(r!==e.port){a[e.port]=null;e.port=r;a[e.port]=e}e.listening=true;for(var i in e.swarms){var s=e.swarms[i];if(s)s._onListening(e.port)}};f.prototype._onConnection=function(e){var t=this;t.pendingConns.push(e);e.once("close",r);function r(){t.pendingConns.splice(t.pendingConns.indexOf(e))}var n=o.createIncomingTCPPeer(e);n.wire.once("handshake",function(i,s){var o=i.toString("hex");r();e.removeListener("close",r);var a=t.swarms[o];if(a){n.swarm=a;a._addIncomingPeer(n);n.onHandshake(i,s)}else{var f=new Error("Unexpected info hash "+o+" from incoming peer "+n.id+": destroying peer");n.destroy(f)}})};f.prototype._onError=function(e){var t=this;t.destroy();for(var r in t.swarms){var n=t.swarms[r];if(n){t.removeSwarm(n);n._onError(e)}}}}).call(this,e("_process"))},{"./peer":19,_process:83,debug:42,dezalgo:45,net:34}],21:[function(e,t,r){(function(r){t.exports=f;var n=e("bitfield");var i=e("debug")("bittorrent-swarm:webconn");var s=e("simple-get");var o=e("inherits");var a=e("bittorrent-protocol");o(f,a);function f(e,t){var s=this;a.call(this);s.url=e;s.parsedTorrent=t;s.setKeepAlive(true);s.on("handshake",function(t,i){s.handshake(t,new r(20).fill(e));var o=s.parsedTorrent.pieces.length;var a=new n(o);for(var f=0;f<=o;f++){a.set(f,true)}s.bitfield(a)});s.on("choke",function(){i("choke")});s.on("unchoke",function(){i("unchoke")});s.once("interested",function(){i("interested");s.unchoke()});s.on("uninterested",function(){i("uninterested")});s.on("bitfield",function(){i("bitfield")});s.on("request",function(e,t,r,n){i("request pieceIndex=%d offset=%d length=%d",e,t,r);s.httpRequest(e,t,r,n)})}f.prototype.httpRequest=function(e,t,r,n){var o=this;var a=e*o.parsedTorrent.pieceLength;var f=a+t;var u=f+r-1;i("Requesting pieceIndex=%d offset=%d length=%d start=%d end=%d",e,t,r,f,u);var h={url:o.url,method:"GET",headers:{"user-agent":"WebTorrent (http://webtorrent.io)",range:"bytes="+f+"-"+u}};s.concat(h,function(e,t,r){if(e)return n(e);if(r.statusCode<200||r.statusCode>=300){return n(new Error("Unexpected HTTP status code "+r.statusCode))}i("Got data of length %d",t.length);n(null,t)})}}).call(this,e("buffer").Buffer)},{bitfield:15,"bittorrent-protocol":16,buffer:36,debug:42,inherits:55,"simple-get":103}],22:[function(e,t,r){arguments[4][17][0].apply(r,arguments)},{dup:17}],23:[function(e,t,r){(function(r,n){t.exports=m;var i=e("events").EventEmitter;var s=e("debug")("bittorrent-tracker");var o=e("inherits");var a=e("once");var f=e("run-parallel");var u=e("uniq");var h=e("url");var l=e("./lib/common");var c=e("./lib/client/http-tracker");var d=e("./lib/client/udp-tracker");var p=e("./lib/client/websocket-tracker");o(m,i);function m(e,t,o,a){var f=this;if(!(f instanceof m))return new m(e,t,o,a);i.call(f);if(!a)a={};f._peerId=n.isBuffer(e)?e:new n(e,"hex");f._peerIdHex=f._peerId.toString("hex");f._peerIdBinary=f._peerId.toString("binary");f._infoHash=n.isBuffer(o.infoHash)?o.infoHash:new n(o.infoHash,"hex");f._infoHashHex=f._infoHash.toString("hex");f._infoHashBinary=f._infoHash.toString("binary");f.torrentLength=o.length;f.destroyed=false;f._port=t;f._rtcConfig=a.rtcConfig;f._wrtc=a.wrtc;s("new client %s",f._infoHashHex);var l=!!f._wrtc||typeof window!=="undefined";var v=typeof o.announce==="string"?[o.announce]:o.announce==null?[]:o.announce;v=v.map(function(e){e=e.toString();if(e[e.length-1]==="/"){e=e.substring(0,e.length-1)}return e});v=u(v);f._trackers=v.map(function(e){var t=h.parse(e).protocol;if((t==="http:"||t==="https:")&&typeof c==="function"){return new c(f,e)}else if(t==="udp:"&&typeof d==="function"){return new d(f,e)}else if((t==="ws:"||t==="wss:")&&l){return new p(f,e)}else{r.nextTick(function(){var t=new Error("unsupported tracker protocol for "+e);f.emit("warning",t)})}return null}).filter(Boolean)}m.scrape=function(e,t,r){r=a(r);var i=new n("01234567890123456789");var s=6881;var o={infoHash:Array.isArray(t)?t[0]:t,announce:[e]};var f=new m(i,s,o);f.once("error",r);var u=Array.isArray(t)?t.length:1;var h={};f.on("scrape",function(e){u-=1;h[e.infoHash]=e;if(u===0){f.destroy();var t=Object.keys(h);if(t.length===1){r(null,h[t[0]])}else{r(null,h)}}});t=Array.isArray(t)?t.map(function(e){return new n(e,"hex")}):new n(t,"hex");f.scrape({infoHash:t})};m.prototype.start=function(e){var t=this;s("send `start`");e=t._defaultAnnounceOpts(e);e.event="started";t._announce(e);t._trackers.forEach(function(e){e.setInterval()})};m.prototype.stop=function(e){var t=this;s("send `stop`");e=t._defaultAnnounceOpts(e);e.event="stopped";t._announce(e)};m.prototype.complete=function(e){var t=this;s("send `complete`");if(!e)e={};if(e.downloaded==null&&t.torrentLength!=null){e.downloaded=t.torrentLength}e=t._defaultAnnounceOpts(e);e.event="completed";t._announce(e)};m.prototype.update=function(e){var t=this;s("send `update`");e=t._defaultAnnounceOpts(e);if(e.event)delete e.event;t._announce(e)};m.prototype._announce=function(e){var t=this;t._trackers.forEach(function(t){t.announce(e)})};m.prototype.scrape=function(e){var t=this;s("send `scrape`");if(!e)e={};t._trackers.forEach(function(t){t.scrape(e)})};m.prototype.setInterval=function(e){var t=this;s("setInterval %d",e);t._trackers.forEach(function(t){t.setInterval(e)})};m.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;s("destroy");var r=t._trackers.map(function(e){return function(t){e.destroy(t)}});f(r,e);t._trackers=[]};m.prototype._defaultAnnounceOpts=function(e){var t=this;if(!e)e={};if(e.numwant==null)e.numwant=l.DEFAULT_ANNOUNCE_PEERS;if(e.uploaded==null)e.uploaded=0;if(e.downloaded==null)e.downloaded=0;if(e.left==null&&t.torrentLength!=null){e.left=t.torrentLength-e.downloaded}return e}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/client/http-tracker":34,"./lib/client/udp-tracker":34,"./lib/client/websocket-tracker":25,"./lib/common":26,_process:83,buffer:36,debug:42,events:47,inherits:55,once:73,"run-parallel":101,uniq:119,url:120}],24:[function(e,t,r){t.exports=s;var n=e("events").EventEmitter;var i=e("inherits");i(s,n);function s(e,t){var r=this;n.call(r);r.client=e;r.announceUrl=t;r.interval=null;r.destroyed=false}s.prototype.setInterval=function(e){var t=this;if(t.interval)return;if(e==null)e=t.DEFAULT_ANNOUNCE_INTERVAL;clearInterval(t.interval);if(e){var r=t.announce.bind(t,t.client._defaultAnnounceOpts());t.interval=setInterval(r,e);if(t.interval.unref)t.interval.unref()}}},{events:47,inherits:55}],25:[function(e,t,r){t.exports=d;var n=e("debug")("bittorrent-tracker:websocket-tracker");var i=e("hat");var s=e("inherits");var o=e("simple-peer");var a=e("simple-websocket");var f=e("../common");var u=e("./tracker");var h={};var l=30*1e3;var c=5*1e3;s(d,u);function d(e,t,r){var i=this;u.call(i,e,t);n("new websocket tracker %s",t);i.peers={};i.socket=null;i.reconnecting=false;i._openSocket()}d.prototype.DEFAULT_ANNOUNCE_INTERVAL=30*1e3;d.prototype.announce=function(e){var t=this;if(t.destroyed||t.reconnecting)return;if(!t.socket.connected){return t.socket.once("connect",t.announce.bind(t,e))}var r=Math.min(e.numwant,10);t._generateOffers(r,function(n){var i={numwant:r,uploaded:e.uploaded||0,downloaded:e.downloaded,event:e.event,info_hash:t.client._infoHashBinary,peer_id:t.client._peerIdBinary,offers:n};if(t._trackerId)i.trackerid=t._trackerId;t._send(i)})};d.prototype.scrape=function(e){var t=this;if(t.destroyed||t.reconnecting)return;t._onSocketError(new Error("scrape not supported "+t.announceUrl))};d.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;clearInterval(t.interval);h[t.announceUrl]=null;t.socket.removeListener("connect",t._onSocketConnectBound);t.socket.removeListener("data",t._onSocketDataBound);t.socket.removeListener("close",t._onSocketCloseBound);t.socket.removeListener("error",t._onSocketErrorBound);t._onSocketConnectBound=null;t._onSocketErrorBound=null;t._onSocketDataBound=null;t._onSocketCloseBound=null;t.socket.on("error",p);try{t.socket.destroy(e)}catch(r){if(e)e()}t.socket=null};d.prototype._openSocket=function(){var e=this;e.destroyed=false;e._onSocketConnectBound=e._onSocketConnect.bind(e);e._onSocketErrorBound=e._onSocketError.bind(e);e._onSocketDataBound=e._onSocketData.bind(e);e._onSocketCloseBound=e._onSocketClose.bind(e);e.socket=h[e.announceUrl];if(!e.socket){e.socket=h[e.announceUrl]=new a(e.announceUrl);e.socket.on("connect",e._onSocketConnectBound)}e.socket.on("data",e._onSocketDataBound);e.socket.on("close",e._onSocketCloseBound);e.socket.on("error",e._onSocketErrorBound)};d.prototype._onSocketConnect=function(){var e=this;if(e.destroyed)return;if(e.reconnecting){e.reconnecting=false;e.announce(e.client._defaultAnnounceOpts())}};d.prototype._onSocketData=function(e){var t=this;if(t.destroyed)return;if(!(typeof e==="object"&&e!==null)){return t.client.emit("warning",new Error("Invalid tracker response"))}if(e.info_hash!==t.client._infoHashBinary){n("ignoring websocket data from %s for %s (looking for %s: reused socket)",t.announceUrl,f.binaryToHex(e.info_hash),t.client._infoHashHex);return}if(e.peer_id&&e.peer_id===t.client._peerIdBinary){return}n("received %s from %s for %s",JSON.stringify(e),t.announceUrl,t.client._infoHashHex);var r=e["failure reason"];if(r)return t.client.emit("warning",new Error(r));var i=e["warning message"];if(i)t.client.emit("warning",new Error(i));var s=e.interval||e["min interval"];if(s)t.setInterval(s*1e3);var a=e["tracker id"];if(a){t._trackerId=a}if(e.complete){t.client.emit("update",{announce:t.announceUrl,complete:e.complete,incomplete:e.incomplete})}var u;if(e.offer&&e.peer_id){u=new o({trickle:false,config:t.client._rtcConfig,wrtc:t.client._wrtc});u.id=f.binaryToHex(e.peer_id);u.once("signal",function(r){var n={info_hash:t.client._infoHashBinary, -peer_id:t.client._peerIdBinary,to_peer_id:e.peer_id,answer:r,offer_id:e.offer_id};if(t._trackerId)n.trackerid=t._trackerId;t._send(n)});u.signal(e.offer);t.client.emit("peer",u)}if(e.answer&&e.peer_id){u=t.peers[f.binaryToHex(e.offer_id)];if(u){u.id=f.binaryToHex(e.peer_id);u.signal(e.answer);t.client.emit("peer",u)}else{n("got unexpected answer: "+JSON.stringify(e.answer))}}};d.prototype._onSocketClose=function(){var e=this;if(e.destroyed)return;e.destroy();e._startReconnectTimer()};d.prototype._onSocketError=function(e){var t=this;if(t.destroyed)return;t.destroy();t.client.emit("warning",e);t._startReconnectTimer()};d.prototype._startReconnectTimer=function(){var e=this;var t=Math.floor(Math.random()*l)+c;e.reconnecting=true;var r=setTimeout(function(){e._openSocket()},t);if(r.unref)r.unref();n("reconnecting socket in %s ms",t)};d.prototype._send=function(e){var t=this;if(t.destroyed)return;var r=JSON.stringify(e);n("send %s",r);t.socket.send(r)};d.prototype._generateOffers=function(e,t){var r=this;var s=[];n("generating %s offers",e);for(var a=0;a=this.size){var i=r.concat(this._buffered);this._bufferedBytes-=this.size;this.push(i.slice(0,this.size));this._buffered=[i.slice(this.size,i.length)]}n()};o.prototype._flush=function(){if(this._bufferedBytes&&this._zeroPadding){var e=new r(this.size-this._bufferedBytes);e.fill(0);this._buffered.push(e);this.push(r.concat(this._buffered));this._buffered=null}else if(this._bufferedBytes){this.push(r.concat(this._buffered));this._buffered=null}this.push(null)}}).call(this,e("buffer").Buffer)},{buffer:36,defined:44,inherits:55,"readable-stream":33}],28:[function(e,t,r){(function(r){t.exports=a;var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};var i=e("core-util-is");i.inherits=e("inherits");var s=e("./_stream_readable");var o=e("./_stream_writable");i.inherits(a,s);u(n(o.prototype),function(e){if(!a.prototype[e])a.prototype[e]=o.prototype[e]});function a(e){if(!(this instanceof a))return new a(e);s.call(this,e);o.call(this,e);if(e&&e.readable===false)this.readable=false;if(e&&e.writable===false)this.writable=false;this.allowHalfOpen=true;if(e&&e.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",f)}function f(){if(this.allowHalfOpen||this._writableState.ended)return;r.nextTick(this.end.bind(this))}function u(e,t){for(var r=0,n=e.length;r0){if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var o=new Error("stream.unshift() after end event");e.emit("error",o)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)y(e)}w(e,t)}}else if(!i){t.reading=false}return d(t)}function d(e){return!e.ended&&(e.needReadable||e.length=p){e=p}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function v(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(isNaN(e)||a.isNull(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=m(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else return t.length}return e}l.prototype.read=function(e){u("read",e);var t=this._readableState;var r=e;if(!a.isNumber(e)||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){u("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)T(this);else y(this);return null}e=v(e,t);if(e===0&&t.ended){if(t.length===0)T(this);return null}var n=t.needReadable;u("need readable",n);if(t.length===0||t.length-e0)i=U(e,t);else i=null;if(a.isNull(i)){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)T(this);if(!a.isNull(i))this.emit("data",i);return i};function g(e,t){var r=null;if(!a.isBuffer(t)&&!a.isString(t)&&!a.isNullOrUndefined(t)&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function _(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;y(e)}function y(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)r.nextTick(function(){b(e)});else b(e)}}function b(e){u("emit readable");e.emit("readable");A(e)}function w(e,t){if(!t.readingMore){t.readingMore=true;r.nextTick(function(){S(e,t)})}}function S(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(s)a=r.join("");else a=i.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;r.nextTick(function(){if(!t.endEmitted&&t.length===0){t.endEmitted=true;e.readable=false;e.emit("end")}})}}function I(e,t){for(var r=0,n=e.length;r1){var r=[];for(var n=0;n1)return new u(e,arguments[1]);return new u(e)}this.length=0;this.parent=undefined;if(typeof e==="number"){return h(this,e)}if(typeof e==="string"){return l(this,e,arguments.length>1?arguments[1]:"utf8")}return c(this,e)}function h(e,t){e=y(e,t<0?0:b(t)|0);if(!u.TYPED_ARRAY_SUPPORT){for(var r=0;r>>1;if(r)e.parent=o;return e}function b(e){if(e>=f()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+f().toString(16)+" bytes")}return e|0}function w(e,t){if(!(this instanceof w))return new w(e,t);var r=new u(e,t);delete r.parent;return r}u.isBuffer=function te(e){return!!(e!=null&&e._isBuffer)};u.compare=function re(e,t){if(!u.isBuffer(e)||!u.isBuffer(t)){throw new TypeError("Arguments must be Buffers")}if(e===t)return 0;var r=e.length;var n=t.length;var i=0;var s=Math.min(r,n);while(i>>1;case"base64":return Q(e).length;default:if(n)return X(e).length;t=(""+t).toLowerCase();n=true}}}u.byteLength=S;u.prototype.length=undefined;u.prototype.parent=undefined;function x(e,t,r){var n=false;t=t|0;r=r===undefined||r===Infinity?this.length:r|0;if(!e)e="utf8";if(t<0)t=0;if(r>this.length)r=this.length;if(r<=t)return"";while(true){switch(e){case"hex":return O(this,t,r);case"utf8":case"utf-8":return B(this,t,r);case"ascii":return P(this,t,r);case"binary":return F(this,t,r);case"base64":return L(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase();n=true}}}u.prototype.toString=function se(){var e=this.length|0;if(e===0)return"";if(arguments.length===0)return B(this,0,e);return x.apply(this,arguments)};u.prototype.equals=function oe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return true;return u.compare(this,e)===0};u.prototype.inspect=function ae(){var e="";var t=r.INSPECT_MAX_BYTES;if(this.length>0){e=this.toString("hex",0,t).match(/.{2}/g).join(" ");if(this.length>t)e+=" ... "}return""};u.prototype.compare=function fe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return 0;return u.compare(this,e)};u.prototype.indexOf=function ue(e,t){if(t>2147483647)t=2147483647;else if(t<-2147483648)t=-2147483648;t>>=0;if(this.length===0)return-1;if(t>=this.length)return-1;if(t<0)t=Math.max(this.length+t,0);if(typeof e==="string"){if(e.length===0)return-1;return String.prototype.indexOf.call(this,e,t)}if(u.isBuffer(e)){return r(this,e,t)}if(typeof e==="number"){if(u.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,e,t)}return r(this,[e],t)}function r(e,t,r){var n=-1;for(var i=0;r+ii){n=i}}var s=t.length;if(s%2!==0)throw new Error("Invalid hex string");if(n>s/2){n=s/2}for(var o=0;os)r=s;if(e.length>0&&(r<0||t<0)||t>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!n)n="utf8";var o=false;for(;;){switch(n){case"hex":return k(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":return A(this,e,t,r);case"binary":return U(this,e,t,r);case"base64":return T(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase();o=true}}};u.prototype.toJSON=function de(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function L(e,t,r){if(t===0&&r===e.length){return n.fromByteArray(e)}else{return n.fromByteArray(e.slice(t,r))}}function B(e,t,r){r=Math.min(e.length,r);var n=[];var i=t;while(i239?4:s>223?3:s>191?2:1;if(i+a<=r){var f,u,h,l;switch(a){case 1:if(s<128){o=s}break;case 2:f=e[i+1];if((f&192)===128){l=(s&31)<<6|f&63;if(l>127){o=l}}break;case 3:f=e[i+1];u=e[i+2];if((f&192)===128&&(u&192)===128){l=(s&15)<<12|(f&63)<<6|u&63;if(l>2047&&(l<55296||l>57343)){o=l}}break;case 4:f=e[i+1];u=e[i+2];h=e[i+3];if((f&192)===128&&(u&192)===128&&(h&192)===128){l=(s&15)<<18|(f&63)<<12|(u&63)<<6|h&63;if(l>65535&&l<1114112){o=l}}}}if(o===null){o=65533;a=1}else if(o>65535){o-=65536;n.push(o>>>10&1023|55296);o=56320|o&1023}n.push(o);i+=a}return R(n)}var C=4096;function R(e){var t=e.length;if(t<=C){return String.fromCharCode.apply(String,e)}var r="";var n=0;while(nn)r=n;var i="";for(var s=t;sr){e=r}if(t<0){t+=r;if(t<0)t=0}else if(t>r){t=r}if(tr)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUIntLE=function me(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s0&&(i*=256)){n+=this[e+--t]*i}return n};u.prototype.readUInt8=function ge(e,t){if(!t)D(e,1,this.length);return this[e]};u.prototype.readUInt16LE=function _e(e,t){if(!t)D(e,2,this.length);return this[e]|this[e+1]<<8};u.prototype.readUInt16BE=function ye(e,t){if(!t)D(e,2,this.length);return this[e]<<8|this[e+1]};u.prototype.readUInt32LE=function be(e,t){if(!t)D(e,4,this.length);return(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};u.prototype.readUInt32BE=function we(e,t){if(!t)D(e,4,this.length);return this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};u.prototype.readIntLE=function Se(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s=i)n-=Math.pow(2,8*t);return n};u.prototype.readIntBE=function xe(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=t;var i=1;var s=this[e+--n];while(n>0&&(i*=256)){s+=this[e+--n]*i}i*=128;if(s>=i)s-=Math.pow(2,8*t);return s};u.prototype.readInt8=function ke(e,t){if(!t)D(e,1,this.length);if(!(this[e]&128))return this[e];return(255-this[e]+1)*-1};u.prototype.readInt16LE=function Ee(e,t){if(!t)D(e,2,this.length);var r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};u.prototype.readInt16BE=function Ae(e,t){if(!t)D(e,2,this.length);var r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};u.prototype.readInt32LE=function Ue(e,t){if(!t)D(e,4,this.length);return this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};u.prototype.readInt32BE=function Te(e,t){if(!t)D(e,4,this.length);return this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};u.prototype.readFloatLE=function Ie(e,t){if(!t)D(e,4,this.length);return i.read(this,e,true,23,4)};u.prototype.readFloatBE=function Le(e,t){ -if(!t)D(e,4,this.length);return i.read(this,e,false,23,4)};u.prototype.readDoubleLE=function Be(e,t){if(!t)D(e,8,this.length);return i.read(this,e,true,52,8)};u.prototype.readDoubleBE=function Ce(e,t){if(!t)D(e,8,this.length);return i.read(this,e,false,52,8)};function N(e,t,r,n,i,s){if(!u.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>i||te.length)throw new RangeError("index out of range")}u.prototype.writeUIntLE=function Re(e,t,r,n){e=+e;t=t|0;r=r|0;if(!n)N(this,e,t,r,Math.pow(2,8*r),0);var i=1;var s=0;this[t]=e&255;while(++s=0&&(s*=256)){this[t+i]=e/s&255}return t+r};u.prototype.writeUInt8=function Fe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,1,255,0);if(!u.TYPED_ARRAY_SUPPORT)e=Math.floor(e);this[t]=e&255;return t+1};function z(e,t,r,n){if(t<0)t=65535+t+1;for(var i=0,s=Math.min(e.length-r,2);i>>(n?i:1-i)*8}}u.prototype.writeUInt16LE=function Oe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8}else{z(this,e,t,true)}return t+2};u.prototype.writeUInt16BE=function Me(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e&255}else{z(this,e,t,false)}return t+2};function j(e,t,r,n){if(t<0)t=4294967295+t+1;for(var i=0,s=Math.min(e.length-r,4);i>>(n?i:3-i)*8&255}}u.prototype.writeUInt32LE=function De(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[t+3]=e>>>24;this[t+2]=e>>>16;this[t+1]=e>>>8;this[t]=e&255}else{j(this,e,t,true)}return t+4};u.prototype.writeUInt32BE=function Ne(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e&255}else{j(this,e,t,false)}return t+4};u.prototype.writeIntLE=function ze(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=0;var o=1;var a=e<0?1:0;this[t]=e&255;while(++s>0)-a&255}return t+r};u.prototype.writeIntBE=function je(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=r-1;var o=1;var a=e<0?1:0;this[t+s]=e&255;while(--s>=0&&(o*=256)){this[t+s]=(e/o>>0)-a&255}return t+r};u.prototype.writeInt8=function He(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,1,127,-128);if(!u.TYPED_ARRAY_SUPPORT)e=Math.floor(e);if(e<0)e=255+e+1;this[t]=e&255;return t+1};u.prototype.writeInt16LE=function qe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8}else{z(this,e,t,true)}return t+2};u.prototype.writeInt16BE=function Ge(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e&255}else{z(this,e,t,false)}return t+2};u.prototype.writeInt32LE=function We(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,2147483647,-2147483648);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8;this[t+2]=e>>>16;this[t+3]=e>>>24}else{j(this,e,t,true)}return t+4};u.prototype.writeInt32BE=function Ye(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,2147483647,-2147483648);if(e<0)e=4294967295+e+1;if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e&255}else{j(this,e,t,false)}return t+4};function H(e,t,r,n,i,s){if(t>i||te.length)throw new RangeError("index out of range");if(r<0)throw new RangeError("index out of range")}function q(e,t,r,n,s){if(!s){H(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38)}i.write(e,t,r,n,23,4);return r+4}u.prototype.writeFloatLE=function Ve(e,t,r){return q(this,e,t,true,r)};u.prototype.writeFloatBE=function Ke(e,t,r){return q(this,e,t,false,r)};function G(e,t,r,n,s){if(!s){H(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308)}i.write(e,t,r,n,52,8);return r+8}u.prototype.writeDoubleLE=function $e(e,t,r){return G(this,e,t,true,r)};u.prototype.writeDoubleBE=function Xe(e,t,r){return G(this,e,t,false,r)};u.prototype.copy=function Ze(e,t,r,n){if(!r)r=0;if(!n&&n!==0)n=this.length;if(t>=e.length)t=e.length;if(!t)t=0;if(n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");if(n>this.length)n=this.length;if(e.length-t=0;s--){e[s+t]=this[s+r]}}else if(i<1e3||!u.TYPED_ARRAY_SUPPORT){for(s=0;s=this.length)throw new RangeError("start out of bounds");if(r<0||r>this.length)throw new RangeError("end out of bounds");var n;if(typeof e==="number"){for(n=t;n55295&&r<57344){if(!i){if(r>56319){if((t-=3)>-1)s.push(239,191,189);continue}else if(o+1===n){if((t-=3)>-1)s.push(239,191,189);continue}i=r;continue}if(r<56320){if((t-=3)>-1)s.push(239,191,189);i=r;continue}r=(i-55296<<10|r-56320)+65536}else if(i){if((t-=3)>-1)s.push(239,191,189)}i=null;if(r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else{throw new Error("Invalid code point")}}return s}function Z(e){var t=[];for(var r=0;r>8;i=r%256;s.push(i);s.push(n)}return s}function Q(e){return n.toByteArray(V(e))}function ee(e,t,r,n){for(var i=0;i=t.length||i>=e.length)break;t[i+r]=e[i]}return i}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":10,ieee754:53,"is-array":56}],37:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Time-out",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Request Entity Too Large",414:"Request-URI Too Large",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Time-out",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],38:[function(e,t,r){t.exports=o;var n=e("block-stream2");var i=e("inherits");var s=e("stream");i(o,s.Writable);function o(e,t,r){var i=this;if(!(i instanceof o)){return new o(e,t,r)}s.Writable.call(i,r);if(!r)r={};if(!e||!e.put||!e.get){throw new Error("First argument must be an abstract-chunk-store compliant store")}t=Number(t);if(!t)throw new Error("Second argument must be a chunk length");i._blockstream=new n(t,{zeroPadding:false});i._blockstream.on("data",f).on("error",function(e){i.destroy(e)});var a=0;function f(t){if(i.destroyed)return;e.put(a,t);a+=1}i.on("finish",function(){this._blockstream.end()})}o.prototype._write=function(e,t,r){this._blockstream.write(e,t,r)};o.prototype.destroy=function(e){if(this.destroyed)return;this.destroyed=true;if(e)this.emit("error",e);this.emit("close")}},{"block-stream2":27,inherits:55,stream:108}],39:[function(e,t,r){t.exports=function(e,t){var r=Infinity;var n=0;var i=null;t.sort(function(e,t){return e-t});for(var s=0,o=t.length;s=r){break}r=n;i=t[s]}return i}},{}],40:[function(e,t,r){(function(e){function t(e){if(Array.isArray){return Array.isArray(e)}return v(e)==="[object Array]"}r.isArray=t;function n(e){return typeof e==="boolean"}r.isBoolean=n;function i(e){return e===null}r.isNull=i;function s(e){return e==null}r.isNullOrUndefined=s;function o(e){return typeof e==="number"}r.isNumber=o;function a(e){return typeof e==="string"}r.isString=a;function f(e){return typeof e==="symbol"}r.isSymbol=f;function u(e){return e===void 0}r.isUndefined=u;function h(e){return v(e)==="[object RegExp]"}r.isRegExp=h;function l(e){return typeof e==="object"&&e!==null}r.isObject=l;function c(e){return v(e)==="[object Date]"}r.isDate=c;function d(e){return v(e)==="[object Error]"||e instanceof Error}r.isError=d;function p(e){return typeof e==="function"}r.isFunction=p;function m(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}r.isPrimitive=m;r.isBuffer=e.isBuffer;function v(e){return Object.prototype.toString.call(e)}}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":57}],41:[function(e,t,r){(function(r,n){t.exports=y;t.exports.announceList=[["udp://tracker.openbittorrent.com:80"],["udp://tracker.internetwarriors.net:1337"],["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://exodus.desync.com:6969"],["wss://tracker.webtorrent.io"]];t.exports.parseInput=b;var i=e("bencode");var s=e("block-stream2");var o=e("piece-length");var a=e("path");var f=e("dezalgo");var u=e("filestream/read");var h=e("flatten");var l=e("fs");var c=e("is-file");var d=e("junk");var p=e("multistream");var m=e("once");var v=e("run-parallel");var g=e("simple-sha1");var _=e("stream");function y(e,t,r){if(typeof t==="function"){r=t;t={}}if(!t)t={};b(e,t,function(e,n,i){if(e)return r(e);t.singleFileTorrent=i;A(n,t,r)})}function b(e,t,r){if(typeof t==="function"){r=t;t={}}if(!t)t={};r=f(r);if(Array.isArray(e)&&e.length===0)throw new Error("invalid input type");if(I(e))e=Array.prototype.slice.call(e);if(!Array.isArray(e))e=[e];if(!t.name)t.name=e[0]&&e[0].name;if(!t.name)t.name=typeof e[0]==="string"&&a.basename(e[0]);if(t.name===undefined){throw new Error("missing option 'name' and unable to infer it from input[0].name")}if(e.length===1&&!e[0].name)e[0].name=t.name;var i=e.reduce(function(e,t){return e+Number(typeof t==="string")},0);var s=e.length===1;if(e.length===1&&typeof e[0]==="string"){c(e[0],function(e,t){if(e)return r(e);s=t;o()})}else{o()}function o(){v(e.map(function(e){return function(r){var o={};if(T(e)){o.getStream=B(e);o.length=e.size}else if(n.isBuffer(e)){o.getStream=C(e);o.length=e.length}else if(L(e)){if(!t.pieceLength){throw new Error("must specify `pieceLength` option if input is Stream")}o.getStream=P(e,o);o.length=0}else if(typeof e==="string"){if(typeof l.readdir!=="function"){throw new Error("filesystem paths do not work in the browser")}var f=i>1||s;w(e,f,r);return}else{throw new Error("invalid input type")}if(!e.name)throw new Error("missing requied `name` property on input");o.path=e.name.split(a.sep);r(null,o)}}),function(e,t){if(e)return r(e);t=h(t);r(null,t,s)})}}function w(e,t,r){x(e,S,function(n,i){if(n)return r(n);if(Array.isArray(i))i=h(i);else i=[i];e=a.normalize(e);if(t){e=e.slice(0,e.lastIndexOf(a.sep)+1)}if(e[e.length-1]!==a.sep)e+=a.sep;i.forEach(function(t){t.getStream=R(t.path);t.path=t.path.replace(e,"").split(a.sep)});r(null,i)})}function S(e,t){t=m(t);l.stat(e,function(r,n){if(r)return t(r);var i={length:n.size,path:e};t(null,i)})}function x(e,t,r){l.readdir(e,function(n,i){if(n&&n.code==="ENOTDIR"){t(e,r)}else if(n){r(n)}else{v(i.filter(k).filter(d.not).map(function(r){return function(n){x(a.join(e,r),t,n)}}),r)}})}function k(e){return e[0]!=="."}function E(e,t,r){r=m(r);var i=[];var o=0;var a=e.map(function(e){return e.getStream});var f=0;var u=0;var h=false;var l=new p(a);var c=new s(t,{zeroPadding:false});l.on("error",_);l.pipe(c).on("data",d).on("end",v).on("error",_);function d(e){o+=e.length;var t=u;g(e,function(e){i[t]=e;f-=1;b()});f+=1;u+=1}function v(){h=true;b()}function _(e){y();r(e)}function y(){l.removeListener("error",_);c.removeListener("data",d);c.removeListener("end",v);c.removeListener("error",_)}function b(){if(h&&f===0){y();r(null,new n(i.join(""),"hex"),o)}}}function A(e,n,s){var a=n.announceList;if(!a){if(typeof n.announce==="string")a=[[n.announce]];else if(Array.isArray(n.announce)){a=n.announce.map(function(e){return[e]})}}if(!a)a=[];if(r.WEBTORRENT_ANNOUNCE){if(typeof r.WEBTORRENT_ANNOUNCE==="string"){a.push([[r.WEBTORRENT_ANNOUNCE]])}else if(Array.isArray(r.WEBTORRENT_ANNOUNCE)){a=a.concat(r.WEBTORRENT_ANNOUNCE.map(function(e){return[e]}))}}if(a.length===0){a=a.concat(t.exports.announceList)}if(typeof n.urlList==="string")n.urlList=[n.urlList];var f={info:{name:n.name},announce:a[0][0],"announce-list":a,"creation date":Number(n.creationDate)||Date.now(),encoding:"UTF-8"};if(n.comment!==undefined)f.comment=n.comment;if(n.createdBy!==undefined)f["created by"]=n.createdBy;if(n.private!==undefined)f.info.private=Number(n.private);if(n.sslCert!==undefined)f.info["ssl-cert"]=n.sslCert;if(n.urlList!==undefined)f["url-list"]=n.urlList;var u=n.pieceLength||o(e.reduce(U,0));f.info["piece length"]=u;E(e,u,function(t,r,o){if(t)return s(t);f.info.pieces=r;e.forEach(function(e){delete e.getStream});if(n.singleFileTorrent){f.info.length=o}else{f.info.files=e}s(null,i.encode(f))})}function U(e,t){return e+t.length}function T(e){return typeof Blob!=="undefined"&&e instanceof Blob}function I(e){return typeof FileList==="function"&&e instanceof FileList}function L(e){return typeof e==="object"&&typeof e.pipe==="function"}function B(e){return function(){return new u(e)}}function C(e){return function(){var t=new _.PassThrough;t.end(e);return t}}function R(e){return function(){return l.createReadStream(e)}}function P(e,t){return function(){var r=new _.Transform;r._transform=function(e,r,n){t.length+=e.length;this.push(e);n()};e.pipe(r);return r}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{bencode:11,"block-stream2":27,buffer:36,dezalgo:45,"filestream/read":48,flatten:49,fs:35,"is-file":58,junk:61,multistream:72,once:73,path:77,"piece-length":79,"run-parallel":101,"simple-sha1":105,stream:108}],42:[function(e,t,r){r=t.exports=e("./debug");r.log=s;r.formatArgs=i;r.save=o;r.load=a;r.useColors=n;r.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:f();r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function n(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}r.formatters.j=function(e){return JSON.stringify(e)};function i(){var e=arguments;var t=this.useColors;e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+r.humanize(this.diff);if(!t)return e;var n="color: "+this.color;e=[e[0],n,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0;var s=0;e[0].replace(/%[a-z%]/g,function(e){if("%%"===e)return;i++;if("%c"===e){s=i}});e.splice(s,0,n);return e}function s(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function o(e){try{if(null==e){r.storage.removeItem("debug")}else{r.storage.debug=e}}catch(t){}}function a(){var e;try{e=r.storage.debug}catch(t){}return e}r.enable(a());function f(){try{return window.localStorage}catch(e){}}},{"./debug":43}],43:[function(e,t,r){r=t.exports=o;r.coerce=h;r.disable=f;r.enable=a;r.enabled=u;r.humanize=e("ms");r.names=[];r.skips=[];r.formatters={};var n=0;var i;function s(){return r.colors[n++%r.colors.length]}function o(e){function t(){}t.enabled=false;function n(){var e=n;var t=+new Date;var o=t-(i||t);e.diff=o;e.prev=i;e.curr=t;i=t;if(null==e.useColors)e.useColors=r.useColors();if(null==e.color&&e.useColors)e.color=s();var a=Array.prototype.slice.call(arguments);a[0]=r.coerce(a[0]);if("string"!==typeof a[0]){a=["%o"].concat(a)}var f=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,n){if(t==="%%")return t;f++;var i=r.formatters[n];if("function"===typeof i){var s=a[f];t=i.call(e,s);a.splice(f,1);f--}return t});if("function"===typeof r.formatArgs){a=r.formatArgs.apply(e,a)}var u=n.log||r.log||console.log.bind(console);u.apply(e,a)}n.enabled=true;var o=r.enabled(e)?n:t;o.namespace=e;return o}function a(e){r.save(e);var t=(e||"").split(/[\s,]+/);var n=t.length;for(var i=0;i0&&this._events[e].length>r){this._events[e].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[e].length);if(typeof console.trace==="function"){console.trace()}}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=false;function n(){this.removeListener(e,n);if(!r){r=true;t.apply(this,arguments)}}n.listener=t;this.on(e,n);return this};n.prototype.removeListener=function(e,t){var r,n,s,a;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;r=this._events[e];s=r.length;n=-1;if(r===t||i(r.listener)&&r.listener===t){delete this._events[e];if(this._events.removeListener)this.emit("removeListener",e,t)}else if(o(r)){for(a=s;a-- >0;){if(r[a]===t||r[a].listener&&r[a].listener===t){n=a;break}}if(n<0)return this;if(r.length===1){r.length=0;delete this._events[e]}else{r.splice(n,1)}if(this._events.removeListener)this.emit("removeListener",e,t)}return this};n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[e])delete this._events[e];return this}if(arguments.length===0){for(t in this._events){if(t==="removeListener")continue;this.removeAllListeners(t)}this.removeAllListeners("removeListener");this._events={};return this}r=this._events[e];if(i(r)){this.removeListener(e,r)}else if(r){while(r.length)this.removeListener(e,r[r.length-1])}delete this._events[e];return this};n.prototype.listeners=function(e){var t;if(!this._events||!this._events[e])t=[];else if(i(this._events[e]))t=[this._events[e]];else t=this._events[e].slice();return t};n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;else if(t)return t.length}return 0};n.listenerCount=function(e,t){return e.listenerCount(t)};function i(e){return typeof e==="function"}function s(e){return typeof e==="number"}function o(e){return typeof e==="object"&&e!==null}function a(e){return e===void 0}},{}],48:[function(e,t,r){var n=e("stream").Readable;var i=e("inherits");var s=/^.*\.(\w+)$/;var o=e("typedarray-to-buffer");function a(e,t){var r=this;if(!(this instanceof a)){return new a(e,t)}t=t||{};n.call(this,t);this._offset=0;this._ready=false;this._file=e;this._size=e.size;this._chunkSize=t.chunkSize||Math.max(this._size/1e3,200*1024);this.reader=new FileReader;this._generateHeaderBlocks(e,t,function(e,t){if(e){return r.emit("error",e)}if(Array.isArray(t)){t.forEach(function(e){r.push(e)})}r._ready=true;r.emit("_ready")})}i(a,n);t.exports=a;a.prototype._generateHeaderBlocks=function(e,t,r){r(null,[])};a.prototype._read=function(){if(!this._ready){this.once("_ready",this._read.bind(this));return}var e=this;var t=this.reader;var r=this._offset;var n=this._offset+this._chunkSize;if(n>this._size)n=this._size;if(r===this._size){this.destroy();this.push(null);return}t.onload=function(){e._offset=n;e.push(o(t.result))};t.onerror=function(){e.emit("error",t.error)};t.readAsArrayBuffer(this._file.slice(r,n))};a.prototype.destroy=function(){this._file=null;if(this.reader){this.reader.onload=null;this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}},{inherits:55,stream:108,"typedarray-to-buffer":118}],49:[function(e,t,r){t.exports=function n(e,t){t=typeof t=="number"?t:Infinity;return r(e,1);function r(e,n){return e.reduce(function(e,i){if(Array.isArray(i)&&n=Math.pow(2,e)){return n(e,t)}else return o};n.rack=function(e,t,r){var i=function(i){var o=0;do{if(o++>10){if(r)e+=r;else throw new Error("too many ID collisions, use more bits")}var a=n(e,t)}while(Object.hasOwnProperty.call(s,a));s[a]=i;return a};var s=i.hats={};i.get=function(e){return i.hats[e]};i.set=function(e,t){i.hats[e]=t;return i};i.bits=e||128;i.base=t||16;return i}},{}],52:[function(e,t,r){var n=e("http");var i=t.exports;for(var s in n){if(n.hasOwnProperty(s))i[s]=n[s]}i.request=function(e,t){if(!e)e={};e.scheme="https";e.protocol="https:";return n.request.call(this,e,t)}},{http:109}],53:[function(e,t,r){r.read=function(e,t,r,n,i){var s,o;var a=i*8-n-1;var f=(1<>1;var h=-7;var l=r?i-1:0;var c=r?-1:1;var d=e[t+l];l+=c;s=d&(1<<-h)-1;d>>=-h;h+=a;for(;h>0;s=s*256+e[t+l],l+=c,h-=8){}o=s&(1<<-h)-1;s>>=-h;h+=n;for(;h>0;o=o*256+e[t+l],l+=c,h-=8){}if(s===0){s=1-u}else if(s===f){return o?NaN:(d?-1:1)*Infinity}else{o=o+Math.pow(2,n);s=s-u}return(d?-1:1)*o*Math.pow(2,s-n)};r.write=function(e,t,r,n,i,s){var o,a,f;var u=s*8-i-1;var h=(1<>1;var c=i===23?Math.pow(2,-24)-Math.pow(2,-77):0;var d=n?0:s-1;var p=n?1:-1;var m=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){a=isNaN(t)?1:0;o=h}else{o=Math.floor(Math.log(t)/Math.LN2);if(t*(f=Math.pow(2,-o))<1){o--;f*=2}if(o+l>=1){t+=c/f}else{t+=c*Math.pow(2,1-l)}if(t*f>=2){o++;f/=2}if(o+l>=h){a=0;o=h}else if(o+l>=1){a=(t*f-1)*Math.pow(2,i);o=o+l}else{a=t*Math.pow(2,l-1)*Math.pow(2,i);o=0}}for(;i>=8;e[r+d]=a&255,d+=p,a/=256,i-=8){}o=o<0;e[r+d]=o&255,d+=p,o/=256,u-=8){}e[r+d-p]|=m*128}},{}],54:[function(e,t,r){(function(e){t.exports=r;function r(e){if(!(this instanceof r))return new r(e);this.store=e;if(!this.store||!this.store.get||!this.store.put){throw new Error("First argument must be abstract-chunk-store compliant")}this.mem=[]}r.prototype.put=function(e,t,r){var n=this;n.mem[e]=t;n.store.put(e,t,function(t){n.mem[e]=null;if(r)r(t)})};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);var i=t&&t.offset||0;var s=t&&t.length&&i+t.length;var o=this.mem[e];if(o)return n(r,null,t?o.slice(i,s):o);this.store.get(e,t,r)};r.prototype.close=function(e){this.store.close(e)};r.prototype.destroy=function(e){this.store.destroy(e)};function n(t,r,n){e.nextTick(function(){if(t)t(r,n)})}}).call(this,e("_process"))},{_process:83}],55:[function(e,t,r){if(typeof Object.create==="function"){t.exports=function n(e,t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}else{t.exports=function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype;e.prototype=new r;e.prototype.constructor=e}}},{}],56:[function(e,t,r){var n=Array.isArray;var i=Object.prototype.toString;t.exports=n||function(e){return!!e&&"[object Array]"==i.call(e)}},{}],57:[function(e,t,r){t.exports=function(e){return!!(e!=null&&(e._isBuffer||e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)))}},{}],58:[function(e,t,r){"use strict";var n=e("fs");t.exports=function s(e,t){if(!t)return i(e);n.stat(e,function(e,r){if(e)return t(e);return t(null,r.isFile())})};t.exports.sync=i;function i(e){return n.existsSync(e)&&n.statSync(e).isFile()}},{fs:35}],59:[function(e,t,r){t.exports=s;s.strict=o;s.loose=a;var n=Object.prototype.toString;var i={"[object Int8Array]":true,"[object Int16Array]":true,"[object Int32Array]":true,"[object Uint8Array]":true,"[object Uint8ClampedArray]":true,"[object Uint16Array]":true,"[object Uint32Array]":true,"[object Float32Array]":true,"[object Float64Array]":true};function s(e){return o(e)||a(e)}function o(e){return e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array}function a(e){return i[n.call(e)]}},{}],60:[function(e,t,r){t.exports=Array.isArray||function(e){return Object.prototype.toString.call(e)=="[object Array]"}},{}],61:[function(e,t,r){"use strict";r.re=/^npm-debug\.log$|^\..*\.swp$|^\.DS_Store$|^\.AppleDouble$|^\.LSOverride$|^Icon[\r\?]?|^\._.*|^\.Spotlight-V100$|\.Trashes|^__MACOSX$|~$|^Thumbs\.db$|^ehthumbs\.db$|^Desktop\.ini$/; -r.is=function(e){return r.re.test(e)};r.not=r.isnt=function(e){return!r.is(e)}},{}],62:[function(e,t,r){(function(r){t.exports=o;t.exports.decode=o;t.exports.encode=a;var n=e("thirty-two");var i=e("xtend");var s=e("uniq");function o(e){var t={};var i=e.split("magnet:?")[1];var o=i&&i.length>=0?i.split("&"):[];o.forEach(function(e){var r=e.split("=");if(r.length!==2)return;var n=r[0];var i=r[1];if(n==="dn")i=decodeURIComponent(i).replace(/\+/g," ");if(n==="tr"||n==="xs"||n==="as"||n==="ws"){i=decodeURIComponent(i)}if(n==="kt")i=decodeURIComponent(i).split("+");if(t[n]){if(Array.isArray(t[n])){t[n].push(i)}else{var s=t[n];t[n]=[s,i]}}else{t[n]=i}});var a;if(t.xt){var f=Array.isArray(t.xt)?t.xt:[t.xt];f.forEach(function(e){if(a=e.match(/^urn:btih:(.{40})/)){t.infoHash=new r(a[1],"hex").toString("hex")}else if(a=e.match(/^urn:btih:(.{32})/)){var i=n.decode(a[1]);t.infoHash=new r(i,"binary").toString("hex")}})}if(t.dn)t.name=t.dn;if(t.kt)t.keywords=t.kt;if(typeof t.tr==="string")t.announce=[t.tr];else if(Array.isArray(t.tr))t.announce=t.tr;else t.announce=[];s(t.announce);t.urlList=[];if(typeof t.as==="string"||Array.isArray(t.as)){t.urlList=t.urlList.concat(t.as)}if(typeof t.ws==="string"||Array.isArray(t.ws)){t.urlList=t.urlList.concat(t.ws)}return t}function a(e){e=i(e);if(e.infoHash)e.xt="urn:btih:"+e.infoHash;if(e.name)e.dn=e.name;if(e.keywords)e.kt=e.keywords;if(e.announce)e.tr=e.announce;if(e.urlList){e.ws=e.urlList;delete e.as}var t="magnet:?";Object.keys(e).filter(function(e){return e.length===2}).forEach(function(r,n){var i=Array.isArray(e[r])?e[r]:[e[r]];i.forEach(function(e,i){if((n>0||i>0)&&(r!=="kt"||i===0))t+="&";if(r==="dn")e=encodeURIComponent(e).replace(/%20/g,"+");if(r==="tr"||r==="xs"||r==="as"||r==="ws"){e=encodeURIComponent(e)}if(r==="kt")e=encodeURIComponent(e);if(r==="kt"&&i>0)t+="+"+e;else t+=r+"="+e})});return t}}).call(this,e("buffer").Buffer)},{buffer:36,"thirty-two":114,uniq:119,xtend:126}],63:[function(e,t,r){t.exports=o;var n=e("inherits");var i=e("stream");var s=typeof window!=="undefined"&&window.MediaSource;n(o,i.Writable);function o(e,t){var r=this;if(!(r instanceof o))return new o(e,t);i.Writable.call(r,t);if(!s)throw new Error("web browser lacks MediaSource support");if(!t)t={};r._elem=e;r._mediaSource=new s;r._sourceBuffer=null;r._cb=null;r._type=t.type||a(t.extname);if(!r._type)throw new Error("missing `opts.type` or `opts.extname` options");r._elem.src=window.URL.createObjectURL(r._mediaSource);r._mediaSource.addEventListener("sourceopen",function(){if(s.isTypeSupported(r._type)){r._sourceBuffer=r._mediaSource.addSourceBuffer(r._type);r._sourceBuffer.addEventListener("updateend",r._flow.bind(r));r._flow()}else{r._mediaSource.endOfStream("decode")}});r.on("finish",function(){r._mediaSource.endOfStream()})}o.prototype._write=function(e,t,r){var n=this;if(!n._sourceBuffer){n._cb=function(i){if(i)return r(i);n._write(e,t,r)};return}if(n._sourceBuffer.updating){return r(new Error("Cannot append buffer while source buffer updating"))}n._sourceBuffer.appendBuffer(e);n._cb=r};o.prototype._flow=function(){var e=this;if(e._cb){e._cb(null)}};function a(e){if(!e)return null;if(e[0]!==".")e="."+e;return{".m4a":'audio/mp4; codecs="mp4a.40.5"',".m4v":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".mp3":"audio/mpeg",".mp4":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".webm":'video/webm; codecs="vorbis, vp8"'}[e]}},{inherits:55,stream:108}],64:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(!(this instanceof r))return new r(e,t);if(!t)t={};this.chunkLength=Number(e);if(!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[];this.closed=false;this.length=Number(t.length)||Infinity;if(this.length!==Infinity){this.lastChunkLength=this.length%this.chunkLength||this.chunkLength;this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1}}r.prototype.put=function(e,t,r){if(this.closed)return n(r,new Error("Storage is closed"));var i=e===this.lastChunkIndex;if(i&&t.length!==this.lastChunkLength){return n(r,new Error("Last chunk length must be "+this.lastChunkLength))}if(!i&&t.length!==this.chunkLength){return n(r,new Error("Chunk length must be "+this.chunkLength))}this.chunks[e]=t;n(r,null)};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);if(this.closed)return n(r,new Error("Storage is closed"));var i=this.chunks[e];if(!i)return n(r,new Error("Chunk not found"));if(!t)return n(r,null,i);var s=t.offset||0;var o=t.length||i.length-s;n(r,null,i.slice(s,o+s))};r.prototype.close=r.prototype.destroy=function(e){if(this.closed)return n(e,new Error("Storage is closed"));this.closed=true;this.chunks=null;n(e,null)};function n(t,r,n){e.nextTick(function(){if(t)t(r,n)})}}).call(this,e("_process"))},{_process:83}],65:[function(e,t,r){var n=function(e,t,r){this._byteOffset=t||0;if(e instanceof ArrayBuffer){this.buffer=e}else if(typeof e=="object"){this.dataView=e;if(t){this._byteOffset+=t}}else{this.buffer=new ArrayBuffer(e||0)}this.position=0;this.endianness=r==null?n.LITTLE_ENDIAN:r};t.exports=n;n.prototype={};n.prototype.save=function(e){var t=new Blob([this.buffer]);var r=window.webkitURL||window.URL;if(r&&r.createObjectURL){var n=r.createObjectURL(t);var i=document.createElement("a");i.setAttribute("href",n);i.setAttribute("download",e);i.click();r.revokeObjectURL(n)}else{throw"DataStream.save: Can't create object URL."}};n.BIG_ENDIAN=false;n.LITTLE_ENDIAN=true;n.prototype._dynamicSize=true;Object.defineProperty(n.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(e){if(!e){this._trimAlloc()}this._dynamicSize=e}});n.prototype._byteLength=0;Object.defineProperty(n.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}});Object.defineProperty(n.prototype,"buffer",{get:function(){this._trimAlloc();return this._buffer},set:function(e){this._buffer=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(n.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(n.prototype,"dataView",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset;this._buffer=e.buffer;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._byteOffset+e.byteLength}});n.prototype._realloc=function(e){if(!this._dynamicSize){return}var t=this._byteOffset+this.position+e;var r=this._buffer.byteLength;if(t<=r){if(t>this._byteLength){this._byteLength=t}return}if(r<1){r=1}while(t>r){r*=2}var n=new ArrayBuffer(r);var i=new Uint8Array(this._buffer);var s=new Uint8Array(n,0,i.length);s.set(i);this.buffer=n;this._byteLength=t};n.prototype._trimAlloc=function(){if(this._byteLength==this._buffer.byteLength){return}var e=new ArrayBuffer(this._byteLength);var t=new Uint8Array(e);var r=new Uint8Array(this._buffer,0,t.length);t.set(r);this.buffer=e};n.prototype.shift=function(e){var t=new ArrayBuffer(this._byteLength-e);var r=new Uint8Array(t);var n=new Uint8Array(this._buffer,e,r.length);r.set(n);this.buffer=t;this.position-=e};n.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t};n.prototype.isEof=function(){return this.position>=this._byteLength};n.prototype.mapInt32Array=function(e,t){this._realloc(e*4);var r=new Int32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.mapInt16Array=function(e,t){this._realloc(e*2);var r=new Int16Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};n.prototype.mapInt8Array=function(e){this._realloc(e*1);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};n.prototype.mapUint32Array=function(e,t){this._realloc(e*4);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.mapUint16Array=function(e,t){this._realloc(e*2);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};n.prototype.mapUint8Array=function(e){this._realloc(e*1);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};n.prototype.mapFloat64Array=function(e,t){this._realloc(e*8);var r=new Float64Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*8;return r};n.prototype.mapFloat32Array=function(e,t){this._realloc(e*4);var r=new Float32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.readInt32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Int32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readInt16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Int16Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readInt8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Int8Array(e);n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};n.prototype.readUint32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Uint32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readUint16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Uint16Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readUint8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Uint8Array(e);n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};n.prototype.readFloat64Array=function(e,t){e=e==null?this.byteLength-this.position/8:e;var r=new Float64Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readFloat32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Float32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.writeInt32Array=function(e,t){this._realloc(e.length*4);if(e instanceof Int32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0){n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength);this.mapInt32Array(e.length,t)}else{for(var r=0;r0;n.memcpy=function(e,t,r,n,i){var s=new Uint8Array(e,t,i);var o=new Uint8Array(r,n,i);s.set(o)};n.arrayToNative=function(e,t){if(t==this.endianness){return e}else{return this.flipArrayEndianness(e)}};n.nativeToEndian=function(e,t){if(this.endianness==t){return e}else{return this.flipArrayEndianness(e)}};n.flipArrayEndianness=function(e){var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(var r=0;ri;n--,i++){var s=t[i];t[i]=t[n];t[n]=s}}return e};n.prototype.failurePosition=0;n.prototype.readStruct=function(e){var t={},r,n,i;var s=this.position;for(var o=0;o>16);this.writeUint8((e&65280)>>8);this.writeUint8(e&255)};n.prototype.adjustUint32=function(e,t){var r=this.position;this.seek(e);this.writeUint32(t);this.seek(r)}},{}],66:[function(e,t,r){var n=e("./DataStream");var s=e("./descriptor");var o=e("./log");var a={ERR_NOT_ENOUGH_DATA:0,OK:1,boxCodes:["mdat","avcC","hvcC","ftyp","payl","vmhd","smhd","hmhd","dref","elst"],fullBoxCodes:["mvhd","tkhd","mdhd","hdlr","smhd","hmhd","nhmd","url ","urn ","ctts","cslg","stco","co64","stsc","stss","stsz","stz2","stts","stsh","mehd","trex","mfhd","tfhd","trun","tfdt","esds","subs","txtC"],containerBoxCodes:[["moov",["trak"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl"],["mvex",["trex"]],["moof",["traf"]],["traf",["trun"]],["vttc"],["tref"]],sampleEntryCodes:[{prefix:"Visual",types:["mp4v","avc1","avc2","avc3","avc4","avcp","drac","encv","mjp2","mvc1","mvc2","resv","s263","svc1","vc-1","hvc1","hev1"]},{prefix:"Audio",types:["mp4a","ac-3","alac","dra1","dtsc","dtse",,"dtsh","dtsl","ec-3","enca","g719","g726","m4ae","mlpa","raw ","samr","sawb","sawp","sevc","sqcp","ssmv","twos"]},{prefix:"Hint",types:["fdp ","m2ts","pm2t","prtp","rm2t","rrtp","rsrp","rtp ","sm2t","srtp"]},{prefix:"Metadata",types:["metx","mett","urim"]},{prefix:"Subtitle",types:["stpp","wvtt","sbtt","tx3g","stxt"]}],trackReferenceTypes:["scal"],initialize:function(){var e,t;var r;a.FullBox.prototype=new a.Box;a.ContainerBox.prototype=new a.Box;a.stsdBox.prototype=new a.FullBox;a.SampleEntry.prototype=new a.FullBox;a.TrackReferenceTypeBox.prototype=new a.Box;r=a.boxCodes.length;for(e=0;ee.byteLength){e.seek(n);o.w("BoxParser",'Not enough data in stream to parse the entire "'+f+'" box');return{code:a.ERR_NOT_ENOUGH_DATA,type:f,size:s,hdr_size:i}}if(a[f+"Box"]){r=new a[f+"Box"](s-i)}else{if(t){r=new a.SampleEntry(f,s-i)}else{r=new a.Box(f,s-i)}}r.hdr_size=i;r.start=n;r.fileStart=n+e.buffer.fileStart;r.parse(e);e.seek(n+s);return{code:a.OK,box:r,size:s}}};t.exports=a;a.initialize();a.Box.prototype.parse=function(e){if(this.type!="mdat"){this.data=e.readUint8Array(this.size)}else{e.seek(this.start+this.size+this.hdr_size)}};a.FullBox.prototype.parseFullHeader=function(e){this.version=e.readUint8();this.flags=e.readUint24();this.size-=4};a.ContainerBox.prototype.parse=function(e){var t;var r;var n;n=e.position;while(e.position=4){this.compatible_brands[t]=e.readString(4);this.size-=4;t++}};a.mvhdBox.prototype.parse=function(e){this.flags=0;this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.rate=e.readUint32();this.volume=e.readUint16()>>8;e.readUint16();e.readUint32Array(2);this.matrix=e.readUint32Array(9);e.readUint32Array(6);this.next_track_id=e.readUint32()};a.TKHD_FLAG_ENABLED=1;a.TKHD_FLAG_IN_MOVIE=2;a.TKHD_FLAG_IN_PREVIEW=4;a.tkhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint32()}e.readUint32Array(2);this.layer=e.readInt16();this.alternate_group=e.readInt16();this.volume=e.readInt16()>>8;e.readUint16();this.matrix=e.readInt32Array(9);this.width=e.readUint32();this.height=e.readUint32()};a.mdhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.language=e.readUint16();var t=[];t[0]=this.language>>10&31;t[1]=this.language>>5&31;t[2]=this.language&31;this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96);e.readUint16()};a.hdlrBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version===0){e.readUint32();this.handler=e.readString(4);e.readUint32Array(3);this.name=e.readCString()}else{this.data=e.readUint8Array(size)}};a.stsdBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);r=e.readUint32();for(i=1;i<=r;i++){t=a.parseOneBox(e,true);this.entries.push(t.box)}};a.avcCBox.prototype.parse=function(e){var t;var r;var n;this.configurationVersion=e.readUint8();this.AVCProfileIndication=e.readUint8();this.profile_compatibility=e.readUint8();this.AVCLevelIndication=e.readUint8();this.lengthSizeMinusOne=e.readUint8()&3;r=e.readUint8()&31;this.size-=6;this.SPS=new Array(r);for(t=0;t0){this.ext=e.readUint8Array(this.size)}};a.hvcCBox.prototype.parse=function(e){var t;var r;var n;var i;this.configurationVersion=e.readUint8();i=e.readUint8();this.general_profile_space=i>>6;this.general_tier_flag=(i&32)>>5;this.general_profile_idc=i&31;this.general_profile_compatibility=e.readUint32();this.general_constraint_indicator=e.readUint8Array(6);this.general_level_idc=e.readUint8();this.min_spatial_segmentation_idc=e.readUint16()&4095;this.parallelismType=e.readUint8()&3;this.chromaFormat=e.readUint8()&3;this.bitDepthLumaMinus8=e.readUint8()&7;this.bitDepthChromaMinus8=e.readUint8()&7;this.avgFrameRate=e.readUint16();i=e.readUint8();this.constantFrameRate=i>>6;this.numTemporalLayers=(i&13)>>3;this.temporalIdNested=(i&4)>>2;this.lengthSizeMinusOne=i&3;this.nalu_arrays=[];numOfArrays=e.readUint8();for(t=0;t>7;s.nalu_type=i&63;numNalus=e.readUint16();for(j=0;j>=1}t+=f(n,0);t+=".";if(this.hvcC.general_tier_flag===0){t+="L"}else{t+="H"}t+=this.hvcC.general_level_idc;var i=false;var s="";for(e=5;e>=0;e--){if(this.hvcC.general_constraint_indicator[e]||i){s="."+f(this.hvcC.general_constraint_indicator[e],0)+s;i=true}}t+=s}return t};a.mp4aBox.prototype.getCodec=function(){var e=a.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var t=this.esds.esd.getOTI();var r=this.esds.esd.getAudioConfig();return e+"."+f(t)+(r?"."+r:"")}else{return e}};a.esdsBox.prototype.parse=function(e){this.parseFullHeader(e);this.data=e.readUint8Array(this.size);this.size=0;var t=new s;this.esd=t.parseOneDescriptor(new n(this.data.buffer,0,n.BIG_ENDIAN))};a.txtCBox.prototype.parse=function(e){this.parseFullHeader(e);this.config=e.readCString()};a.cttsBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);t=e.readUint32();this.sample_counts=[];this.sample_offsets=[];if(this.version===0){for(r=0;rt&&this.flags&a.TFHD_FLAG_BASE_DATA_OFFSET){this.base_data_offset=e.readUint64();t+=8}else{this.base_data_offset=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_DESC){this.default_sample_description_index=e.readUint32();t+=4}else{this.default_sample_description_index=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_DUR){this.default_sample_duration=e.readUint32();t+=4}else{this.default_sample_duration=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_SIZE){this.default_sample_size=e.readUint32();t+=4}else{this.default_sample_size=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_FLAGS){this.default_sample_flags=e.readUint32();t+=4}else{this.default_sample_flags=0}};a.TRUN_FLAGS_DATA_OFFSET=1;a.TRUN_FLAGS_FIRST_FLAG=4;a.TRUN_FLAGS_DURATION=256;a.TRUN_FLAGS_SIZE=512;a.TRUN_FLAGS_FLAGS=1024;a.TRUN_FLAGS_CTS_OFFSET=2048;a.trunBox.prototype.parse=function(e){var t=0;this.parseFullHeader(e);this.sample_count=e.readUint32();t+=4;if(this.size>t&&this.flags&a.TRUN_FLAGS_DATA_OFFSET){this.data_offset=e.readInt32();t+=4}else{this.data_offset=0}if(this.size>t&&this.flags&a.TRUN_FLAGS_FIRST_FLAG){this.first_sample_flags=e.readUint32();t+=4}else{this.first_sample_flags=0}this.sample_duration=[];this.sample_size=[];this.sample_flags=[];this.sample_composition_time_offset=[];if(this.size>t){for(var r=0;r0){for(r=0;rn.MAX_SIZE){this.size+=8}o.d("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.position+(t||""));if(this.size>n.MAX_SIZE){e.writeUint32(1)}else{this.sizePosition=e.position;e.writeUint32(this.size)}e.writeString(this.type,null,4);if(this.size>n.MAX_SIZE){e.writeUint64(this.size)}};a.FullBox.prototype.writeHeader=function(e){this.size+=4;a.Box.prototype.writeHeader.call(this,e," v="+this.version+" f="+this.flags);e.writeUint8(this.version);e.writeUint24(this.flags)};a.Box.prototype.write=function(e){if(this.type==="mdat"){if(this.data){this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}}else{this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}};a.ContainerBox.prototype.write=function(e){this.size=0;this.writeHeader(e);for(var t=0;t>3}else{return null}};a.DecoderConfigDescriptor=function(e){a.Descriptor.call(this,t,e)};a.DecoderConfigDescriptor.prototype=new a.Descriptor;a.DecoderConfigDescriptor.prototype.parse=function(e){this.oti=e.readUint8();this.streamType=e.readUint8();this.bufferSize=e.readUint24();this.maxBitrate=e.readUint32();this.avgBitrate=e.readUint32();this.size-=13;this.parseRemainingDescriptors(e)};a.DecoderSpecificInfo=function(e){a.Descriptor.call(this,r,e)};a.DecoderSpecificInfo.prototype=new a.Descriptor;a.SLConfigDescriptor=function(e){a.Descriptor.call(this,i,e)};a.SLConfigDescriptor.prototype=new a.Descriptor;return this};t.exports=i},{"./log":69}],68:[function(e,t,r){var n=e("./box");var i=e("./DataStream");var s=e("./log");var o=function(e){this.stream=e;this.boxes=[];this.mdats=[];this.moofs=[];this.isProgressive=false;this.lastMoofIndex=0;this.lastBoxStartPosition=0;this.parsingMdat=null;this.moovStartFound=false;this.samplesDataSize=0;this.nextParsePosition=0};t.exports=o;o.prototype.mergeNextBuffer=function(){var e;if(this.stream.bufferIndex+1"+this.stream.buffer.byteLength+")");return true}else{return false}}else{return false}};o.prototype.parse=function(){var e;var t;var r;s.d("ISOFile","Starting parsing with buffer #"+this.stream.bufferIndex+" (fileStart: "+this.stream.buffer.fileStart+" - Length: "+this.stream.buffer.byteLength+") from position "+this.lastBoxStartPosition+" ("+(this.stream.buffer.fileStart+this.lastBoxStartPosition)+" in the file)");this.stream.seek(this.lastBoxStartPosition);while(true){if(this.parsingMdat!==null){r=this.parsingMdat;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){s.d("ISOFile","Found 'mdat' end in buffer #"+this.stream.bufferIndex);this.parsingMdat=null;continue}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex);return}}else{this.lastBoxStartPosition=this.stream.position;t=n.parseOneBox(this.stream);if(t.code===n.ERR_NOT_ENOUGH_DATA){if(t.type==="mdat"){r=new n[t.type+"Box"](t.size-t.hdr_size);this.parsingMdat=r;this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+this.stream.position;r.hdr_size=t.hdr_size;this.stream.buffer.usedBytes+=t.hdr_size;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){this.parsingMdat=null;continue}else{if(!this.moovStartFound){this.nextParsePosition=r.fileStart+r.size+r.hdr_size}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex)}return}}else{if(t.type==="moov"){this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}}else if(t.type==="free"){e=this.reposition(false,this.stream.buffer.fileStart+this.stream.position+t.size);if(e){continue}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size;return}}merged=this.mergeNextBuffer();if(merged){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength;continue}else{if(!t.type){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{if(this.moovStartFound){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size}}return}}}else{r=t.box;this.boxes.push(r);switch(r.type){case"mdat":this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+r.start;break;case"moof":this.moofs.push(r);break;case"moov":this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}default:if(this[r.type]!==undefined){s.w("ISOFile","Duplicate Box of type: "+r.type+", overriding previous occurrence")}this[r.type]=r;break}if(r.type==="mdat"){this.stream.buffer.usedBytes+=r.hdr_size}else{this.stream.buffer.usedBytes+=t.size}}}}};o.prototype.reposition=function(e,t){var r;r=this.findPosition(e,t);if(r!==-1){this.stream.buffer=this.stream.nextBuffers[r];this.stream.bufferIndex=r;this.stream.position=t-this.stream.buffer.fileStart;s.d("ISOFile","Repositioning parser at buffer position: "+this.stream.position);return true}else{return false}};o.prototype.findPosition=function(e,t){var r;var n=null;var i=-1;if(e===true){r=0}else{r=this.stream.bufferIndex}while(r=t){s.d("ISOFile","Found position in existing buffer #"+i);return i}else{return-1}}else{return-1}};o.prototype.findEndContiguousBuf=function(e){var t;var r;var n;r=this.stream.nextBuffers[e];if(this.stream.nextBuffers.length>e+1){for(t=e+1;t-1){this.moov.boxes.splice(r,1)}this.moov.mvex=null}this.moov.mvex=new n.mvexBox;this.moov.boxes.push(this.moov.mvex);this.moov.mvex.mehd=new n.mehdBox;this.moov.mvex.boxes.push(this.moov.mvex.mehd);this.moov.mvex.mehd.fragment_duration=this.initial_duration;for(t=0;t0?this.moov.traks[t].samples[0].duration:0;o.default_sample_size=0;o.default_sample_flags=1<<16}this.moov.write(e)};o.prototype.resetTables=function(){var e;var t,r,n,i,s,o,a,f;this.initial_duration=this.moov.mvhd.duration;this.moov.mvhd.duration=0;for(e=0;eg){_++;if(g<0){g=0}g+=a.sample_counts[_]}if(t>0){n.samples[t-1].duration=a.sample_deltas[_];x.dts=n.samples[t-1].dts+n.samples[t-1].duration}else{x.dts=0}if(f){if(t>y){b++;y+=f.sample_counts[b]}x.cts=n.samples[t].dts+f.sample_offsets[b]}else{x.cts=x.dts}if(u){if(t==u.sample_numbers[w]-1){x.is_rap=true;w++}else{x.is_rap=false}}else{x.is_rap=true}if(l){if(l.samples[subs_entry_index].sample_delta+last_subs_sample_index==t){x.subsamples=l.samples[subs_entry_index].subsamples;last_subs_sample_index+=l.samples[subs_entry_index].sample_delta}}}if(t>0)n.samples[t-1].duration=n.mdia.mdhd.duration-n.samples[t-1].dts}};o.prototype.updateSampleLists=function(){var e,t,r;var i,s,o,a;var f;var u,h,l,c,d;var p;while(this.lastMoofIndex0){p.dts=c.samples[c.samples.length-2].dts+c.samples[c.samples.length-2].duration}else{if(l.tfdt){p.dts=l.tfdt.baseMediaDecodeTime}else{p.dts=0}c.first_traf_merged=true}p.cts=p.dts;if(m.flags&n.TRUN_FLAGS_CTS_OFFSET){p.cts=p.dts+m.sample_composition_time_offset[r]}sample_flags=a;if(m.flags&n.TRUN_FLAGS_FLAGS){sample_flags=m.sample_flags[r]}else if(r===0&&m.flags&n.TRUN_FLAGS_FIRST_FLAG){sample_flags=m.first_sample_flags}p.is_rap=sample_flags>>16&1?false:true;var v=l.tfhd.flags&n.TFHD_FLAG_BASE_DATA_OFFSET?true:false;var g=l.tfhd.flags&n.TFHD_FLAG_DEFAULT_BASE_IS_MOOF?true:false;var _=m.flags&n.TRUN_FLAGS_DATA_OFFSET?true:false;var y=0;if(!v){if(!g){if(t===0){y=h.fileStart}else{y=f}}else{y=h.fileStart}}else{y=l.tfhd.base_data_offset}if(t===0&&r===0){if(_){p.offset=y+m.data_offset}else{p.offset=y}}else{p.offset=f}f=p.offset+p.size}}if(l.subs){var b=l.first_sample_index;for(t=0;t0){t+=","}t+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return t};o.prototype.getTrexById=function(e){var t;if(!this.originalMvex)return null;for(t=0;t=r.fileStart&&o.offset+o.alreadyRead=o){console.debug("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},i:function(t,r){if(i>=o){console.info("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},w:function(t,i){if(r>=o){console.warn("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",i)}},e:function(r,i){if(t>=o){console.error("["+n.getDurationString(new Date-e,1e3)+"]","["+r+"]",i)}}};return a}();t.exports=n;n.getDurationString=function(e,t){function r(e,t){var r=""+e;var n=r.split(".");while(n[0].length0){var r="";for(var i=0;i0)r+=",";r+="["+n.getDurationString(e.start(i))+","+n.getDurationString(e.end(i))+"]"}return r}else{return"(empty)"}}},{}],70:[function(e,t,r){var n=e("./box");var s=e("./DataStream");var o=e("./isofile");var a=e("./log");var f=function(){this.inputStream=null;this.nextBuffers=[];this.inputIsoFile=null;this.onMoovStart=null;this.moovStartSent=false;this.onReady=null;this.readySent=false;this.onSegment=null;this.onSamples=null;this.onError=null;this.sampleListBuilt=false;this.fragmentedTracks=[];this.extractedTracks=[];this.isFragmentationStarted=false;this.nextMoofNumber=0};t.exports=f;f.prototype.setSegmentOptions=function(e,t,r){var n=this.inputIsoFile.getTrackById(e);if(n){var i={};this.fragmentedTracks.push(i);i.id=e;i.user=t;i.trak=n;n.nextSample=0;i.segmentStream=null;i.nb_samples=1e3;i.rapAlignement=true;if(r){if(r.nbSamples)i.nb_samples=r.nbSamples;if(r.rapAlignement)i.rapAlignement=r.rapAlignement}}};f.prototype.unsetSegmentOptions=function(e){var t=-1;for(var r=0;r-1){this.fragmentedTracks.splice(t,1)}};f.prototype.setExtractionOptions=function(e,t,r){var n=this.inputIsoFile.getTrackById(e);if(n){var i={};this.extractedTracks.push(i);i.id=e;i.user=t;i.trak=n;n.nextSample=0;i.nb_samples=1e3;i.samples=[];if(r){if(r.nbSamples)i.nb_samples=r.nbSamples}}};f.prototype.unsetExtractionOptions=function(e){var t=-1;for(var r=0;r-1){this.extractedTracks.splice(t,1)}};f.prototype.createSingleSampleMoof=function(e){var t=new n.moofBox;var r=new n.mfhdBox;r.sequence_number=this.nextMoofNumber;this.nextMoofNumber++;t.boxes.push(r);var i=new n.trafBox;t.boxes.push(i);var s=new n.tfhdBox;i.boxes.push(s);s.track_id=e.track_id;s.flags=n.TFHD_FLAG_DEFAULT_BASE_IS_MOOF;var o=new n.tfdtBox;i.boxes.push(o);o.baseMediaDecodeTime=e.dts;var a=new n.trunBox;i.boxes.push(a);t.trun=a;a.flags=n.TRUN_FLAGS_DATA_OFFSET|n.TRUN_FLAGS_DURATION|n.TRUN_FLAGS_SIZE|n.TRUN_FLAGS_FLAGS|n.TRUN_FLAGS_CTS_OFFSET;a.data_offset=0;a.first_sample_flags=0;a.sample_count=1;a.sample_duration=[];a.sample_duration[0]=e.duration;a.sample_size=[];a.sample_size[0]=e.size;a.sample_flags=[];a.sample_flags[0]=0;a.sample_composition_time_offset=[];a.sample_composition_time_offset[0]=e.cts-e.dts;return t};f.prototype.createFragment=function(e,t,r,i){var o=this.inputIsoFile.getTrackById(t);var f=this.inputIsoFile.getSample(o,r);if(f==null){if(this.nextSeekPosition){this.nextSeekPosition=Math.min(o.samples[r].offset,this.nextSeekPosition)}else{this.nextSeekPosition=o.samples[r].offset}return null}var u=i||new s;u.endianness=s.BIG_ENDIAN;var h=this.createSingleSampleMoof(f);h.write(u);h.trun.data_offset=h.size+8;a.d("BoxWriter","Adjusting data_offset with new value "+h.trun.data_offset);u.adjustUint32(h.trun.data_offset_position,h.trun.data_offset);var l=new n.mdatBox;l.data=f.data;l.write(u);return u};ArrayBuffer.concat=function(e,t){a.d("ArrayBuffer","Trying to create a new buffer of size: "+(e.byteLength+t.byteLength));var r=new Uint8Array(e.byteLength+t.byteLength);r.set(new Uint8Array(e),0);r.set(new Uint8Array(t),e.byteLength);return r.buffer};f.prototype.reduceBuffer=function(e,t,r){var n;n=new Uint8Array(r);n.set(new Uint8Array(e,t,r));n.buffer.fileStart=e.fileStart+t;n.buffer.usedBytes=0;return n.buffer};f.prototype.insertBuffer=function(e){var t=true;for(var r=0;rn.byteLength){this.nextBuffers.splice(r,1);r--;continue}else{a.w("MP4Box","Buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+") already appended, ignoring")}}else{if(e.fileStart+e.byteLength<=n.fileStart){}else{e=this.reduceBuffer(e,0,n.fileStart-e.fileStart)}a.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.splice(r,0,e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}t=false;break}else if(e.fileStart0){e=this.reduceBuffer(e,i,s)}else{t=false;break}}}if(t){a.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.push(e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}};f.prototype.processSamples=function(){var e;var t;if(this.isFragmentationStarted&&this.onSegment!==null){for(e=0;e=t.samples.length){a.i("MP4Box","Sending fragmented data on track #"+r.id+" for samples ["+(t.nextSample-r.nb_samples)+","+(t.nextSample-1)+"]");if(this.onSegment){this.onSegment(r.id,r.user,r.segmentStream.buffer,t.nextSample)}r.segmentStream=null;if(r!==this.fragmentedTracks[e]){break}}}}}if(this.onSamples!==null){for(e=0;e=t.samples.length){a.d("MP4Box","Sending samples on track #"+i.id+" for sample "+t.nextSample);if(this.onSamples){this.onSamples(i.id,i.user,i.samples)}i.samples=[];if(i!==this.extractedTracks[e]){break}}}}}};f.prototype.appendBuffer=function(e){var t;var r;if(e===null||e===undefined){throw"Buffer must be defined and non empty"}if(e.fileStart===undefined){throw"Buffer must have a fileStart property"}if(e.byteLength===0){a.w("MP4Box","Ignoring empty buffer (fileStart: "+e.fileStart+")");return}e.usedBytes=0;this.insertBuffer(e);if(!this.inputStream){if(this.nextBuffers.length>0){r=this.nextBuffers[0];if(r.fileStart===0){this.inputStream=new s(r,0,s.BIG_ENDIAN);this.inputStream.nextBuffers=this.nextBuffers;this.inputStream.bufferIndex=0}else{a.w("MP4Box","The first buffer should have a fileStart of 0");return}}else{a.w("MP4Box","No buffer to start parsing from");return}}if(!this.inputIsoFile){this.inputIsoFile=new o(this.inputStream)}this.inputIsoFile.parse();if(this.inputIsoFile.moovStartFound&&!this.moovStartSent){this.moovStartSent=true;if(this.onMoovStart)this.onMoovStart()}if(this.inputIsoFile.moov){if(!this.sampleListBuilt){this.inputIsoFile.buildSampleLists();this.sampleListBuilt=true}this.inputIsoFile.updateSampleLists();if(this.onReady&&!this.readySent){var n=this.getInfo();this.readySent=true;this.onReady(n)}this.processSamples();if(this.nextSeekPosition){t=this.nextSeekPosition;this.nextSeekPosition=undefined}else{t=this.inputIsoFile.nextParsePosition}var i=this.inputIsoFile.findPosition(true,t);if(i!==-1){t=this.inputIsoFile.findEndContiguousBuf(i)}a.i("MP4Box","Next buffer to fetch should have a fileStart position of "+t);return t}else{if(this.inputIsoFile!==null){return this.inputIsoFile.nextParsePosition}else{return 0}}};f.prototype.getInfo=function(){var e={};var t;var r;var n;var s=new Date(4,0,1,0,0,0,0).getTime();e.duration=this.inputIsoFile.moov.mvhd.duration;e.timescale=this.inputIsoFile.moov.mvhd.timescale;e.isFragmented=this.inputIsoFile.moov.mvex!=null;if(e.isFragmented&&this.inputIsoFile.moov.mvex.mehd){e.fragment_duration=this.inputIsoFile.moov.mvex.mehd.fragment_duration}else{e.fragment_duration=0}e.isProgressive=this.inputIsoFile.isProgressive;e.hasIOD=this.inputIsoFile.moov.iods!=null;e.brands=[];e.brands.push(this.inputIsoFile.ftyp.major_brand);e.brands=e.brands.concat(this.inputIsoFile.ftyp.compatible_brands);e.created=new Date(s+this.inputIsoFile.moov.mvhd.creation_time*1e3);e.modified=new Date(s+this.inputIsoFile.moov.mvhd.modification_time*1e3);e.tracks=[];e.audioTracks=[];e.videoTracks=[];e.subtitleTracks=[];e.metadataTracks=[];e.hintTracks=[];e.otherTracks=[];for(i=0;ie*i.timescale){f=r.samples[n-1].offset;h=n-1;break}if(t&&i.is_rap){s=i.offset;o=i.cts;u=n}}if(t){r.nextSample=u;a.i("MP4Box","Seeking to RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+a.getDurationString(o,l)+" and offset: "+s);return{offset:s,time:o/l}}else{r.nextSample=h;a.i("MP4Box","Seeking to non-RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+a.getDurationString(e)+" and offset: "+s);return{offset:f,time:e}}};f.prototype.seek=function(e,t){var r=this.inputIsoFile.moov;var n;var i;var s;var o={offset:Infinity,time:Infinity};if(!this.inputIsoFile.moov){throw"Cannot seek: moov not received!"}else{for(s=0;s1e4)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);var f=(t[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return r*a;case"days":case"day":case"d":return r*o;case"hours":case"hour":case"hrs":case"hr":case"h":return r*s;case"minutes":case"minute":case"mins":case"min":case"m":return r*i;case"seconds":case"second":case"secs":case"sec":case"s":return r*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r}}function u(e){if(e>=o)return Math.round(e/o)+"d";if(e>=s)return Math.round(e/s)+"h";if(e>=i)return Math.round(e/i)+"m";if(e>=n)return Math.round(e/n)+"s";return e+"ms"}function h(e){return l(e,o,"day")||l(e,s,"hour")||l(e,i,"minute")||l(e,n,"second")||e+" ms"}function l(e,t,r){if(e0?[e["url-list"]]:[]}t.urlList=(e["url-list"]||[]).map(function(e){return e.toString()});var a=e.info.files||[e.info];t.files=a.map(function(e,r){var n=[].concat(t.name,e["path.utf-8"]||e.path||[]).map(function(e){return e.toString()});return{path:i.join.apply(null,[i.sep].concat(n)).slice(1),name:n[n.length-1],length:e.length,offset:a.slice(0,r).reduce(u,0)}});t.length=a.reduce(u,0);var f=t.files[t.files.length-1];t.pieceLength=e.info["piece length"];t.lastPieceLength=(f.offset+f.length)%t.pieceLength||t.pieceLength;t.pieces=h(e.info.pieces);return t}function f(e){var t={info:e.info};t["announce-list"]=e.announce.map(function(e){if(!t.announce)t.announce=e;e=new r(e,"utf8");return[e]});if(e.created){t["creation date"]=e.created.getTime()/1e3|0}if(e.urlList){t["url-list"]=e.urlList}return n.encode(t)}function u(e,t){return e+t.length}function h(e){var t=[];for(var r=0;r=0;n--){var i=e[n];if(i==="."){e.splice(n,1)}else if(i===".."){e.splice(n,1);r++}else if(r){e.splice(n,1);r--}}if(t){for(;r--;r){e.unshift("..")}}return e}var n=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var i=function(e){return n.exec(e).slice(1)};r.resolve=function(){var r="",n=false;for(var i=arguments.length-1;i>=-1&&!n;i--){var o=i>=0?arguments[i]:e.cwd();if(typeof o!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!o){continue}r=o+"/"+r;n=o.charAt(0)==="/"}r=t(s(r.split("/"),function(e){return!!e}),!n).join("/");return(n?"/":"")+r||"."};r.normalize=function(e){var n=r.isAbsolute(e),i=o(e,-1)==="/";e=t(s(e.split("/"),function(e){return!!e}),!n).join("/");if(!e&&!n){e="."}if(e&&i){e+="/"}return(n?"/":"")+e};r.isAbsolute=function(e){return e.charAt(0)==="/"};r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(s(e,function(e,t){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))};r.relative=function(e,t){e=r.resolve(e).substr(1);t=r.resolve(t).substr(1);function n(e){var t=0;for(;t=0;r--){if(e[r]!=="")break}if(t>r)return[];return e.slice(t,r-t+1)}var i=n(e.split("/"));var s=n(t.split("/"));var o=Math.min(i.length,s.length);var a=o;for(var f=0;f1){for(var r=1;r0;return h(i,o,a,function(e){if(!r)r=e;if(e)n.forEach(l);if(o)return;n.forEach(l);t(r)})});return e.reduce(c)};t.exports=d},{"end-of-stream":46,fs:35,once:73}],85:[function(t,r,n){(function(t){(function(i){var s=typeof n=="object"&&n&&!n.nodeType&&n;var o=typeof r=="object"&&r&&!r.nodeType&&r;var a=typeof t=="object"&&t;if(a.global===a||a.window===a||a.self===a){i=a}var f,u=2147483647,h=36,l=1,c=26,d=38,p=700,m=72,v=128,g="-",_=/^xn--/,y=/[^\x20-\x7E]/,b=/[\x2E\u3002\uFF0E\uFF61]/g,w={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},S=h-l,x=Math.floor,k=String.fromCharCode,E;function A(e){throw RangeError(w[e])}function U(e,t){var r=e.length;var n=[];while(r--){n[r]=t(e[r])}return n}function T(e,t){var r=e.split("@");var n="";if(r.length>1){n=r[0]+"@";e=r[1]}e=e.replace(b,".");var i=e.split(".");var s=U(i,t).join(".");return n+s}function I(e){var t=[],r=0,n=e.length,i,s;while(r=55296&&i<=56319&&r65535){e-=65536;t+=k(e>>>10&1023|55296);e=56320|e&1023}t+=k(e);return t}).join("")}function B(e){if(e-48<10){return e-22}if(e-65<26){return e-65}if(e-97<26){return e-97}return h}function C(e,t){return e+22+75*(e<26)-((t!=0)<<5)}function R(e,t,r){var n=0;e=r?x(e/p):e>>1;e+=x(e/t);for(;e>S*c>>1;n+=h){e=x(e/S)}return x(n+(S+1)*e/(e+d))}function P(e){var t=[],r=e.length,n,i=0,s=v,o=m,a,f,d,p,_,y,b,w,S;a=e.lastIndexOf(g);if(a<0){a=0}for(f=0;f=128){A("not-basic")}t.push(e.charCodeAt(f))}for(d=a>0?a+1:0;d=r){A("invalid-input")}b=B(e.charCodeAt(d++));if(b>=h||b>x((u-i)/_)){A("overflow")}i+=b*_;w=y<=o?l:y>=o+c?c:y-o;if(bx(u/S)){A("overflow")}_*=S}n=t.length+1;o=R(i-p,n,p==0);if(x(i/n)>u-s){A("overflow")}s+=x(i/n);i%=n;t.splice(i++,0,s)}return L(t)}function F(e){var t,r,n,i,s,o,a,f,d,p,_,y=[],b,w,S,E;e=I(e);b=e.length;t=v;r=0;s=m;for(o=0;o=t&&_x((u-r)/w)){A("overflow")}r+=(a-t)*w;t=a;for(o=0;ou){A("overflow")}if(_==t){for(f=r,d=h;;d+=h){p=d<=s?l:d>=s+c?c:d-s;if(f0&&u>f){u=f}for(var h=0;h=0){d=l.substr(0,c);p=l.substr(c+1)}else{d=l;p=""}m=decodeURIComponent(d);v=decodeURIComponent(p);if(!n(o,m)){o[m]=v}else if(i(o[m])){o[m].push(v)}else{o[m]=[o[m],v]}}return o};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}},{}],87:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,a){t=t||"&";r=r||"=";if(e===null){e=undefined}if(typeof e==="object"){return s(o(e),function(o){var a=encodeURIComponent(n(o))+r;if(i(e[o])){return s(e[o],function(e){return a+encodeURIComponent(n(e))}).join(t)}else{return a+encodeURIComponent(n(e[o]))}}).join(t)}if(!a)return"";return encodeURIComponent(n(a))+r+encodeURIComponent(n(e))};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};function s(e,t){if(e.map)return e.map(t);var r=[];for(var n=0;n0){if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var o=new Error("stream.unshift() after end event");e.emit("error",o)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)S(e)}k(e,t)}}else if(!i){t.reading=false}return v(t)}function v(e){return!e.ended&&(e.needReadable||e.length=g){e=g}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function y(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(e===null||isNaN(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=_(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else{return t.length}}return e}p.prototype.read=function(e){l("read",e);var t=this._readableState;var r=e;if(typeof e!=="number"||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){l("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)C(this);else S(this);return null}e=y(e,t);if(e===0&&t.ended){if(t.length===0)C(this);return null}var n=t.needReadable;l("need readable",n);if(t.length===0||t.length-e0)i=B(e,t);else i=null;if(i===null){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)C(this);if(i!==null)this.emit("data",i);return i};function b(e,t){var r=null;if(!s.isBuffer(t)&&typeof t!=="string"&&t!==null&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function w(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;S(e)}function S(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){l("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)n(x,e);else x(e)}}function x(e){l("emit readable");e.emit("readable");L(e)}function k(e,t){if(!t.readingMore){t.readingMore=true;n(E,e,t)}}function E(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(i)a=r.join("");else if(r.length===1)a=r[0];else a=s.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;n(R,t,e)}}function R(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function P(e,t){for(var r=0,n=e.length;r-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e};function p(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=new i(t,r)}return t}function m(e,t,r,n,s){r=p(t,r,n);if(i.isBuffer(r))n="buffer";var o=t.objectMode?1:r.length;t.length+=o;var a=t.length0;e+=1);return e};var o=function(e,t){for(var r=t>>2;r>2]|=128<<24-(t%4<<3);e[((t>>2)+2&~15)+14]=r>>29;e[((t>>2)+2&~15)+15]=r<<3};var f=function(e,t,r,n,i){var s=this,o,a=i%4,f=n%4,u=n-f;if(u>0){switch(a){case 0:e[i+3|0]=s.charCodeAt(r);case 1:e[i+2|0]=s.charCodeAt(r+1);case 2:e[i+1|0]=s.charCodeAt(r+2);case 3:e[i|0]=s.charCodeAt(r+3)}}for(o=a;o>2]=s.charCodeAt(r+o)<<24|s.charCodeAt(r+o+1)<<16|s.charCodeAt(r+o+2)<<8|s.charCodeAt(r+o+3)}switch(f){case 3:e[i+u+1|0]=s.charCodeAt(r+u+2);case 2:e[i+u+2|0]=s.charCodeAt(r+u+1);case 1:e[i+u+3|0]=s.charCodeAt(r+u)}};var u=function(e,t,r,n,i){var s=this,o,a=i%4,f=n%4,u=n-f;if(u>0){switch(a){case 0:e[i+3|0]=s[r];case 1:e[i+2|0]=s[r+1];case 2:e[i+1|0]=s[r+2];case 3:e[i|0]=s[r+3]}}for(o=4-a;o>2]=s[r+o]<<24|s[r+o+1]<<16|s[r+o+2]<<8|s[r+o+3]}switch(f){case 3:e[i+u+1|0]=s[r+u+2];case 2:e[i+u+2|0]=s[r+u+1];case 1:e[i+u+3|0]=s[r+u]}};var h=function(e,t,r,n,s){var o=this,a,f=s%4,u=n%4,h=n-u;var l=new Uint8Array(i.readAsArrayBuffer(o.slice(r,r+n)));if(h>0){switch(f){case 0:e[s+3|0]=l[0];case 1:e[s+2|0]=l[1];case 2:e[s+1|0]=l[2];case 3:e[s|0]=l[3]}}for(a=4-f;a>2]=l[a]<<24|l[a+1]<<16|l[a+2]<<8|l[a+3]}switch(u){case 3:e[s+h+1|0]=l[h+2];case 2:e[s+h+2|0]=l[h+1];case 1:e[s+h+3|0]=l[h]}};var l=function(e){switch(r.getDataType(e)){case"string":return f.bind(e);case"array":return u.bind(e);case"buffer":return u.bind(e);case"arraybuffer":return u.bind(new Uint8Array(e));case"view":return u.bind(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));case"blob":return h.bind(e)}};var c=function(e,t){switch(r.getDataType(e)){case"string":return e.slice(t);case"array":return e.slice(t);case"buffer":return e.slice(t);case"arraybuffer":return e.slice(t);case"view":return e.buffer.slice(t)}};var d=function(e){var t,r,n="0123456789abcdef",i=[],s=new Uint8Array(e);for(t=0;t>4&15)+n.charAt(r>>0&15)}return i.join("")};var p=function(e){var t;if(e<=65536)return 65536;if(e<16777216){for(t=1;t0){throw new Error("Chunk size must be a multiple of 128 bit")}t.maxChunkLen=e;t.padMaxChunkLen=s(e);t.heap=new ArrayBuffer(p(t.padMaxChunkLen+320+20));t.h32=new Int32Array(t.heap);t.h8=new Int8Array(t.heap);t.core=new n._core({Int32Array:Int32Array,DataView:DataView},{},t.heap);t.buffer=null};m(e||64*1024);var v=function(e,t){var r=new Int32Array(e,t+320,5);r[0]=1732584193;r[1]=-271733879;r[2]=-1732584194;r[3]=271733878;r[4]=-1009589776};var g=function(e,r){ -var n=s(e);var i=new Int32Array(t.heap,0,n>>2);o(i,e);a(i,e,r);return n};var _=function(e,r,n){l(e)(t.h8,t.h32,r,n,0)};var y=function(e,r,n,i,s){var o=n;if(s){o=g(n,i)}_(e,r,n);t.core.hash(o,t.padMaxChunkLen)};var b=function(e,t){var r=new Int32Array(e,t+320,5);var n=new Int32Array(5);var i=new DataView(n.buffer);i.setInt32(0,r[0],false);i.setInt32(4,r[1],false);i.setInt32(8,r[2],false);i.setInt32(12,r[3],false);i.setInt32(16,r[4],false);return n};var w=this.rawDigest=function(e){var r=e.byteLength||e.length||e.size||0;v(t.heap,t.padMaxChunkLen);var n=0,i=t.maxChunkLen,s;for(n=0;r>n+i;n+=i){y(e,n,i,r,false)}y(e,n,r-n,r,true);return b(t.heap,t.padMaxChunkLen)};this.digest=this.digestFromString=this.digestFromBuffer=this.digestFromArrayBuffer=function(e){return d(w(e).buffer)}}n._core=function o(e,t,r){"use asm";var n=new e.Int32Array(r);function i(e,t){e=e|0;t=t|0;var r=0,i=0,s=0,o=0,a=0,f=0,u=0,h=0,l=0,c=0,d=0,p=0,m=0,v=0;s=n[t+320>>2]|0;a=n[t+324>>2]|0;u=n[t+328>>2]|0;l=n[t+332>>2]|0;d=n[t+336>>2]|0;for(r=0;(r|0)<(e|0);r=r+64|0){o=s;f=a;h=u;c=l;p=d;for(i=0;(i|0)<64;i=i+4|0){v=n[r+i>>2]|0;m=((s<<5|s>>>27)+(a&u|~a&l)|0)+((v+d|0)+1518500249|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[e+i>>2]=v}for(i=e+64|0;(i|0)<(e+80|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a&u|~a&l)|0)+((v+d|0)+1518500249|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+80|0;(i|0)<(e+160|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a^u^l)|0)+((v+d|0)+1859775393|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+160|0;(i|0)<(e+240|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a&u|a&l|u&l)|0)+((v+d|0)-1894007588|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+240|0;(i|0)<(e+320|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a^u^l)|0)+((v+d|0)-899497514|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}s=s+o|0;a=a+f|0;u=u+h|0;l=l+c|0;d=d+p|0}n[t+320>>2]=s;n[t+324>>2]=a;n[t+328>>2]=u;n[t+332>>2]=l;n[t+336>>2]=d}return{hash:i}};if(typeof t!=="undefined"){t.exports=n}else if(typeof window!=="undefined"){window.Rusha=n}if(typeof FileReaderSync!=="undefined"){var i=new FileReaderSync,s=new n(4*1024*1024);self.onmessage=function a(e){var t,r=e.data.data;try{t=s.digest(r);self.postMessage({id:e.data.id,hash:t})}catch(n){self.postMessage({id:e.data.id,error:n.name})}}}})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],103:[function(e,t,r){(function(r){t.exports=u;var n=e("xtend");var i=e("http");var s=e("https");var o=e("once");var a=e("unzip-response");var f=e("url");function u(e,t){e=typeof e==="string"?{url:e}:n(e);t=o(t);if(e.url)h(e);if(e.headers==null)e.headers={};if(e.maxRedirects==null)e.maxRedirects=10;var r=e.body;e.body=undefined;if(r&&!e.method)e.method="POST";var f=Object.keys(e.headers).some(function(e){return e.toLowerCase()==="accept-encoding"});if(!f)e.headers["accept-encoding"]="gzip, deflate";var l=e.protocol==="https:"?s:i;var c=l.request(e,function(r){if(r.statusCode>=300&&r.statusCode<400&&"location"in r.headers){e.url=r.headers.location;h(e);r.resume();e.maxRedirects-=1;if(e.maxRedirects>0)u(e,t);else t(new Error("too many redirects"));return}t(null,typeof a==="function"?a(r):r)});c.on("error",t);c.end(r);return c}t.exports.concat=function(e,t){return u(e,function(e,n){if(e)return t(e);var i=[];n.on("data",function(e){i.push(e)});n.on("end",function(){t(null,r.concat(i),n)})})};["get","post","put","patch","head","delete"].forEach(function(e){t.exports[e]=function(t,r){if(typeof t==="string")t={url:t};t.method=e.toUpperCase();return u(t,r)}});function h(e){var t=f.parse(e.url);if(t.hostname)e.hostname=t.hostname;if(t.port)e.port=t.port;if(t.protocol)e.protocol=t.protocol;e.path=t.path;delete e.url}}).call(this,e("buffer").Buffer)},{buffer:36,http:109,https:52,once:73,"unzip-response":34,url:120,xtend:126}],104:[function(e,t,r){(function(r){t.exports=l;var n=e("debug")("simple-peer");var i=e("get-browser-rtc");var s=e("hat");var o=e("inherits");var a=e("is-typedarray");var f=e("once");var u=e("stream");var h=e("typedarray-to-buffer");o(l,u.Duplex);function l(e){var t=this;if(!(t instanceof l))return new l(e);t._debug("new peer %o",e);if(!e)e={};e.allowHalfOpen=false;if(e.highWaterMark==null)e.highWaterMark=1024*1024;u.Duplex.call(t,e);t.initiator=e.initiator||false;t.channelConfig=e.channelConfig||l.channelConfig;t.channelName=e.channelName||s(160);if(!e.initiator)t.channelName=null;t.config=e.config||l.config;t.constraints=e.constraints||l.constraints;t.reconnectTimer=e.reconnectTimer||0;t.sdpTransform=e.sdpTransform||function(e){return e};t.stream=e.stream||false;t.trickle=e.trickle!==undefined?e.trickle:true;t.destroyed=false;t.connected=false;t.remoteAddress=undefined;t.remoteFamily=undefined;t.remotePort=undefined;t.localAddress=undefined;t.localPort=undefined;t._wrtc=e.wrtc||i();if(!t._wrtc){if(typeof window==="undefined"){throw new Error("No WebRTC support: Specify `opts.wrtc` option in this environment")}else{throw new Error("No WebRTC support: Not a supported browser")}}t._maxBufferedAmount=e.highWaterMark;t._pcReady=false;t._channelReady=false;t._iceComplete=false;t._channel=null;t._pendingCandidates=[];t._chunk=null;t._cb=null;t._interval=null;t._reconnectTimeout=null;t._pc=new t._wrtc.RTCPeerConnection(t.config,t.constraints);t._pc.oniceconnectionstatechange=t._onIceConnectionStateChange.bind(t);t._pc.onsignalingstatechange=t._onSignalingStateChange.bind(t);t._pc.onicecandidate=t._onIceCandidate.bind(t);if(t.stream)t._pc.addStream(t.stream);t._pc.onaddstream=t._onAddStream.bind(t);if(t.initiator){t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)});t._pc.onnegotiationneeded=f(t._createOffer.bind(t));if(typeof window==="undefined"||!window.webkitRTCPeerConnection){t._pc.onnegotiationneeded()}}else{t._pc.ondatachannel=t._setupData.bind(t)}t.on("finish",function(){if(t.connected){setTimeout(function(){t._destroy()},100)}else{t.once("connect",function(){setTimeout(function(){t._destroy()},100)})}})}l.WEBRTC_SUPPORT=!!i();l.config={iceServers:[{url:"stun:23.21.150.121",urls:"stun:23.21.150.121"}]};l.constraints={};l.channelConfig={};Object.defineProperty(l.prototype,"bufferSize",{get:function(){var e=this;return e._channel&&e._channel.bufferedAmount||0}});l.prototype.address=function(){var e=this;return{port:e.localPort,family:"IPv4",address:e.localAddress}};l.prototype.signal=function(e){var t=this;if(t.destroyed)throw new Error("cannot signal after peer is destroyed");if(typeof e==="string"){try{e=JSON.parse(e)}catch(r){e={}}}t._debug("signal()");function n(e){try{t._pc.addIceCandidate(new t._wrtc.RTCIceCandidate(e),c,t._onError.bind(t))}catch(r){t._destroy(new Error("error adding candidate: "+r.message))}}if(e.sdp){t._pc.setRemoteDescription(new t._wrtc.RTCSessionDescription(e),function(){if(t.destroyed)return;if(t._pc.remoteDescription.type==="offer")t._createAnswer();t._pendingCandidates.forEach(n);t._pendingCandidates=[]},t._onError.bind(t))}if(e.candidate){if(t._pc.remoteDescription)n(e.candidate);else t._pendingCandidates.push(e.candidate)}if(!e.sdp&&!e.candidate){t._destroy(new Error("signal() called with invalid signal data"))}};l.prototype.send=function(e){var t=this;if(!a.strict(e)&&!(e instanceof ArrayBuffer)&&!r.isBuffer(e)&&typeof e!=="string"&&(typeof Blob==="undefined"||!(e instanceof Blob))){e=JSON.stringify(e)}if(r.isBuffer(e)&&!a.strict(e)){e=new Uint8Array(e)}var n=e.length||e.byteLength||e.size;t._channel.send(e);t._debug("write: %d bytes",n)};l.prototype.destroy=function(e){var t=this;t._destroy(null,e)};l.prototype._destroy=function(e,t){var r=this;if(r.destroyed)return;if(t)r.once("close",t);r._debug("destroy (error: %s)",e&&e.message);r.readable=r.writable=false;if(!r._readableState.ended)r.push(null);if(!r._writableState.finished)r.end();r.destroyed=true;r.connected=false;r._pcReady=false;r._channelReady=false;r._chunk=null;r._cb=null;clearInterval(r._interval);clearTimeout(r._reconnectTimeout);if(r._pc){try{r._pc.close()}catch(e){}r._pc.oniceconnectionstatechange=null;r._pc.onsignalingstatechange=null;r._pc.onicecandidate=null}if(r._channel){try{r._channel.close()}catch(e){}r._channel.onmessage=null;r._channel.onopen=null;r._channel.onclose=null}r._pc=null;r._channel=null;if(e)r.emit("error",e);r.emit("close")};l.prototype._setupData=function(e){var t=this;t._channel=e.channel;t.channelName=t._channel.label;t._channel.binaryType="arraybuffer";t._channel.onmessage=t._onChannelMessage.bind(t);t._channel.onopen=t._onChannelOpen.bind(t);t._channel.onclose=t._onChannelClose.bind(t)};l.prototype._read=function(){};l.prototype._write=function(e,t,r){var n=this;if(n.destroyed)return r(new Error("cannot write after peer is destroyed"));if(n.connected){try{n.send(e)}catch(i){return n._onError(i)}if(n._channel.bufferedAmount>n._maxBufferedAmount){n._debug("start backpressure: bufferedAmount %d",n._channel.bufferedAmount);n._cb=r}else{r(null)}}else{n._debug("write before connect");n._chunk=e;n._cb=r}};l.prototype._createOffer=function(){var e=this;if(e.destroyed)return;e._pc.createOffer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,c,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.offerConstraints)};l.prototype._createAnswer=function(){var e=this;if(e.destroyed)return;e._pc.createAnswer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,c,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.answerConstraints)};l.prototype._onIceConnectionStateChange=function(){var e=this;if(e.destroyed)return;var t=e._pc.iceGatheringState;var r=e._pc.iceConnectionState;e._debug("iceConnectionStateChange %s %s",t,r);e.emit("iceConnectionStateChange",t,r);if(r==="connected"||r==="completed"){clearTimeout(e._reconnectTimeout);e._pcReady=true;e._maybeReady()}if(r==="disconnected"){if(e.reconnectTimer){clearTimeout(e._reconnectTimeout);e._reconnectTimeout=setTimeout(function(){e._destroy()},e.reconnectTimer)}else{e._destroy()}}if(r==="closed"){e._destroy()}};l.prototype._maybeReady=function(){var e=this;e._debug("maybeReady pc %s channel %s",e._pcReady,e._channelReady);if(e.connected||e._connecting||!e._pcReady||!e._channelReady)return;e._connecting=true;if(typeof window!=="undefined"&&!!window.mozRTCPeerConnection){e._pc.getStats(null,function(e){var r=[];e.forEach(function(e){r.push(e)});t(r)},e._onError.bind(e))}else{e._pc.getStats(function(e){var r=[];e.result().forEach(function(e){var t={};e.names().forEach(function(r){t[r]=e.stat(r)});t.id=e.id;t.type=e.type;t.timestamp=e.timestamp;r.push(t)});t(r)})}function t(t){t.forEach(function(t){if(t.type==="remotecandidate"){e.remoteAddress=t.ipAddress;e.remotePort=Number(t.portNumber);e.remoteFamily="IPv4";e._debug("connect remote: %s:%s (%s)",e.remoteAddress,e.remotePort,e.remoteFamily)}else if(t.type==="localcandidate"&&t.candidateType==="host"){e.localAddress=t.ipAddress;e.localPort=Number(t.portNumber);e._debug("connect local: %s:%s",e.localAddress,e.localPort)}});e._connecting=false;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(r){return e._onError(r)}e._chunk=null;e._debug('sent chunk from "write before connect"');var n=e._cb;e._cb=null;n(null)}e._interval=setInterval(function(){if(!e._cb||!e._channel||e._channel.bufferedAmount>e._maxBufferedAmount)return;e._debug("ending backpressure: bufferedAmount %d",e._channel.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref();e._debug("connect");e.emit("connect")}};l.prototype._onSignalingStateChange=function(){var e=this;if(e.destroyed)return;e._debug("signalingStateChange %s",e._pc.signalingState);e.emit("signalingStateChange",e._pc.signalingState)};l.prototype._onIceCandidate=function(e){var t=this;if(t.destroyed)return;if(e.candidate&&t.trickle){t.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}})}else if(!e.candidate){t._iceComplete=true;t.emit("_iceComplete")}};l.prototype._onChannelMessage=function(e){var t=this;if(t.destroyed)return;var r=e.data;t._debug("read: %d bytes",r.byteLength||r.length);if(r instanceof ArrayBuffer){r=h(new Uint8Array(r));t.push(r)}else{try{r=JSON.parse(r)}catch(n){}t.emit("data",r)}};l.prototype._onChannelOpen=function(){var e=this;if(e.connected||e.destroyed)return;e._debug("on channel open");e._channelReady=true;e._maybeReady()};l.prototype._onChannelClose=function(){var e=this;if(e.destroyed)return;e._debug("on channel close");e._destroy()};l.prototype._onAddStream=function(e){var t=this;if(t.destroyed)return;t._debug("on add stream");t.emit("stream",e.stream)};l.prototype._onError=function(e){var t=this;if(t.destroyed)return;t._debug("error %s",e.message||e);t._destroy(e)};l.prototype._debug=function(){var e=this;var t=[].slice.call(arguments);var r=e.channelName&&e.channelName.substring(0,7);t[0]="["+r+"] "+t[0];n.apply(null,t)};function c(){}}).call(this,{isBuffer:e("../is-buffer/index.js")})},{"../is-buffer/index.js":57,debug:42,"get-browser-rtc":50,hat:51,inherits:55,"is-typedarray":59,once:73,stream:108,"typedarray-to-buffer":118}],105:[function(e,t,r){var n=e("rusha");var i=new n;var s=window.crypto||window.msCrypto||{};var o=s.subtle||s.webkitSubtle;var a=i.digest.bind(i);try{o.digest({name:"sha-1"},new Uint8Array).catch(function(){o=false})}catch(f){o=false}function u(e,t){if(!o){setTimeout(t,0,a(e));return}if(typeof e==="string"){e=h(e)}o.digest({name:"sha-1"},e).then(function r(e){t(l(new Uint8Array(e)))},function n(r){t(a(e))})}function h(e){var t=e.length;var r=new Uint8Array(t);for(var n=0;n>>4).toString(16));r.push((i&15).toString(16))}return r.join("")}t.exports=u;t.exports.sync=a},{rusha:102}],106:[function(e,t,r){(function(r){t.exports=h;var n=e("debug")("simple-websocket");var i=e("inherits");var s=e("is-typedarray");var o=e("stream");var a=e("typedarray-to-buffer");var f=e("ws");var u=typeof window!=="undefined"?window.WebSocket:f;i(h,o.Duplex);function h(e,t){var r=this;if(!(r instanceof h))return new h(e,t);if(!t)t={};n("new websocket: %s %o",e,t);t.allowHalfOpen=false;if(t.highWaterMark==null)t.highWaterMark=1024*1024;o.Duplex.call(r,t);r.url=e;r.connected=false;r.destroyed=false;r._maxBufferedAmount=t.highWaterMark;r._chunk=null;r._cb=null;r._interval=null;r._ws=new u(r.url);r._ws.binaryType="arraybuffer";r._ws.onopen=r._onOpen.bind(r);r._ws.onmessage=r._onMessage.bind(r);r._ws.onclose=r._onClose.bind(r);r._ws.onerror=function(){r._onError(new Error("connection error to "+r.url))};r.on("finish",function(){if(r.connected){setTimeout(function(){r._destroy()},100)}else{r.once("connect",function(){setTimeout(function(){r._destroy()},100)})}})}h.WEBSOCKET_SUPPORT=!!u;h.prototype.send=function(e){var t=this;if(!s.strict(e)&&!(e instanceof ArrayBuffer)&&!r.isBuffer(e)&&typeof e!=="string"&&(typeof Blob==="undefined"||!(e instanceof Blob))){e=JSON.stringify(e)}var i=e.length||e.byteLength||e.size;t._ws.send(e);n("write: %d bytes",i)};h.prototype.destroy=function(e){var t=this;t._destroy(null,e)};h.prototype._destroy=function(e,t){var r=this;if(r.destroyed)return;if(t)r.once("close",t);n("destroy (error: %s)",e&&e.message);this.readable=this.writable=false;if(!r._readableState.ended)r.push(null);if(!r._writableState.finished)r.end();r.connected=false;r.destroyed=true;clearInterval(r._interval);r._interval=null;r._chunk=null;r._cb=null;if(r._ws){var i=r._ws;var s=function(){i.onclose=null;r.emit("close")};if(i.readyState===u.CLOSED){s()}else{try{i.onclose=s;i.close()}catch(e){s()}}i.onopen=null;i.onmessage=null;i.onerror=null}r._ws=null;if(e)r.emit("error",e)};h.prototype._read=function(){};h.prototype._write=function(e,t,r){var i=this;if(i.destroyed)return r(new Error("cannot write after socket is destroyed"));if(i.connected){try{i.send(e)}catch(s){return i._onError(s)}if(typeof f!=="function"&&i._ws.bufferedAmount>i._maxBufferedAmount){n("start backpressure: bufferedAmount %d",i._ws.bufferedAmount);i._cb=r}else{r(null)}}else{n("write before connect");i._chunk=e;i._cb=r}};h.prototype._onMessage=function(e){var t=this;if(t.destroyed)return;var i=e.data;n("read: %d bytes",i.byteLength||i.length);if(i instanceof ArrayBuffer){i=a(new Uint8Array(i));t.push(i)}else if(r.isBuffer(i)){t.push(i)}else{try{i=JSON.parse(i)}catch(s){}t.emit("data",i)}};h.prototype._onOpen=function(){var e=this;if(e.connected||e.destroyed)return;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(t){return e._onError(t)}e._chunk=null;n('sent chunk from "write before connect"');var r=e._cb;e._cb=null;r(null)}if(typeof f!=="function"){e._interval=setInterval(function(){if(!e._cb||!e._ws||e._ws.bufferedAmount>e._maxBufferedAmount){return}n("ending backpressure: bufferedAmount %d",e._ws.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref()}n("connect");e.emit("connect")};h.prototype._onClose=function(){var e=this;if(e.destroyed)return;n("on close");e._destroy()};h.prototype._onError=function(e){var t=this;if(t.destroyed)return;n("error: %s",e.message||e);t._destroy(e)}}).call(this,{isBuffer:e("../is-buffer/index.js")})},{"../is-buffer/index.js":57,debug:42,inherits:55,"is-typedarray":59,stream:108,"typedarray-to-buffer":118,ws:34}],107:[function(e,t,r){var n=1;var i=65535;var s=4;var o=function(){n=n+1&i};var a=setInterval(o,1e3/s|0);if(a.unref)a.unref();t.exports=function(e){var t=s*(e||5);var r=[0];var o=1;var a=n-1&i;return function(e){var f=n-a&i;if(f>t)f=t;a=n;while(f--){if(o===t)o=0;r[o]=r[o===0?t-1:o-1];o++}if(e)r[o-1]+=e;var u=r[o-1];var h=r.lengthe._pos){var o=r.substr(e._pos);if(e._charset==="x-user-defined"){var a=new i(o.length);for(var u=0;ue._pos){e.push(new i(new Uint8Array(h.result.slice(e._pos))));e._pos=h.result.byteLength}};h.onload=function(){e.push(null)};h.readAsArrayBuffer(r);break}if(e._xhr.readyState===f.DONE&&e._mode!=="ms-stream"){e.push(null)}}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{"./capability":110,_process:83,buffer:36,inherits:55,stream:108}],113:[function(e,t,r){var n=e("buffer").Buffer;var i=n.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function s(e){if(e&&!i(e)){throw new Error("Unknown encoding: "+e)}}var o=r.StringDecoder=function(e){this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,"");s(e);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=f;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=u;break;default:this.write=a;return}this.charBuffer=new n(6);this.charReceived=0;this.charLength=0};o.prototype.write=function(e){var t="";while(this.charLength){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;e.copy(this.charBuffer,this.charReceived,0,r);this.charReceived+=r;if(this.charReceived=55296&&n<=56319){this.charLength+=this.surrogateSize;t="";continue}this.charReceived=this.charLength=0;if(e.length===0){return t}break}this.detectIncompleteChar(e);var i=e.length;if(this.charLength){e.copy(this.charBuffer,0,e.length-this.charReceived,i);i-=this.charReceived}t+=e.toString(this.encoding,0,i);var i=t.length-1;var n=t.charCodeAt(i);if(n>=55296&&n<=56319){var s=this.surrogateSize;this.charLength+=s;this.charReceived+=s;this.charBuffer.copy(this.charBuffer,s,0,s);e.copy(this.charBuffer,0,0,s);return t.substring(0,i)}return t};o.prototype.detectIncompleteChar=function(e){var t=e.length>=3?3:e.length;for(;t>0;t--){var r=e[e.length-t];if(t==1&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t};o.prototype.end=function(e){var t="";if(e&&e.length)t=this.write(e);if(this.charReceived){var r=this.charReceived;var n=this.charBuffer;var i=this.encoding;t+=n.slice(0,r).toString(i)}return t};function a(e){return e.toString(this.encoding)}function f(e){this.charReceived=e.length%2;this.charLength=this.charReceived?2:0}function u(e){this.charReceived=e.length%3;this.charLength=this.charReceived?3:0}},{buffer:36}],114:[function(e,t,r){var n=e("./thirty-two");r.encode=n.encode;r.decode=n.decode},{"./thirty-two":115}],115:[function(e,t,r){(function(e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";var n=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,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,255,255,255,255,255,255,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,255,255,255,255,255];function i(e){var t=Math.floor(e.length/5);return e.length%5==0?t:t+1}r.encode=function(r){var n=0;var s=0;var o=0;var a=0;var f=new e(i(r)*8);if(!e.isBuffer(r)){r=new e(r)}while(n3){a=u&255>>o;o=(o+5)%8;a=a<>8-o;n++}else{a=u>>8-(o+5)&31;o=(o+5)%8;if(o==0)n++}f[s]=t.charCodeAt(a);s++}for(n=s;n>>r;a[o]=s;o++;s=255&i<<8-r}}else{throw new Error("Invalid input - it is not base32 encoded string")}}return a.slice(0,o)}}).call(this,e("buffer").Buffer)},{buffer:36}],116:[function(e,t,r){(function(r,n){t.exports=c;var i=e("debug")("torrent-discovery");var s=e("bittorrent-dht/client");var o=e("events").EventEmitter;var a=e("xtend/mutable");var f=e("inherits");var u=e("run-parallel");var h=e("re-emitter"); -var l=e("bittorrent-tracker/client");f(c,o);function c(e){var t=this;if(!(t instanceof c))return new c(e);o.call(t);a(t,{announce:[],dht:typeof s==="function",rtcConfig:null,peerId:null,port:0,tracker:true,wrtc:null},e);t.infoHash=null;t.infoHashHex=null;t.torrent=null;t._externalDHT=typeof t.dht==="object";t._performedDHTLookup=false;if(!t.peerId)throw new Error("peerId required");if(!r.browser&&!t.port)throw new Error("port required");if(t.dht)t._createDHT(t.dhtPort)}c.prototype.setTorrent=function(e){var t=this;if(!t.infoHash&&n.isBuffer(e)||typeof e==="string"){t.infoHash=typeof e==="string"?new n(e,"hex"):e}else if(!t.torrent&&e&&e.infoHash){t.torrent=e;t.infoHash=typeof e.infoHash==="string"?new n(e.infoHash,"hex"):e.infoHash}else{return}t.infoHashHex=t.infoHash.toString("hex");i("setTorrent %s",t.infoHashHex);if(t.tracker&&t.tracker!==true){t.tracker.torrentLength=e.length}else{t._createTracker()}if(t.dht){if(t.dht.ready)t._dhtLookupAndAnnounce();else t.dht.on("ready",t._dhtLookupAndAnnounce.bind(t))}};c.prototype.updatePort=function(e){var t=this;if(e===t.port)return;t.port=e;if(t.dht&&t.infoHash){t._performedDHTLookup=false;t._dhtLookupAndAnnounce()}if(t.tracker&&t.tracker!==true){t.tracker.stop();t.tracker.destroy(function(){t._createTracker()})}};c.prototype.stop=function(e){var t=this;var r=[];if(t.tracker&&t.tracker!==true){t.tracker.stop();r.push(function(e){t.tracker.destroy(e)})}if(!t._externalDHT&&t.dht&&t.dht!==true){r.push(function(e){t.dht.destroy(e)})}u(r,e)};c.prototype._createDHT=function(e){var t=this;if(!t._externalDHT)t.dht=new s;h(t.dht,t,["error","warning"]);t.dht.on("peer",function(e,r){if(r===t.infoHashHex)t.emit("peer",e)});if(!t._externalDHT)t.dht.listen(e)};c.prototype._createTracker=function(){var e=this;if(!e.tracker)return;var t=e.torrent?a({announce:[]},e.torrent):{infoHash:e.infoHashHex,announce:[]};if(e.announce)t.announce=t.announce.concat(e.announce);var r={rtcConfig:e.rtcConfig,wrtc:e.wrtc};e.tracker=new l(e.peerId,e.port,t,r);h(e.tracker,e,["peer","warning","error"]);e.tracker.on("update",function(t){e.emit("trackerAnnounce",t)});e.tracker.start()};c.prototype._dhtLookupAndAnnounce=function(){var e=this;if(e._performedDHTLookup)return;e._performedDHTLookup=true;i("dht lookup");e.dht.lookup(e.infoHash,function(t){if(t||!e.port)return;i("dht announce");e.dht.announce(e.infoHash,e.port,function(){i("dht announce complete");e.emit("dhtAnnounce")})})}}).call(this,e("_process"),e("buffer").Buffer)},{_process:83,"bittorrent-dht/client":34,"bittorrent-tracker/client":23,buffer:36,debug:42,events:47,inherits:55,"re-emitter":90,"run-parallel":101,"xtend/mutable":127}],117:[function(e,t,r){(function(e){t.exports=n;var r=1<<14;function n(e){if(!(this instanceof n))return new n(e);this.length=e;this.missing=e;this.sources=null;this._chunks=Math.ceil(e/r);this._remainder=e%r||r;this._buffered=0;this._buffer=null;this._cancellations=null;this._reservations=0;this._flushed=false}n.BLOCK_LENGTH=r;n.prototype.chunkLength=function(e){return e===this._chunks-1?this._remainder:r};n.prototype.chunkOffset=function(e){return e*r};n.prototype.reserve=function(){if(!this.init())return-1;if(this._cancellations.length)return this._cancellations.pop();if(this._reservations",'"',"`"," ","\r","\n"," "],h=["{","}","|","\\","^","`"].concat(u),l=["'"].concat(h),c=["%","/","?",";","#"].concat(l),d=["/","?","#"],p=255,m=/^[+a-z0-9A-Z_-]{0,63}$/,v=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:true,"javascript:":true},_={javascript:true,"javascript:":true},y={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},b=e("querystring");function w(e,t,r){if(e&&i.isObject(e)&&e instanceof s)return e;var n=new s;n.parse(e,t,r);return n}s.prototype.parse=function(e,t,r){if(!i.isString(e)){throw new TypeError("Parameter 'url' must be a string, not "+typeof e)}var s=e.indexOf("?"),a=s!==-1&&s127){F+="x"}else{F+=P[O]}}if(!F.match(m)){var D=C.slice(0,U);var N=C.slice(U+1);var z=P.match(v);if(z){D.push(z[1]);N.unshift(z[2])}if(N.length){w="/"+N.join(".")+w}this.hostname=D.join(".");break}}}}if(this.hostname.length>p){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!B){this.hostname=n.toASCII(this.hostname)}var j=this.port?":"+this.port:"";var H=this.hostname||"";this.host=H+j;this.href+=this.host;if(B){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(w[0]!=="/"){w="/"+w}}}if(!g[k]){for(var U=0,R=l.length;U0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}r.search=e.search;r.query=e.query;if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.href=r.format();return r}if(!x.length){r.pathname=null;if(r.search){r.path="/"+r.search}else{r.path=null}r.href=r.format();return r}var A=x.slice(-1)[0];var U=(r.host||e.host||x.length>1)&&(A==="."||A==="..")||A==="";var T=0;for(var I=x.length;I>=0;I--){A=x[I];if(A==="."){x.splice(I,1)}else if(A===".."){x.splice(I,1);T++}else if(T){x.splice(I,1);T--}}if(!w&&!S){for(;T--;T){x.unshift("..")}}if(w&&x[0]!==""&&(!x[0]||x[0].charAt(0)!=="/")){x.unshift("")}if(U&&x.join("/").substr(-1)!=="/"){x.push("")}var L=x[0]===""||x[0]&&x[0].charAt(0)==="/";if(k){r.hostname=r.host=L?"":x.length?x.shift():"";var E=r.host&&r.host.indexOf("@")>0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}w=w||r.host&&x.length;if(w&&!L){x.unshift("")}if(!x.length){r.pathname=null;r.path=null}else{r.pathname=x.join("/")}if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.auth=e.auth||r.auth;r.slashes=r.slashes||e.slashes;r.href=r.format();return r};s.prototype.parseHost=function(){var e=this.host;var t=a.exec(e);if(t){t=t[0];if(t!==":"){this.port=t.substr(1)}e=e.substr(0,e.length-t.length)}if(e)this.hostname=e}},{"./util":121,punycode:85,querystring:88}],121:[function(e,t,r){"use strict";t.exports={isString:function(e){return typeof e==="string"},isObject:function(e){return typeof e==="object"&&e!==null},isNull:function(e){return e===null},isNullOrUndefined:function(e){return e==null}}},{}],122:[function(e,t,r){(function(r){var n=e("bencode");var i=e("bitfield");var s=e("events").EventEmitter;var o=e("inherits");var a=e("simple-sha1");var f=1e7;var u=1e3;var h=16*1024;t.exports=function(e){o(t,s);function t(t){s.call(this);this._wire=t;this._metadataComplete=false;this._metadataSize=null;this._remainingRejects=null;this._fetching=false;this._bitfield=new i(0,{grow:u});if(r.isBuffer(e)){this.setMetadata(e)}}t.prototype.name="ut_metadata";t.prototype.onHandshake=function(e,t,r){this._infoHash=e;this._infoHashHex=e.toString("hex")};t.prototype.onExtendedHandshake=function(e){if(!e.m||!e.m.ut_metadata){return this.emit("warning",new Error("Peer does not support ut_metadata"))}if(!e.metadata_size){return this.emit("warning",new Error("Peer does not have metadata"))}if(e.metadata_size>f){return this.emit("warning",new Error("Peer gave maliciously large metadata size"))}this._metadataSize=e.metadata_size;this._numPieces=Math.ceil(this._metadataSize/h);this._remainingRejects=this._numPieces*2;if(this._fetching){this._requestPieces()}};t.prototype.onMessage=function(e){var t,r;try{var i=e.toString();var s=i.indexOf("ee")+2;t=n.decode(i.substring(0,s));r=e.slice(s)}catch(o){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,r,t.total_size);break;case 2:this._onReject(t.piece);break}};t.prototype.fetch=function(){if(this._metadataComplete){return}this._fetching=true;if(this._metadataSize){this._requestPieces()}};t.prototype.cancel=function(){this._fetching=false};t.prototype.setMetadata=function(e){if(this._metadataComplete)return true;try{var t=n.decode(e).info;if(t){e=n.encode(t)}}catch(r){}if(this._infoHashHex&&this._infoHashHex!==a.sync(e)){return false}this.cancel();this.metadata=e;this._metadataComplete=true;this._metadataSize=this.metadata.length;this._wire.extendedHandshake.metadata_size=this._metadataSize;this.emit("metadata",n.encode({info:n.decode(this.metadata)}));return true};t.prototype._send=function(e,t){var i=n.encode(e);if(r.isBuffer(t)){i=r.concat([i,t])}this._wire.extended("ut_metadata",i)};t.prototype._request=function(e){this._send({msg_type:0,piece:e})};t.prototype._data=function(e,t,r){var n={msg_type:1,piece:e};if(typeof r==="number"){n.total_size=r}this._send(n,t)};t.prototype._reject=function(e){this._send({msg_type:2,piece:e})};t.prototype._onRequest=function(e){if(!this._metadataComplete){this._reject(e);return}var t=e*h;var r=t+h;if(r>this._metadataSize){r=this._metadataSize}var n=this.metadata.slice(t,r);this._data(e,n,this._metadataSize)};t.prototype._onData=function(e,t,r){if(t.length>h){return}t.copy(this.metadata,e*h);this._bitfield.set(e);this._checkDone()};t.prototype._onReject=function(e){if(this._remainingRejects>0&&this._fetching){this._request(e);this._remainingRejects-=1}else{this.emit("warning",new Error('Peer sent "reject" too much'))}};t.prototype._requestPieces=function(){this.metadata=new r(this._metadataSize);for(var e=0;e0){this._requestPieces()}else{this.emit("warning",new Error("Peer sent invalid metadata"))}};return t}}).call(this,e("buffer").Buffer)},{bencode:11,bitfield:15,buffer:36,events:47,inherits:55,"simple-sha1":105}],123:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(n("noDeprecation")){return e}var r=false;function i(){if(!r){if(n("throwDeprecation")){throw new Error(t)}else if(n("traceDeprecation")){console.trace(t)}else{console.warn(t)}r=true}return e.apply(this,arguments)}return i}function n(t){try{if(!e.localStorage)return false}catch(r){return false}var n=e.localStorage[t];if(null==n)return false;return String(n).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],124:[function(e,t,r){var n=e("debug")("videostream");var i=e("mp4box");var s=.01;var o=60;t.exports=function(e,t,r){r=r||{};var f=r.debugTrack||-1;var u=[];function h(){t.addEventListener("waiting",S);t.addEventListener("timeupdate",E)}h();var l=false;function c(e){l=true;t.removeEventListener("waiting",S);t.removeEventListener("timeupdate",E);if(p.readyState==="open")p.endOfStream(e)}function d(e){var r=e.buffer.buffered;var i=t.currentTime;var a=-1;for(var f=0;fi){break}else if(a>=0||i<=h){a=h}}var l=a-i;if(l<0)l=0;n("Buffer length: %f",l);return l<=o}var p=new MediaSource;p.addEventListener("sourceopen",function(){w(0)});t.src=window.URL.createObjectURL(p);var m=new i;m.onError=function(e){n("MP4Box error: %s",e.message);if(b){b()}if(p.readyState==="open"){c("decode")}};var v=false;var g={};m.onReady=function(e){n("MP4 info: %o",e);e.tracks.forEach(function(e){var t;if(e.video){t="video/mp4"}else if(e.audio){t="audio/mp4"}else{return}t+='; codecs="'+e.codec+'"';if(MediaSource.isTypeSupported(t)){var r=p.addSourceBuffer(t);var n={buffer:r,arrayBuffers:[],meta:e,ended:false};r.addEventListener("updateend",A.bind(null,n));m.setSegmentOptions(e.id,null,{nbSamples:e.video?1:100});g[e.id]=n}});if(Object.keys(g).length===0){c("decode");return}var t=m.initializeSegmentation();t.forEach(function(e){k(g[e.id],e.buffer);if(e.id===f){a("init-track-"+f+".mp4",[e.buffer]);u.push(e.buffer)}});v=true};m.onSegment=function(e,t,r,n){var i=g[e];k(i,r,n===i.meta.nb_samples);if(e===f&&u){u.push(r);if(n>1e3){a("track-"+f+".mp4",u);u=null}}};var _;var y=null;var b=null;function w(t){if(t===e.length){m.flush();return}if(y&&t===_){var r=y;setTimeout(function(){if(y===r)y.resume()});return}if(y){y.destroy();b()}_=t;var i={start:_,end:e.length-1};y=e.createReadStream(i);function s(e){y.pause();var t=e.toArrayBuffer();t.fileStart=_;_+=t.byteLength;var r;try{r=m.appendBuffer(t)}catch(i){n("MP4Box threw exception: %s",i.message);if(p.readyState==="open"){c("decode")}y.destroy();b();return}w(r)}y.on("data",s);function o(){b();w(_)}y.on("end",o);function a(e){n("Stream error: %s",e.message);if(p.readyState==="open"){c("network")}}y.on("error",a);b=function(){y.removeListener("data",s);y.removeListener("end",o);y.removeListener("error",a);y=null;b=null}}function S(){if(v){x(t.currentTime)}}function x(e){if(l)h();var t=m.seek(e,true);n("Seeking to time: %d",e);n("Seeked file offset: %d",t.offset);w(t.offset)}function k(e,t,r){e.arrayBuffers.push({buffer:t,ended:r||false});A(e)}function E(){Object.keys(g).forEach(function(e){var t=g[e];if(t.blocked){A(t)}})}function A(e){if(e.buffer.updating)return;e.blocked=!d(e);if(e.blocked)return;if(e.arrayBuffers.length===0)return;var t=e.arrayBuffers.shift();var r=false;try{e.buffer.appendBuffer(t.buffer);e.ended=t.ended;r=true}catch(i){n("SourceBuffer error: %s",i.message);c("decode");return}if(r){U()}}function U(){if(p.readyState!=="open"){return}var e=Object.keys(g).every(function(e){var t=g[e];return t.ended&&!t.buffer.updating});if(e){c()}}};function a(e,t){var r=new Blob(t);var n=URL.createObjectURL(r);var i=document.createElement("a");i.setAttribute("href",n);i.setAttribute("download",e);i.click()}},{debug:42,mp4box:70}],125:[function(e,t,r){t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=="function")throw new TypeError("need wrapper function");Object.keys(e).forEach(function(t){r[t]=e[t]});return r;function r(){var t=new Array(arguments.length);for(var r=0;r0)return new Array(e+(/\./.test(t)?2:1)).join(r)+t;return t+""}},{}],129:[function(e,t,r){t.exports={name:"webtorrent",description:"Streaming torrent client",version:"0.63.1",author:{name:"Feross Aboukhadijeh",email:"feross@feross.org",url:"http://feross.org/"},bin:{webtorrent:"./bin/cmd.js"},browser:{"./lib/server.js":false,"bittorrent-dht/client":false,"fs-chunk-store":"memory-chunk-store","load-ip-set":false,ut_pex:false},bugs:{url:"https://github.com/feross/webtorrent/issues"},dependencies:{"addr-to-ip-port":"^1.0.1",bitfield:"^1.0.2","bittorrent-dht":"^4.0.4","bittorrent-swarm":"^5.0.0","chunk-store-stream":"^2.0.0",clivas:"^0.2.0","create-torrent":"^3.4.0","cross-spawn-async":"^2.0.0",debug:"^2.1.0","end-of-stream":"^1.0.0",executable:"^2.1.0","fs-chunk-store":"^1.3.4",hat:"0.0.3","immediate-chunk-store":"^1.0.7",inherits:"^2.0.1",inquirer:"^0.11.0","load-ip-set":"^1.0.3",mediasource:"^1.0.0","memory-chunk-store":"^1.2.0",mime:"^1.2.11",minimist:"^1.1.0",moment:"^2.8.3",multistream:"^2.0.2","network-address":"^1.0.0","parse-torrent":"^5.1.0","path-exists":"^2.1.0","pretty-bytes":"^2.0.1",pump:"^1.0.0","random-iterate":"^1.0.1","range-parser":"^1.0.2","re-emitter":"^1.0.0","run-parallel":"^1.0.0","simple-sha1":"^2.0.0",speedometer:"^1.0.0",thunky:"^0.1.0","torrent-discovery":"^3.0.0","torrent-piece":"^1.0.0",uniq:"^1.0.1",ut_metadata:"^2.1.0",ut_pex:"^1.0.1",videostream:"^1.1.4","windows-no-runnable":"0.0.6",xtend:"^4.0.0","zero-fill":"^2.2.0"},devDependencies:{"bittorrent-tracker":"^6.0.0",brfs:"^1.2.0",browserify:"^12.0.1",finalhandler:"^0.4.0","run-auto":"^1.0.0","serve-static":"^1.9.3","simple-get":"^1.0.0",standard:"^5.1.0",tape:"^4.0.0","uglify-js":"^2.4.15",zelda:"^2.0.0",zuul:"^3.0.0"},homepage:"http://webtorrent.io",keywords:["torrent","bittorrent","bittorrent client","streaming","download","webrtc","webrtc data","webtorrent","mad science"],license:"MIT",main:"index.js",optionalDependencies:{"airplay-js":"^0.2.3",chromecasts:"^1.5.3",nodebmc:"0.0.5"},repository:{type:"git",url:"git://github.com/feross/webtorrent.git"},scripts:{build:"browserify -s WebTorrent -e ./ | uglifyjs -m > webtorrent.min.js","build-debug":"browserify -s WebTorrent -e ./ > webtorrent.debug.js",size:"npm run build && cat webtorrent.min.js | gzip | wc -c",test:"standard && node ./bin/test.js","test-browser":"zuul -- test/basic.js","test-browser-local":"zuul --local -- test/basic.js","test-node":"tape test/*.js"}}},{}],130:[function(e,t,r){(function(r,n,i){t.exports=w;var s=e("create-torrent");var o=e("debug")("webtorrent");var a=e("bittorrent-dht/client");var f=e("events").EventEmitter;var u=e("xtend");var h=e("hat");var l=e("inherits");var c=e("load-ip-set");var d=e("run-parallel");var p=e("parse-torrent");var m=e("speedometer");var v=e("zero-fill");var g=e("path");var _=e("./lib/torrent");l(w,f);var y=e("./package.json").version;var b=y.match(/([0-9]+)/g).slice(0,2).map(v(2)).join("");function w(e){var t=this;if(!(t instanceof w))return new w(e);if(!e)e={};f.call(t);if(!o.enabled)t.setMaxListeners(0);t.destroyed=false;t.torrentPort=e.torrentPort||0;t.tracker=e.tracker!==undefined?e.tracker:true;t._rtcConfig=e.rtcConfig;t._wrtc=e.wrtc||n.WRTC;t.torrents=[];t.downloadSpeed=m();t.uploadSpeed=m();t.peerId=e.peerId===undefined?new i("-WW"+b+"-"+h(48),"utf8"):typeof e.peerId==="string"?new i(e.peerId,"hex"):e.peerId;t.peerIdHex=t.peerId.toString("hex");t.nodeId=e.nodeId===undefined?new i(h(160),"hex"):typeof e.nodeId==="string"?new i(e.nodeId,"hex"):e.nodeId;t.nodeIdHex=t.nodeId.toString("hex");if(e.dht!==false&&typeof a==="function"){t.dht=new a(u({nodeId:t.nodeId},e.dht));t.dht.listen(e.dhtPort)}o("new webtorrent (peerId %s, nodeId %s)",t.peerIdHex,t.nodeIdHex);if(typeof c==="function"){c(e.blocklist,{headers:{"user-agent":"WebTorrent/"+y+" (http://webtorrent.io)"}},function(e,r){if(e)return t.error("Failed to load blocklist: "+e.message);t.blocked=r;s()})}else r.nextTick(s);function s(){if(t.destroyed)return;t.ready=true;t.emit("ready")}}Object.defineProperty(w.prototype,"ratio",{get:function(){var e=this;var t=e.torrents.reduce(function(e,t){return e+t.uploaded},0);var r=e.torrents.reduce(function(e,t){return e+t.downloaded},0)||1;return t/r}});w.prototype.get=function(e){var t=this;if(e instanceof _)return e;var r;try{r=p(e)}catch(n){}if(!r)return null;if(!r.infoHash)throw new Error("Invalid torrent identifier");for(var i=0,s=t.torrents.length;i=0)y();else if(l.indexOf(g)>=0)w();else if(c.indexOf(g)>=0)S();else if(d.indexOf(g)>=0)x();else v(r,new Error('Unsupported file type "'+g+'": Cannot append to DOM'));function y(){if(!p){return v(r,new Error("Video/audio streaming is not supported in your browser. You can still share "+"or download "+e.name+" (once it's fully downloaded). Use Chrome for "+"MediaSource support."))}var s=f.indexOf(g)>=0?"video":"audio";if(a.indexOf(g)>=0)h();else l();function h(){n("Use `videostream` package for "+e.name);y();u.addEventListener("error",d);u.addEventListener("playing",b);o(e,u)}function l(){n("Use MediaSource API for "+e.name);y();u.addEventListener("error",m);u.addEventListener("playing",b);e.createReadStream().pipe(new i(u,{extname:g}));if(_)u.currentTime=_}function c(){n("Use Blob URL for "+e.name);y();u.addEventListener("error",k);u.addEventListener("playing",b);e.getBlobURL(function(e,t){if(e)return k(e);u.src=t;if(_)u.currentTime=_})}function d(e){n("videostream error: fallback to MediaSource API: %o",e.message||e);u.removeEventListener("error",d);u.removeEventListener("playing",b);l()}function m(e){n("MediaSource API error: fallback to Blob URL: %o",e.message||e);u.removeEventListener("error",m);u.removeEventListener("playing",b);c()}function y(e){if(!u){u=document.createElement(s);u.controls=true;u.autoplay=true;u.play();u.addEventListener("progress",function(){_=u.currentTime});t.appendChild(u)}}}function b(){u.removeEventListener("playing",b);r(null,u)}function w(){u=document.createElement("audio");u.controls=true;u.autoplay=true;t.appendChild(u);e.getBlobURL(function(e,t){if(e)return k(e);u.addEventListener("error",k);u.addEventListener("playing",b);u.src=t;u.play()})}function S(){e.getBlobURL(function(n,i){if(n)return k(n);u=document.createElement("img");u.src=i;u.alt=e.name;t.appendChild(u);r(null,u)})}function x(){e.getBlobURL(function(e,n){if(e)return k(e);u=document.createElement("iframe");u.src=n;if(g!==".pdf")u.sandbox="allow-forms allow-scripts";t.appendChild(u);r(null,u)})}function k(t){if(u)u.remove();t.message='Error appending file "'+e.name+'" to DOM: '+t.message;n(t.message);if(r)r(t)}};function m(){}function v(e,t,n){r.nextTick(function(){if(e)e(t,n)})}}).call(this,e("_process"))},{_process:76,debug:39,mediasource:60,path:73,videostream:117}],2:[function(e,t,r){t.exports=o;var n=e("debug")("webtorrent:file-stream");var i=e("inherits");var s=e("stream");i(o,s.Readable);function o(e,t){s.Readable.call(this,t);this.destroyed=false;this._torrent=e._torrent;var r=t&&t.start||0;var n=t&&t.end||e.length-1;var i=e._torrent.pieceLength;this._startPiece=(r+e.offset)/i|0;this._endPiece=(n+e.offset)/i|0;this._piece=this._startPiece;this._offset=r+e.offset-this._startPiece*i;this._missing=n-r+1;this._reading=false;this._notifying=false;this._criticalLength=Math.min(1024*1024/i|0,2)}o.prototype._read=function(){if(this._reading)return;this._reading=true;this._notify()};o.prototype._notify=function(){var e=this;if(!e._reading||e._missing===0)return;if(!e._torrent.bitfield.get(e._piece)){return e._torrent.critical(e._piece,e._piece+e._criticalLength)}if(e._notifying)return;e._notifying=true;var t=e._piece;e._torrent.store.get(t,function(r,i){e._notifying=false;if(e.destroyed)return;if(r)return e.destroy(r);n("read %s (length %s) (err %s)",t,i.length,r&&r.message);if(e._offset){i=i.slice(e._offset);e._offset=0}if(e._missing0){return r[Math.random()*r.length|0]}else{return-1}}},{}],6:[function(e,t,r){(function(r,n){t.exports=H;var i=e("addr-to-ip-port");var s=e("bitfield");var o=e("chunk-store-stream/write");var a=e("create-torrent");var f=e("debug")("webtorrent:torrent");var u=e("torrent-discovery");var h=e("events").EventEmitter;var l=e("xtend/mutable");var c=e("fs-chunk-store");var d=e("immediate-chunk-store");var p=e("inherits");var m=e("multistream");var v=e("os");var g=e("run-parallel");var _=e("parse-torrent");var y=e("path");var b=e("path-exists");var w=e("torrent-piece");var S=e("pump");var x=e("random-iterate");var k=e("re-emitter");var E=e("simple-sha1");var A=e("bittorrent-swarm");var U=e("uniq");var T=e("ut_metadata");var I=e("ut_pex");var L=e("./file");var B=e("./rarity-map");var C=e("./server");var R=128*1024;var P=3e4;var F=5e3;var O=3*w.BLOCK_LENGTH;var M=.5;var D=1;var N=1e4;var z=2;var j=typeof b.sync==="function"?y.join(b.sync("/tmp")?"/tmp":v.tmpDir(),"webtorrent"):"/tmp/webtorrent";p(H,h);function H(e,t){h.call(this);if(!f.enabled)this.setMaxListeners(0);f("new torrent");this.client=t.client;this.announce=t.announce;this.urlList=t.urlList;this.path=t.path;this._store=t.store||c;this.strategy=t.strategy||"sequential";this._rechokeNumSlots=t.uploads===false||t.uploads===0?0:+t.uploads||10;this._rechokeOptimisticWire=null;this._rechokeOptimisticTime=0;this._rechokeIntervalId=null;this.ready=false;this.destroyed=false;this.metadata=null;this.store=null;this.numBlockedPeers=0;this.files=null;this.done=false;this._amInterested=false;this._selections=[];this._critical=[];this._servers=[];if(e)this._onTorrentId(e)}Object.defineProperty(H.prototype,"timeRemaining",{get:function(){if(this.done)return 0;if(this.swarm.downloadSpeed()===0)return Infinity;else return(this.length-this.downloaded)/this.swarm.downloadSpeed()*1e3}});Object.defineProperty(H.prototype,"downloaded",{get:function(){var e=0;for(var t=0,r=this.pieces.length;tt||e<0||t>=i.pieces.length){throw new Error("invalid selection ",e,":",t)}r=Number(r)||0;f("select %s-%s (priority %s)",e,t,r);i._selections.push({from:e,to:t,offset:0,priority:r,notify:n||W});i._selections.sort(function(e,t){return t.priority-e.priority});i._updateSelections()};H.prototype.deselect=function(e,t,r){var n=this;r=Number(r)||0;f("deselect %s-%s (priority %s)",e,t,r);for(var i=0;i2*(t.swarm.numConns-t.swarm.numPeers)&&e.amInterested){e.destroy()}else{r=setTimeout(n,F);if(r.unref)r.unref()}}var i=0;function s(){if(e.peerPieces.length!==t.pieces.length)return;for(;iR){return e.destroy()}if(t.pieces[r])return;t.store.get(r,{offset:n,length:i},s)});e.bitfield(t.bitfield);e.interested();r=setTimeout(n,F);if(r.unref)r.unref();e.isSeeder=false;s()};H.prototype._updateSelections=function(){var e=this;if(!e.swarm||e.destroyed)return;if(!e.metadata)return e.once("metadata",e._updateSelections.bind(e));r.nextTick(e._gcSelections.bind(e));e._updateInterest();e._update()};H.prototype._gcSelections=function(){var e=this;for(var t=0;t=r)return;var n=q(e,D);f(false)||f(true);function i(t,r,n,i){return function(s){return s>=t&&s<=r&&!(s in n)&&e.peerPieces.get(s)&&(!i||i(s))}}function s(){if(e.requests.length)return;var r=t._selections.length;while(r--){var n=t._selections[r];var s;if(t.strategy==="rarest"){var o=n.from+n.offset;var a=n.to;var f=a-o+1;var u={};var h=0;var l=i(o,a,u);while(h=n.from+n.offset;--s){if(!e.peerPieces.get(s))continue;if(t._request(e,s,false))return}}}}function o(){var r=e.downloadSpeed()||1;if(r>O)return function(){return true};var n=Math.max(1,e.requests.length)*w.BLOCK_LENGTH/r;var i=10;var s=0;return function(e){if(!i||t.bitfield.get(e))return true;var o=t.pieces[e].missing;for(;s0)continue;i--;return false}return true}}function a(e){var r=e;for(var n=e;n=n)return true;var s=o();for(var f=0;f0)e._rechokeOptimisticTime-=1;else e._rechokeOptimisticWire=null;var t=[];e.swarm.wires.forEach(function(r){if(!r.isSeeder&&r!==e._rechokeOptimisticWire){t.push({wire:r,downloadSpeed:r.downloadSpeed(),uploadSpeed:r.uploadSpeed(),salt:Math.random(),isChoked:true})}});t.sort(o);var r=0;var n=0;for(;n=O)continue;if(2*u>n||u>s)continue;o=f;s=u}if(!o)return false;for(a=0;a=o)return false;var a=i.pieces[t];var u=a.reserve();if(u===-1&&n&&i._hotswap(e,t)){u=a.reserve()}if(u===-1)return false;var h=i._reservations[t];if(!h)h=i._reservations[t]=[];var l=h.indexOf(null);if(l===-1)l=h.length;h[l]=e;var c=a.chunkOffset(u);var d=a.chunkLength(u);e.request(t,c,d,function m(r,n){if(!i.ready)return i.once("ready",function(){m(r,n)});if(h[l]===e)h[l]=null;if(a!==i.pieces[t])return p();if(r){f("error getting piece %s (offset: %s length: %s) from %s: %s",t,c,d,e.remoteAddress+":"+e.remotePort,r.message);a.cancel(u);p();return}f("got piece %s (offset: %s length: %s) from %s",t,c,d,e.remoteAddress+":"+e.remotePort);if(!a.set(u,n,e))return p();var s=a.flush();E(s,function(e){if(e===i._hashes[t]){if(!i.pieces[t])return;f("piece verified %s",t);i.pieces[t]=null;i._reservations[t]=null;i.bitfield.set(t,true);i.store.put(t,s);i.swarm.wires.forEach(function(e){e.have(t)});i._checkDone()}else{i.pieces[t]=new w(a.length);i.emit("warning",new Error("Piece "+t+" failed verification"))}p()})});function p(){r.nextTick(function(){i._update()})}return true};H.prototype._checkDone=function(){var e=this;if(e.destroyed)return;e.files.forEach(function(t){if(t.done)return;for(var r=t._startPiece;r<=t._endPiece;++r){if(!e.bitfield.get(r))return}t.done=true;t.emit("done");f("file done: "+t.name)});if(e.files.every(function(e){return e.done})){e.done=true;e.emit("done");f("torrent done: "+e.infoHash);if(e.discovery.tracker)e.discovery.tracker.complete()}e._gcSelections()};H.prototype.load=function(e,t){var r=this;if(!Array.isArray(e))e=[e];if(!t)t=W;var n=new m(e);var i=new o(r.store,r.pieceLength);S(n,i,function(e){if(e)return t(e);r.pieces.forEach(function(e,t){r.pieces[t]=null;r._reservations[t]=null;r.bitfield.set(t,true)});r._checkDone();t(null)})};H.prototype.createServer=function(e){var t=this;if(typeof C!=="function")return;var r=new C(t,e);t._servers.push(r);return r};H.prototype._onError=function(e){var t=this;f("torrent error: %s",e.message||e);t.emit("error",e);t.destroy()};function q(e,t){return Math.ceil(2+t*e.downloadSpeed()/w.BLOCK_LENGTH)}function G(e){return Math.random()*e|0}function W(){}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./file":3,"./rarity-map":5,"./server":31,_process:76,"addr-to-ip-port":7,bitfield:15,"bittorrent-swarm":17,"chunk-store-stream/write":35,"create-torrent":38,debug:39,events:44,"fs-chunk-store":61,"immediate-chunk-store":51,inherits:52,multistream:69,os:31,"parse-torrent":72,path:73,"path-exists":31,pump:77,"random-iterate":82,"re-emitter":83,"run-parallel":94,"simple-sha1":98,"torrent-discovery":109,"torrent-piece":110,uniq:112,ut_metadata:115,ut_pex:31,"xtend/mutable":120}],7:[function(e,t,r){var n=/^\[?([^\]]+)\]?:(\d+)$/;var i={};var s=0;t.exports=function o(e){if(s===1e5)t.exports.reset();if(!i[e]){var r=n.exec(e);if(!r)throw new Error("invalid addr: "+e);i[e]=[r[1],Number(r[2])];s+=1}return i[e]};t.exports.reset=function a(){i={};s=0}},{}],8:[function(e,t,r){"use strict";var n=e("./raw");var i=[];var s=[];var o=n.makeRequestCallFromTimer(a);function a(){if(s.length){throw s.shift()}}t.exports=f;function f(e){var t;if(i.length){t=i.pop()}else{t=new u}t.task=e;n(t)}function u(){this.task=null}u.prototype.call=function(){try{this.task.call()}catch(e){if(f.onerror){f.onerror(e)}else{s.push(e);o()}}finally{this.task=null;i[i.length]=this}}},{"./raw":9}],9:[function(e,t,r){(function(e){"use strict";t.exports=r;function r(e){if(!n.length){s();i=true}n[n.length]=e}var n=[];var i=false;var s;var o=0;var a=1024;function f(){while(oa){for(var t=0,r=n.length-o;t0){throw new Error("Invalid string. Length must be a multiple of 4")}var f=e.length;o="="===e.charAt(f-2)?2:"="===e.charAt(f-1)?1:0;a=new t(e.length*3/4-o);i=o>0?e.length-4:e.length;var u=0;function l(e){a[u++]=e}for(r=0,n=0;r>16);l((s&65280)>>8);l(s&255)}if(o===2){s=h(e.charAt(r))<<2|h(e.charAt(r+1))>>4;l(s&255)}else if(o===1){s=h(e.charAt(r))<<10|h(e.charAt(r+1))<<4|h(e.charAt(r+2))>>2;l(s>>8&255);l(s&255)}return a}function c(e){var t,r=e.length%3,i="",s,o;function a(e){return n.charAt(e)}function f(e){return a(e>>18&63)+a(e>>12&63)+a(e>>6&63)+a(e&63)}for(t=0,o=e.length-r;t>2);i+=a(s<<4&63);i+="==";break;case 2:s=(e[e.length-2]<<8)+e[e.length-1];i+=a(s>>10);i+=a(s>>4&63);i+=a(s<<2&63);i+="=";break}return i}e.toByteArray=l;e.fromByteArray=c})(typeof r==="undefined"?this.base64js={}:r)},{}],11:[function(e,t,r){t.exports={encode:e("./lib/encode"),decode:e("./lib/decode")}},{"./lib/decode":12,"./lib/encode":14}],12:[function(e,t,r){(function(r){var n=e("./dict");function i(e,t){i.position=0;i.encoding=t||null;i.data=!r.isBuffer(e)?new r(e):e;return i.next()}i.position=0;i.data=null;i.encoding=null;i.next=function(){switch(i.data[i.position]){case 100:return i.dictionary();break;case 108:return i.list();break;case 105:return i.integer();break;default:return i.bytes();break}};i.find=function(e){var t=i.position;var r=i.data.length;var n=i.data;while(t>3;if(e%8!==0)t++;return t}n.prototype.get=function(e){var t=e>>3;return t>e%8)};n.prototype.set=function(e,t){var r=e>>3;if(t||arguments.length===1){if(this.buffer.length>e%8}else if(r>e%8)}};n.prototype._grow=function(e){if(this.buffer.length=this._parserSize){var i=this._buffer.length===1?this._buffer[0]:r.concat(this._buffer);this._bufferSize-=this._parserSize;this._buffer=this._bufferSize?[i.slice(this._parserSize)]:[];this._parser(i.slice(0,this._parserSize))}n(null)};w.prototype._read=function(){};w.prototype._callback=function(e,t,r){if(!e)return;this._clearTimeout();if(!this.peerChoking&&!this._finished)this._updateTimeout();e.callback(t,r)};w.prototype._clearTimeout=function(){if(!this._timeout)return;clearTimeout(this._timeout);this._timeout=null};w.prototype._updateTimeout=function(){if(!this._timeoutMs||!this.requests.length||this._timeout)return;this._timeout=setTimeout(this._onTimeout.bind(this),this._timeoutMs);if(this._timeoutUnref&&this._timeout.unref)this._timeout.unref()};w.prototype._parse=function(e,t){this._parserSize=e;this._parser=t};w.prototype._message=function(e,t,n){var i=n?n.length:0;var s=new r(5+4*t.length);s.writeUInt32BE(s.length+i-4,0);s[4]=e;for(var o=0;o0){this._parse(t,this._onmessage)}else{this._onKeepAlive();this._parse(4,this._onmessagelength)}};w.prototype._onmessage=function(e){this._parse(4,this._onmessagelength);switch(e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:this._debug("got unknown message");return this.emit("unknownmessage",e)}};w.prototype._parseHandshake=function(){this._parse(1,function(e){var t=e.readUInt8(0);this._parse(t+48,function(e){var r=e.slice(0,t);if(r.toString()!=="BitTorrent protocol"){this._debug("Error: wire not speaking BitTorrent protocol (%s)",r.toString());this.end();return}e=e.slice(t);this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(e[7]&1),extended:!!(e[5]&16)});this._parse(4,this._onmessagelength)}.bind(this))}.bind(this))};w.prototype._onfinish=function(){this._finished=true;this.push(null);while(this.read()){}clearInterval(this._keepAliveInterval);this._parse(Number.MAX_VALUE,function(){});this.peerRequests=[];while(this.requests.length){this._callback(this.requests.shift(),new Error("wire was closed"),null)}};w.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._debugId+"] "+e[0];s.apply(null,e)};function S(e,t,r,n){for(var i=0;i=e.maxConns){return}s("drain (%s queued, %s/%s peers)",e.numQueued,e.numPeers,e.maxConns);var t=e._queue.shift();if(!t)return;s("tcp connect attempt to %s",t.addr);var r=i(t.addr);var n={host:r[0],port:r[1]};if(e._hostname)n.localAddress=e._hostname;var o=t.conn=f.connect(n);o.once("connect",function(){t.onConnect()});o.once("error",function(e){t.destroy(e)});t.setConnectTimeout();o.on("close",function(){if(e.destroyed)return;if(t.retries>=d.length){s("conn %s closed: will not re-add (max %s attempts)",t.addr,d.length);return}var r=d[t.retries];s("conn %s closed: will re-add to queue in %sms (attempt %s)",t.addr,r,t.retries+1);var n=setTimeout(function i(){var r=e._addPeer(t.addr);if(r)r.retries=t.retries+1},r);if(n.unref)n.unref()})};p.prototype._onError=function(e){var t=this;t.emit("error",e);t.destroy()};p.prototype._validAddr=function(e){var t=this;var r=i(e);var n=r[0];var s=r[1];return s>0&&s<65535&&!(n==="127.0.0.1"&&s===t._port)}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/peer":18,"./lib/tcp-pool":31,_process:76,"addr-to-ip-port":31,buffer:33,debug:39,events:44,inherits:52,net:31,speedometer:100}],18:[function(e,t,r){var n=e("debug")("bittorrent-swarm:peer");var i=e("./webconn");var s=e("bittorrent-protocol");var o=25e3;var a=25e3;r.createWebRTCPeer=function(e,t){var r=new f(e.id);r.conn=e;r.swarm=t;if(r.conn.connected){r.onConnect()}else{r.conn.once("connect",function(){r.onConnect()});r.conn.once("error",function(e){r.destroy(e)});r.setConnectTimeout()}return r};r.createIncomingTCPPeer=function(e){var t=e.remoteAddress+":"+e.remotePort;var r=new f(t);r.conn=e;r.addr=t;r.onConnect();return r};r.createOutgoingTCPPeer=function(e,t){var r=new f(e);r.addr=e;r.swarm=t;return r};r.createWebPeer=function(e,t,r){var n=new f(e);n.swarm=r;n.conn=new i(e,t);n.onConnect();return n};function f(e){var t=this;t.id=e;n("new Peer %s",e);t.addr=null;t.conn=null;t.swarm=null;t.wire=null;t.connected=false;t.destroyed=false;t.timeout=null;t.retries=0;t.sentHandshake=false}f.prototype.onConnect=function(){var e=this;if(e.destroyed)return;e.connected=true;n("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 r=e.wire=new s;r.once("end",function(){e.destroy()});r.once("close",function(){e.destroy()});r.once("finish",function(){e.destroy()});r.once("error",function(t){e.destroy(t)});r.once("handshake",function(t,r){e.onHandshake(t,r)});e.setHandshakeTimeout();t.pipe(r).pipe(t);if(e.swarm&&!e.sentHandshake)e.handshake()};f.prototype.onHandshake=function(e,t){var r=this;if(!r.swarm)return;if(r.swarm.destroyed)return r.destroy(new Error("swarm already destroyed"));if(e!==r.swarm.infoHash){return r.destroy(new Error("unexpected handshake info hash for this swarm"))}if(t===r.swarm.peerId){return r.destroy(new Error("refusing to handshake with self"))}n("Peer %s got handshake %s",r.id,e);clearTimeout(r.handshakeTimeout);r.retries=0;r.wire.on("download",function(e){if(r.destroyed)return;r.swarm.downloaded+=e;r.swarm.downloadSpeed(e);r.swarm.emit("download",e)});r.wire.on("upload",function(e){if(r.destroyed)return;r.swarm.uploaded+=e;r.swarm.uploadSpeed(e);r.swarm.emit("upload",e)});if(!r.sentHandshake)r.handshake();r.swarm.wires.push(r.wire);var i=r.addr;if(!i&&r.conn.remoteAddress){i=r.conn.remoteAddress+":"+r.conn.remotePort}r.swarm.emit("wire",r.wire,i)};f.prototype.handshake=function(){var e=this;e.wire.handshake(e.swarm.infoHash,e.swarm.peerId,e.swarm.handshakeOpts);e.sentHandshake=true};f.prototype.setConnectTimeout=function(){var e=this;clearTimeout(e.connectTimeout);e.connectTimeout=setTimeout(function(){e.destroy(new Error("connect timeout"))},o);if(e.connectTimeout.unref)e.connectTimeout.unref()};f.prototype.setHandshakeTimeout=function(){var e=this;clearTimeout(e.handshakeTimeout);e.handshakeTimeout=setTimeout(function(){e.destroy(new Error("handshake timeout"))},a);if(e.handshakeTimeout.unref)e.handshakeTimeout.unref()};f.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;t.connected=false;n("destroy %s (error: %s)",t.id,e&&(e.message||e));clearTimeout(t.connectTimeout);clearTimeout(t.handshakeTimeout);var r=t.swarm;var i=t.conn;var s=t.wire;t.conn=null;t.swarm=null;t.wire=null;if(r&&s){var o=r.wires.indexOf(s);if(o>=0)r.wires.splice(o,1)}if(i)i.destroy();if(s)s.destroy();if(r)r.removePeer(t.id)}},{"./webconn":19,"bittorrent-protocol":16,debug:39}],19:[function(e,t,r){t.exports=u;var n=e("bitfield");var i=e("debug")("bittorrent-swarm:webconn");var s=e("simple-get");var o=e("inherits");var a=e("simple-sha1");var f=e("bittorrent-protocol");o(u,f);function u(e,t){var r=this;f.call(this);r.url=e;r.peerId=a.sync(e);r.parsedTorrent=t;r.setKeepAlive(true);r.on("handshake",function(e,t){r.handshake(e,r.peerId);var i=r.parsedTorrent.pieces.length;var s=new n(i);for(var o=0;o<=i;o++){s.set(o,true)}r.bitfield(s)});r.on("choke",function(){i("choke")});r.on("unchoke",function(){i("unchoke")});r.once("interested",function(){i("interested");r.unchoke()});r.on("uninterested",function(){i("uninterested")});r.on("bitfield",function(){i("bitfield")});r.on("request",function(e,t,n,s){i("request pieceIndex=%d offset=%d length=%d",e,t,n);r.httpRequest(e,t,n,s)})}u.prototype.httpRequest=function(e,t,r,n){var o=this;var a=e*o.parsedTorrent.pieceLength;var f=a+t;var u=f+r-1;i("Requesting pieceIndex=%d offset=%d length=%d start=%d end=%d",e,t,r,f,u);var h={url:o.url,method:"GET",headers:{"user-agent":"WebTorrent (http://webtorrent.io)",range:"bytes="+f+"-"+u}};s.concat(h,function(e,t,r){if(e)return n(e);if(r.statusCode<200||r.statusCode>=300){return n(new Error("Unexpected HTTP status code "+r.statusCode))}i("Got data of length %d",t.length);n(null,t)})}},{bitfield:15,"bittorrent-protocol":16,debug:39,inherits:52,"simple-get":96,"simple-sha1":98}],20:[function(e,t,r){(function(r,n){t.exports=m;var i=e("events").EventEmitter;var s=e("debug")("bittorrent-tracker");var o=e("inherits");var a=e("once");var f=e("run-parallel");var u=e("uniq");var h=e("url");var l=e("./lib/common");var c=e("./lib/client/http-tracker");var d=e("./lib/client/udp-tracker");var p=e("./lib/client/websocket-tracker");o(m,i);function m(e,t,o,a){var f=this;if(!(f instanceof m))return new m(e,t,o,a);i.call(f);if(!a)a={};f.peerId=typeof e==="string"?e:e.toString("hex");f.peerIdBuffer=new n(f.peerId,"hex");f._peerIdBinary=f.peerIdBuffer.toString("binary");f.infoHash=typeof o.infoHash==="string"?o.infoHash:o.infoHash.toString("hex");f.infoHashBuffer=new n(f.infoHash,"hex");f._infoHashBinary=f.infoHashBuffer.toString("binary");f.torrentLength=o.length;f.destroyed=false;f._port=t;f._rtcConfig=a.rtcConfig;f._wrtc=a.wrtc;s("new client %s",f.infoHash);var l=!!f._wrtc||typeof window!=="undefined";var v=typeof o.announce==="string"?[o.announce]:o.announce==null?[]:o.announce;v=v.map(function(e){e=e.toString();if(e[e.length-1]==="/"){e=e.substring(0,e.length-1)}return e});v=u(v);f._trackers=v.map(function(e){var t=h.parse(e).protocol;if((t==="http:"||t==="https:")&&typeof c==="function"){return new c(f,e)}else if(t==="udp:"&&typeof d==="function"){return new d(f,e)}else if((t==="ws:"||t==="wss:")&&l){return new p(f,e)}else{r.nextTick(function(){var t=new Error("unsupported tracker protocol for "+e);f.emit("warning",t)})}return null}).filter(Boolean)}m.scrape=function(e,t,r){r=a(r);var i=new n("01234567890123456789");var s=6881;var o={infoHash:Array.isArray(t)?t[0]:t,announce:[e]};var f=new m(i,s,o);f.once("error",r);var u=Array.isArray(t)?t.length:1;var h={};f.on("scrape",function(e){u-=1;h[e.infoHash]=e;if(u===0){f.destroy();var t=Object.keys(h);if(t.length===1){r(null,h[t[0]])}else{r(null,h)}}});t=Array.isArray(t)?t.map(function(e){return new n(e,"hex")}):new n(t,"hex");f.scrape({infoHash:t})};m.prototype.start=function(e){var t=this;s("send `start`");e=t._defaultAnnounceOpts(e);e.event="started";t._announce(e);t._trackers.forEach(function(e){e.setInterval()})};m.prototype.stop=function(e){var t=this;s("send `stop`");e=t._defaultAnnounceOpts(e);e.event="stopped";t._announce(e)};m.prototype.complete=function(e){var t=this;s("send `complete`");if(!e)e={};if(e.downloaded==null&&t.torrentLength!=null){e.downloaded=t.torrentLength}e=t._defaultAnnounceOpts(e);e.event="completed";t._announce(e)};m.prototype.update=function(e){var t=this;s("send `update`");e=t._defaultAnnounceOpts(e);if(e.event)delete e.event;t._announce(e)};m.prototype._announce=function(e){var t=this;t._trackers.forEach(function(t){t.announce(e)})};m.prototype.scrape=function(e){var t=this;s("send `scrape`");if(!e)e={};t._trackers.forEach(function(t){t.scrape(e)})};m.prototype.setInterval=function(e){var t=this;s("setInterval %d",e);t._trackers.forEach(function(t){t.setInterval(e)})};m.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;s("destroy");var r=t._trackers.map(function(e){return function(t){e.destroy(t)}});f(r,e);t._trackers=[]};m.prototype._defaultAnnounceOpts=function(e){var t=this;if(!e)e={};if(e.numwant==null)e.numwant=l.DEFAULT_ANNOUNCE_PEERS;if(e.uploaded==null)e.uploaded=0;if(e.downloaded==null)e.downloaded=0;if(e.left==null&&t.torrentLength!=null){e.left=t.torrentLength-e.downloaded}return e}}).call(this,e("_process"),e("buffer").Buffer)},{"./lib/client/http-tracker":31,"./lib/client/udp-tracker":31,"./lib/client/websocket-tracker":22,"./lib/common":23,_process:76,buffer:33,debug:39,events:44,inherits:52,once:70,"run-parallel":94,uniq:112,url:113}],21:[function(e,t,r){t.exports=s;var n=e("events").EventEmitter;var i=e("inherits");i(s,n);function s(e,t){var r=this;n.call(r);r.client=e;r.announceUrl=t;r.interval=null;r.destroyed=false}s.prototype.setInterval=function(e){var t=this;if(t.interval)return;if(e==null)e=t.DEFAULT_ANNOUNCE_INTERVAL;clearInterval(t.interval);if(e){var r=t.announce.bind(t,t.client._defaultAnnounceOpts());t.interval=setInterval(r,e);if(t.interval.unref)t.interval.unref()}}},{events:44,inherits:52}],22:[function(e,t,r){t.exports=d;var n=e("debug")("bittorrent-tracker:websocket-tracker");var i=e("hat");var s=e("inherits");var o=e("simple-peer");var a=e("simple-websocket");var f=e("../common");var u=e("./tracker");var h={};var l=30*1e3;var c=5*1e3;s(d,u);function d(e,t,r){var i=this;u.call(i,e,t);n("new websocket tracker %s",t);i.peers={};i.socket=null;i.reconnecting=false;i._openSocket()}d.prototype.DEFAULT_ANNOUNCE_INTERVAL=30*1e3;d.prototype.announce=function(e){var t=this;if(t.destroyed||t.reconnecting)return;if(!t.socket.connected){return t.socket.once("connect",t.announce.bind(t,e))}var r=Math.min(e.numwant,10);t._generateOffers(r,function(n){var i={numwant:r,uploaded:e.uploaded||0,downloaded:e.downloaded,event:e.event,info_hash:t.client._infoHashBinary,peer_id:t.client._peerIdBinary,offers:n};if(t._trackerId)i.trackerid=t._trackerId;t._send(i)})};d.prototype.scrape=function(e){var t=this;if(t.destroyed||t.reconnecting)return;t._onSocketError(new Error("scrape not supported "+t.announceUrl))};d.prototype.destroy=function(e){var t=this;if(t.destroyed)return;t.destroyed=true;clearInterval(t.interval);h[t.announceUrl]=null;t.socket.removeListener("connect",t._onSocketConnectBound);t.socket.removeListener("data",t._onSocketDataBound);t.socket.removeListener("close",t._onSocketCloseBound);t.socket.removeListener("error",t._onSocketErrorBound);t._onSocketConnectBound=null;t._onSocketErrorBound=null;t._onSocketDataBound=null;t._onSocketCloseBound=null;t.socket.on("error",p);try{t.socket.destroy(e)}catch(r){if(e)e()}t.socket=null};d.prototype._openSocket=function(){var e=this;e.destroyed=false;e._onSocketConnectBound=e._onSocketConnect.bind(e);e._onSocketErrorBound=e._onSocketError.bind(e);e._onSocketDataBound=e._onSocketData.bind(e);e._onSocketCloseBound=e._onSocketClose.bind(e);e.socket=h[e.announceUrl];if(!e.socket){e.socket=h[e.announceUrl]=new a(e.announceUrl);e.socket.on("connect",e._onSocketConnectBound)}e.socket.on("data",e._onSocketDataBound);e.socket.on("close",e._onSocketCloseBound);e.socket.on("error",e._onSocketErrorBound)};d.prototype._onSocketConnect=function(){var e=this;if(e.destroyed)return;if(e.reconnecting){e.reconnecting=false;e.announce(e.client._defaultAnnounceOpts())}};d.prototype._onSocketData=function(e){var t=this;if(t.destroyed)return;if(!(typeof e==="object"&&e!==null)){return t.client.emit("warning",new Error("Invalid tracker response"))}if(e.info_hash!==t.client._infoHashBinary){n("ignoring websocket data from %s for %s (looking for %s: reused socket)",t.announceUrl,f.binaryToHex(e.info_hash),t.client.infoHash);return}if(e.peer_id&&e.peer_id===t.client._peerIdBinary){return}n("received %s from %s for %s",JSON.stringify(e),t.announceUrl,t.client.infoHash);var r=e["failure reason"];if(r)return t.client.emit("warning",new Error(r));var i=e["warning message"];if(i)t.client.emit("warning",new Error(i));var s=e.interval||e["min interval"];if(s)t.setInterval(s*1e3);var a=e["tracker id"];if(a){t._trackerId=a}if(e.complete){t.client.emit("update",{announce:t.announceUrl,complete:e.complete,incomplete:e.incomplete})}var u;if(e.offer&&e.peer_id){u=new o({trickle:false,config:t.client._rtcConfig,wrtc:t.client._wrtc});u.id=f.binaryToHex(e.peer_id);u.once("signal",function(r){var n={info_hash:t.client._infoHashBinary,peer_id:t.client._peerIdBinary,to_peer_id:e.peer_id,answer:r,offer_id:e.offer_id};if(t._trackerId)n.trackerid=t._trackerId;t._send(n)});u.signal(e.offer);t.client.emit("peer",u)}if(e.answer&&e.peer_id){u=t.peers[f.binaryToHex(e.offer_id)];if(u){u.id=f.binaryToHex(e.peer_id);u.signal(e.answer);t.client.emit("peer",u)}else{n("got unexpected answer: "+JSON.stringify(e.answer))}}};d.prototype._onSocketClose=function(){var e=this;if(e.destroyed)return;e.destroy();e._startReconnectTimer()};d.prototype._onSocketError=function(e){var t=this;if(t.destroyed)return;t.destroy();t.client.emit("warning",e);t._startReconnectTimer()};d.prototype._startReconnectTimer=function(){var e=this;var t=Math.floor(Math.random()*l)+c;e.reconnecting=true;var r=setTimeout(function(){e._openSocket()},t);if(r.unref)r.unref();n("reconnecting socket in %s ms",t)};d.prototype._send=function(e){var t=this;if(t.destroyed)return;var r=JSON.stringify(e);n("send %s",r);t.socket.send(r)};d.prototype._generateOffers=function(e,t){var r=this;var s=[];n("generating %s offers",e);for(var a=0;a=this.size){var i=r.concat(this._buffered);this._bufferedBytes-=this.size;this.push(i.slice(0,this.size));this._buffered=[i.slice(this.size,i.length)]}n()};o.prototype._flush=function(){if(this._bufferedBytes&&this._zeroPadding){var e=new r(this.size-this._bufferedBytes);e.fill(0);this._buffered.push(e);this.push(r.concat(this._buffered)); +this._buffered=null}else if(this._bufferedBytes){this.push(r.concat(this._buffered));this._buffered=null}this.push(null)}}).call(this,e("buffer").Buffer)},{buffer:33,defined:41,inherits:52,"readable-stream":30}],25:[function(e,t,r){(function(r){t.exports=a;var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};var i=e("core-util-is");i.inherits=e("inherits");var s=e("./_stream_readable");var o=e("./_stream_writable");i.inherits(a,s);u(n(o.prototype),function(e){if(!a.prototype[e])a.prototype[e]=o.prototype[e]});function a(e){if(!(this instanceof a))return new a(e);s.call(this,e);o.call(this,e);if(e&&e.readable===false)this.readable=false;if(e&&e.writable===false)this.writable=false;this.allowHalfOpen=true;if(e&&e.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",f)}function f(){if(this.allowHalfOpen||this._writableState.ended)return;r.nextTick(this.end.bind(this))}function u(e,t){for(var r=0,n=e.length;r0){if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var o=new Error("stream.unshift() after end event");e.emit("error",o)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)y(e)}w(e,t)}}else if(!i){t.reading=false}return d(t)}function d(e){return!e.ended&&(e.needReadable||e.length=p){e=p}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function v(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(isNaN(e)||a.isNull(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=m(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else return t.length}return e}l.prototype.read=function(e){u("read",e);var t=this._readableState;var r=e;if(!a.isNumber(e)||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){u("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)T(this);else y(this);return null}e=v(e,t);if(e===0&&t.ended){if(t.length===0)T(this);return null}var n=t.needReadable;u("need readable",n);if(t.length===0||t.length-e0)i=U(e,t);else i=null;if(a.isNull(i)){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)T(this);if(!a.isNull(i))this.emit("data",i);return i};function g(e,t){var r=null;if(!a.isBuffer(t)&&!a.isString(t)&&!a.isNullOrUndefined(t)&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function _(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;y(e)}function y(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)r.nextTick(function(){b(e)});else b(e)}}function b(e){u("emit readable");e.emit("readable");A(e)}function w(e,t){if(!t.readingMore){t.readingMore=true;r.nextTick(function(){S(e,t)})}}function S(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(s)a=r.join("");else a=i.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;r.nextTick(function(){if(!t.endEmitted&&t.length===0){t.endEmitted=true;e.readable=false;e.emit("end")}})}}function I(e,t){for(var r=0,n=e.length;r1){var r=[];for(var n=0;n1)return new u(e,arguments[1]);return new u(e)}this.length=0;this.parent=undefined;if(typeof e==="number"){return h(this,e)}if(typeof e==="string"){return l(this,e,arguments.length>1?arguments[1]:"utf8")}return c(this,e)}function h(e,t){e=y(e,t<0?0:b(t)|0);if(!u.TYPED_ARRAY_SUPPORT){for(var r=0;r>>1;if(r)e.parent=o;return e}function b(e){if(e>=f()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+f().toString(16)+" bytes")}return e|0}function w(e,t){if(!(this instanceof w))return new w(e,t);var r=new u(e,t);delete r.parent;return r}u.isBuffer=function te(e){return!!(e!=null&&e._isBuffer)};u.compare=function re(e,t){if(!u.isBuffer(e)||!u.isBuffer(t)){throw new TypeError("Arguments must be Buffers")}if(e===t)return 0;var r=e.length;var n=t.length;var i=0;var s=Math.min(r,n);while(i>>1;case"base64":return Q(e).length;default:if(n)return Z(e).length;t=(""+t).toLowerCase();n=true}}}u.byteLength=S;u.prototype.length=undefined;u.prototype.parent=undefined;function x(e,t,r){var n=false;t=t|0;r=r===undefined||r===Infinity?this.length:r|0;if(!e)e="utf8";if(t<0)t=0;if(r>this.length)r=this.length;if(r<=t)return"";while(true){switch(e){case"hex":return O(this,t,r);case"utf8":case"utf-8":return B(this,t,r);case"ascii":return P(this,t,r);case"binary":return F(this,t,r);case"base64":return L(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase();n=true}}}u.prototype.toString=function se(){var e=this.length|0;if(e===0)return"";if(arguments.length===0)return B(this,0,e);return x.apply(this,arguments)};u.prototype.equals=function oe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return true;return u.compare(this,e)===0};u.prototype.inspect=function ae(){var e="";var t=r.INSPECT_MAX_BYTES;if(this.length>0){e=this.toString("hex",0,t).match(/.{2}/g).join(" ");if(this.length>t)e+=" ... "}return""};u.prototype.compare=function fe(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return 0;return u.compare(this,e)};u.prototype.indexOf=function ue(e,t){if(t>2147483647)t=2147483647;else if(t<-2147483648)t=-2147483648;t>>=0;if(this.length===0)return-1;if(t>=this.length)return-1;if(t<0)t=Math.max(this.length+t,0);if(typeof e==="string"){if(e.length===0)return-1;return String.prototype.indexOf.call(this,e,t)}if(u.isBuffer(e)){return r(this,e,t)}if(typeof e==="number"){if(u.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,e,t)}return r(this,[e],t)}function r(e,t,r){var n=-1;for(var i=0;r+ii){n=i}}var s=t.length;if(s%2!==0)throw new Error("Invalid hex string");if(n>s/2){n=s/2}for(var o=0;os)r=s;if(e.length>0&&(r<0||t<0)||t>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!n)n="utf8";var o=false;for(;;){switch(n){case"hex":return k(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":return A(this,e,t,r);case"binary":return U(this,e,t,r);case"base64":return T(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase();o=true}}};u.prototype.toJSON=function de(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function L(e,t,r){if(t===0&&r===e.length){return n.fromByteArray(e)}else{return n.fromByteArray(e.slice(t,r))}}function B(e,t,r){r=Math.min(e.length,r);var n=[];var i=t;while(i239?4:s>223?3:s>191?2:1;if(i+a<=r){var f,u,h,l;switch(a){case 1:if(s<128){o=s}break;case 2:f=e[i+1];if((f&192)===128){l=(s&31)<<6|f&63;if(l>127){o=l}}break;case 3:f=e[i+1];u=e[i+2];if((f&192)===128&&(u&192)===128){l=(s&15)<<12|(f&63)<<6|u&63;if(l>2047&&(l<55296||l>57343)){o=l}}break;case 4:f=e[i+1];u=e[i+2];h=e[i+3];if((f&192)===128&&(u&192)===128&&(h&192)===128){l=(s&15)<<18|(f&63)<<12|(u&63)<<6|h&63;if(l>65535&&l<1114112){o=l}}}}if(o===null){o=65533;a=1}else if(o>65535){o-=65536;n.push(o>>>10&1023|55296);o=56320|o&1023}n.push(o);i+=a}return R(n)}var C=4096;function R(e){var t=e.length;if(t<=C){return String.fromCharCode.apply(String,e)}var r="";var n=0;while(nn)r=n;var i="";for(var s=t;sr){e=r}if(t<0){t+=r;if(t<0)t=0}else if(t>r){t=r}if(tr)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUIntLE=function me(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s0&&(i*=256)){n+=this[e+--t]*i}return n};u.prototype.readUInt8=function ge(e,t){if(!t)D(e,1,this.length);return this[e]};u.prototype.readUInt16LE=function _e(e,t){if(!t)D(e,2,this.length);return this[e]|this[e+1]<<8};u.prototype.readUInt16BE=function ye(e,t){if(!t)D(e,2,this.length);return this[e]<<8|this[e+1]};u.prototype.readUInt32LE=function be(e,t){if(!t)D(e,4,this.length);return(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};u.prototype.readUInt32BE=function we(e,t){if(!t)D(e,4,this.length);return this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};u.prototype.readIntLE=function Se(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s=i)n-=Math.pow(2,8*t);return n};u.prototype.readIntBE=function xe(e,t,r){e=e|0;t=t|0;if(!r)D(e,t,this.length);var n=t;var i=1;var s=this[e+--n];while(n>0&&(i*=256)){s+=this[e+--n]*i}i*=128;if(s>=i)s-=Math.pow(2,8*t);return s};u.prototype.readInt8=function ke(e,t){if(!t)D(e,1,this.length);if(!(this[e]&128))return this[e];return(255-this[e]+1)*-1};u.prototype.readInt16LE=function Ee(e,t){if(!t)D(e,2,this.length);var r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};u.prototype.readInt16BE=function Ae(e,t){if(!t)D(e,2,this.length);var r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};u.prototype.readInt32LE=function Ue(e,t){if(!t)D(e,4,this.length);return this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};u.prototype.readInt32BE=function Te(e,t){if(!t)D(e,4,this.length);return this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};u.prototype.readFloatLE=function Ie(e,t){if(!t)D(e,4,this.length);return i.read(this,e,true,23,4)};u.prototype.readFloatBE=function Le(e,t){if(!t)D(e,4,this.length);return i.read(this,e,false,23,4)};u.prototype.readDoubleLE=function Be(e,t){if(!t)D(e,8,this.length);return i.read(this,e,true,52,8)};u.prototype.readDoubleBE=function Ce(e,t){if(!t)D(e,8,this.length);return i.read(this,e,false,52,8)};function N(e,t,r,n,i,s){if(!u.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>i||te.length)throw new RangeError("index out of range")}u.prototype.writeUIntLE=function Re(e,t,r,n){e=+e;t=t|0;r=r|0;if(!n)N(this,e,t,r,Math.pow(2,8*r),0);var i=1;var s=0;this[t]=e&255;while(++s=0&&(s*=256)){this[t+i]=e/s&255}return t+r};u.prototype.writeUInt8=function Fe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,1,255,0);if(!u.TYPED_ARRAY_SUPPORT)e=Math.floor(e);this[t]=e&255;return t+1};function z(e,t,r,n){if(t<0)t=65535+t+1;for(var i=0,s=Math.min(e.length-r,2);i>>(n?i:1-i)*8}}u.prototype.writeUInt16LE=function Oe(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8}else{z(this,e,t,true)}return t+2};u.prototype.writeUInt16BE=function Me(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e&255}else{z(this,e,t,false)}return t+2};function j(e,t,r,n){if(t<0)t=4294967295+t+1;for(var i=0,s=Math.min(e.length-r,4);i>>(n?i:3-i)*8&255}}u.prototype.writeUInt32LE=function De(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[t+3]=e>>>24;this[t+2]=e>>>16;this[t+1]=e>>>8;this[t]=e&255}else{j(this,e,t,true)}return t+4};u.prototype.writeUInt32BE=function Ne(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e&255}else{j(this,e,t,false)}return t+4};u.prototype.writeIntLE=function ze(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=0;var o=1;var a=e<0?1:0;this[t]=e&255;while(++s>0)-a&255}return t+r};u.prototype.writeIntBE=function je(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);N(this,e,t,r,i-1,-i)}var s=r-1;var o=1;var a=e<0?1:0;this[t+s]=e&255;while(--s>=0&&(o*=256)){this[t+s]=(e/o>>0)-a&255}return t+r};u.prototype.writeInt8=function He(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,1,127,-128);if(!u.TYPED_ARRAY_SUPPORT)e=Math.floor(e);if(e<0)e=255+e+1;this[t]=e&255;return t+1};u.prototype.writeInt16LE=function qe(e,t,r){ +e=+e;t=t|0;if(!r)N(this,e,t,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8}else{z(this,e,t,true)}return t+2};u.prototype.writeInt16BE=function Ge(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e&255}else{z(this,e,t,false)}return t+2};u.prototype.writeInt32LE=function We(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,2147483647,-2147483648);if(u.TYPED_ARRAY_SUPPORT){this[t]=e&255;this[t+1]=e>>>8;this[t+2]=e>>>16;this[t+3]=e>>>24}else{j(this,e,t,true)}return t+4};u.prototype.writeInt32BE=function Ye(e,t,r){e=+e;t=t|0;if(!r)N(this,e,t,4,2147483647,-2147483648);if(e<0)e=4294967295+e+1;if(u.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e&255}else{j(this,e,t,false)}return t+4};function H(e,t,r,n,i,s){if(t>i||te.length)throw new RangeError("index out of range");if(r<0)throw new RangeError("index out of range")}function q(e,t,r,n,s){if(!s){H(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38)}i.write(e,t,r,n,23,4);return r+4}u.prototype.writeFloatLE=function Ve(e,t,r){return q(this,e,t,true,r)};u.prototype.writeFloatBE=function Ke(e,t,r){return q(this,e,t,false,r)};function G(e,t,r,n,s){if(!s){H(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308)}i.write(e,t,r,n,52,8);return r+8}u.prototype.writeDoubleLE=function $e(e,t,r){return G(this,e,t,true,r)};u.prototype.writeDoubleBE=function Ze(e,t,r){return G(this,e,t,false,r)};u.prototype.copy=function Xe(e,t,r,n){if(!r)r=0;if(!n&&n!==0)n=this.length;if(t>=e.length)t=e.length;if(!t)t=0;if(n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");if(n>this.length)n=this.length;if(e.length-t=0;s--){e[s+t]=this[s+r]}}else if(i<1e3||!u.TYPED_ARRAY_SUPPORT){for(s=0;s=this.length)throw new RangeError("start out of bounds");if(r<0||r>this.length)throw new RangeError("end out of bounds");var n;if(typeof e==="number"){for(n=t;n55295&&r<57344){if(!i){if(r>56319){if((t-=3)>-1)s.push(239,191,189);continue}else if(o+1===n){if((t-=3)>-1)s.push(239,191,189);continue}i=r;continue}if(r<56320){if((t-=3)>-1)s.push(239,191,189);i=r;continue}r=(i-55296<<10|r-56320)+65536}else if(i){if((t-=3)>-1)s.push(239,191,189)}i=null;if(r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else{throw new Error("Invalid code point")}}return s}function X(e){var t=[];for(var r=0;r>8;i=r%256;s.push(i);s.push(n)}return s}function Q(e){return n.toByteArray(V(e))}function ee(e,t,r,n){for(var i=0;i=t.length||i>=e.length)break;t[i+r]=e[i]}return i}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":10,ieee754:50,"is-array":53}],34:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Time-out",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Request Entity Too Large",414:"Request-URI Too Large",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Time-out",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],35:[function(e,t,r){t.exports=o;var n=e("block-stream2");var i=e("inherits");var s=e("stream");i(o,s.Writable);function o(e,t,r){var i=this;if(!(i instanceof o)){return new o(e,t,r)}s.Writable.call(i,r);if(!r)r={};if(!e||!e.put||!e.get){throw new Error("First argument must be an abstract-chunk-store compliant store")}t=Number(t);if(!t)throw new Error("Second argument must be a chunk length");i._blockstream=new n(t,{zeroPadding:false});i._blockstream.on("data",f).on("error",function(e){i.destroy(e)});var a=0;function f(t){if(i.destroyed)return;e.put(a,t);a+=1}i.on("finish",function(){this._blockstream.end()})}o.prototype._write=function(e,t,r){this._blockstream.write(e,t,r)};o.prototype.destroy=function(e){if(this.destroyed)return;this.destroyed=true;if(e)this.emit("error",e);this.emit("close")}},{"block-stream2":24,inherits:52,stream:101}],36:[function(e,t,r){t.exports=function(e,t){var r=Infinity;var n=0;var i=null;t.sort(function(e,t){return e-t});for(var s=0,o=t.length;s=r){break}r=n;i=t[s]}return i}},{}],37:[function(e,t,r){(function(e){function t(e){if(Array.isArray){return Array.isArray(e)}return v(e)==="[object Array]"}r.isArray=t;function n(e){return typeof e==="boolean"}r.isBoolean=n;function i(e){return e===null}r.isNull=i;function s(e){return e==null}r.isNullOrUndefined=s;function o(e){return typeof e==="number"}r.isNumber=o;function a(e){return typeof e==="string"}r.isString=a;function f(e){return typeof e==="symbol"}r.isSymbol=f;function u(e){return e===void 0}r.isUndefined=u;function h(e){return v(e)==="[object RegExp]"}r.isRegExp=h;function l(e){return typeof e==="object"&&e!==null}r.isObject=l;function c(e){return v(e)==="[object Date]"}r.isDate=c;function d(e){return v(e)==="[object Error]"||e instanceof Error}r.isError=d;function p(e){return typeof e==="function"}r.isFunction=p;function m(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}r.isPrimitive=m;r.isBuffer=e.isBuffer;function v(e){return Object.prototype.toString.call(e)}}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":54}],38:[function(e,t,r){(function(r,n){t.exports=y;t.exports.announceList=[["udp://tracker.openbittorrent.com:80"],["udp://tracker.internetwarriors.net:1337"],["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://exodus.desync.com:6969"],["wss://tracker.webtorrent.io"],["wss://tracker.btorrent.xyz"]];t.exports.parseInput=b;var i=e("bencode");var s=e("block-stream2");var o=e("piece-length");var a=e("path");var f=e("dezalgo");var u=e("filestream/read");var h=e("flatten");var l=e("fs");var c=e("is-file");var d=e("junk");var p=e("multistream");var m=e("once");var v=e("run-parallel");var g=e("simple-sha1");var _=e("stream");function y(e,t,r){if(typeof t==="function"){r=t;t={}}if(!t)t={};b(e,t,function(e,n,i){if(e)return r(e);t.singleFileTorrent=i;A(n,t,r)})}function b(e,t,r){if(typeof t==="function"){r=t;t={}}if(!t)t={};r=f(r);if(Array.isArray(e)&&e.length===0)throw new Error("invalid input type");if(I(e))e=Array.prototype.slice.call(e);if(!Array.isArray(e))e=[e];if(!t.name)t.name=e[0]&&e[0].name;if(!t.name)t.name=typeof e[0]==="string"&&a.basename(e[0]);if(t.name===undefined){throw new Error("missing option 'name' and unable to infer it from input[0].name")}if(e.length===1&&!e[0].name)e[0].name=t.name;var i=e.reduce(function(e,t){return e+Number(typeof t==="string")},0);var s=e.length===1;if(e.length===1&&typeof e[0]==="string"){if(typeof l.stat!=="function"){throw new Error("filesystem paths do not work in the browser")}c(e[0],function(e,t){if(e)return r(e);s=t;o()})}else{o()}function o(){v(e.map(function(e){return function(r){var o={};if(T(e)){o.getStream=B(e);o.length=e.size}else if(n.isBuffer(e)){o.getStream=C(e);o.length=e.length}else if(L(e)){if(!t.pieceLength){throw new Error("must specify `pieceLength` option if input is Stream")}o.getStream=P(e,o);o.length=0}else if(typeof e==="string"){if(typeof l.stat!=="function"){throw new Error("filesystem paths do not work in the browser")}var f=i>1||s;w(e,f,r);return}else{throw new Error("invalid input type")}if(!e.name)throw new Error("missing requied `name` property on input");o.path=e.name.split(a.sep);r(null,o)}}),function(e,t){if(e)return r(e);t=h(t);r(null,t,s)})}}function w(e,t,r){x(e,S,function(n,i){if(n)return r(n);if(Array.isArray(i))i=h(i);else i=[i];e=a.normalize(e);if(t){e=e.slice(0,e.lastIndexOf(a.sep)+1)}if(e[e.length-1]!==a.sep)e+=a.sep;i.forEach(function(t){t.getStream=R(t.path);t.path=t.path.replace(e,"").split(a.sep)});r(null,i)})}function S(e,t){t=m(t);l.stat(e,function(r,n){if(r)return t(r);var i={length:n.size,path:e};t(null,i)})}function x(e,t,r){l.readdir(e,function(n,i){if(n&&n.code==="ENOTDIR"){t(e,r)}else if(n){r(n)}else{v(i.filter(k).filter(d.not).map(function(r){return function(n){x(a.join(e,r),t,n)}}),r)}})}function k(e){return e[0]!=="."}function E(e,t,r){r=m(r);var i=[];var o=0;var a=e.map(function(e){return e.getStream});var f=0;var u=0;var h=false;var l=new p(a);var c=new s(t,{zeroPadding:false});l.on("error",_);l.pipe(c).on("data",d).on("end",v).on("error",_);function d(e){o+=e.length;var t=u;g(e,function(e){i[t]=e;f-=1;b()});f+=1;u+=1}function v(){h=true;b()}function _(e){y();r(e)}function y(){l.removeListener("error",_);c.removeListener("data",d);c.removeListener("end",v);c.removeListener("error",_)}function b(){if(h&&f===0){y();r(null,new n(i.join(""),"hex"),o)}}}function A(e,n,s){var a=n.announceList;if(!a){if(typeof n.announce==="string")a=[[n.announce]];else if(Array.isArray(n.announce)){a=n.announce.map(function(e){return[e]})}}if(!a)a=[];if(r.WEBTORRENT_ANNOUNCE){if(typeof r.WEBTORRENT_ANNOUNCE==="string"){a.push([[r.WEBTORRENT_ANNOUNCE]])}else if(Array.isArray(r.WEBTORRENT_ANNOUNCE)){a=a.concat(r.WEBTORRENT_ANNOUNCE.map(function(e){return[e]}))}}if(a.length===0){a=a.concat(t.exports.announceList)}if(typeof n.urlList==="string")n.urlList=[n.urlList];var f={info:{name:n.name},announce:a[0][0],"announce-list":a,"creation date":Number(n.creationDate)||Date.now(),encoding:"UTF-8"};if(n.comment!==undefined)f.comment=n.comment;if(n.createdBy!==undefined)f["created by"]=n.createdBy;if(n.private!==undefined)f.info.private=Number(n.private);if(n.sslCert!==undefined)f.info["ssl-cert"]=n.sslCert;if(n.urlList!==undefined)f["url-list"]=n.urlList;var u=n.pieceLength||o(e.reduce(U,0));f.info["piece length"]=u;E(e,u,function(t,r,o){if(t)return s(t);f.info.pieces=r;e.forEach(function(e){delete e.getStream});if(n.singleFileTorrent){f.info.length=o}else{f.info.files=e}s(null,i.encode(f))})}function U(e,t){return e+t.length}function T(e){return typeof Blob!=="undefined"&&e instanceof Blob}function I(e){return typeof FileList==="function"&&e instanceof FileList}function L(e){return typeof e==="object"&&typeof e.pipe==="function"}function B(e){return function(){return new u(e)}}function C(e){return function(){var t=new _.PassThrough;t.end(e);return t}}function R(e){return function(){return l.createReadStream(e)}}function P(e,t){return function(){var r=new _.Transform;r._transform=function(e,r,n){t.length+=e.length;this.push(e);n()};e.pipe(r);return r}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{bencode:11,"block-stream2":24,buffer:33,dezalgo:42,"filestream/read":45,flatten:46,fs:32,"is-file":55,junk:58,multistream:69,once:70,path:73,"piece-length":74,"run-parallel":94,"simple-sha1":98,stream:101}],39:[function(e,t,r){r=t.exports=e("./debug");r.log=s;r.formatArgs=i;r.save=o;r.load=a;r.useColors=n;r.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:f();r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function n(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}r.formatters.j=function(e){return JSON.stringify(e)};function i(){var e=arguments;var t=this.useColors;e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+r.humanize(this.diff);if(!t)return e;var n="color: "+this.color;e=[e[0],n,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0;var s=0;e[0].replace(/%[a-z%]/g,function(e){if("%%"===e)return;i++;if("%c"===e){s=i}});e.splice(s,0,n);return e}function s(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function o(e){try{if(null==e){r.storage.removeItem("debug")}else{r.storage.debug=e}}catch(t){}}function a(){var e;try{e=r.storage.debug}catch(t){}return e}r.enable(a());function f(){try{return window.localStorage}catch(e){}}},{"./debug":40}],40:[function(e,t,r){r=t.exports=o;r.coerce=h;r.disable=f;r.enable=a;r.enabled=u;r.humanize=e("ms");r.names=[];r.skips=[];r.formatters={};var n=0;var i;function s(){return r.colors[n++%r.colors.length]}function o(e){function t(){}t.enabled=false;function n(){var e=n;var t=+new Date;var o=t-(i||t);e.diff=o;e.prev=i;e.curr=t;i=t;if(null==e.useColors)e.useColors=r.useColors();if(null==e.color&&e.useColors)e.color=s();var a=Array.prototype.slice.call(arguments);a[0]=r.coerce(a[0]);if("string"!==typeof a[0]){a=["%o"].concat(a)}var f=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,n){if(t==="%%")return t;f++;var i=r.formatters[n];if("function"===typeof i){var s=a[f];t=i.call(e,s);a.splice(f,1);f--}return t});if("function"===typeof r.formatArgs){a=r.formatArgs.apply(e,a)}var u=n.log||r.log||console.log.bind(console);u.apply(e,a)}n.enabled=true;var o=r.enabled(e)?n:t;o.namespace=e;return o}function a(e){r.save(e);var t=(e||"").split(/[\s,]+/);var n=t.length;for(var i=0;i0&&this._events[e].length>r){this._events[e].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[e].length);if(typeof console.trace==="function"){console.trace()}}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=false;function n(){this.removeListener(e,n);if(!r){r=true;t.apply(this,arguments)}}n.listener=t;this.on(e,n);return this};n.prototype.removeListener=function(e,t){var r,n,s,a;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;r=this._events[e];s=r.length;n=-1;if(r===t||i(r.listener)&&r.listener===t){delete this._events[e];if(this._events.removeListener)this.emit("removeListener",e,t)}else if(o(r)){for(a=s;a-- >0;){if(r[a]===t||r[a].listener&&r[a].listener===t){n=a;break}}if(n<0)return this;if(r.length===1){r.length=0;delete this._events[e]}else{r.splice(n,1)}if(this._events.removeListener)this.emit("removeListener",e,t)}return this};n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[e])delete this._events[e];return this}if(arguments.length===0){for(t in this._events){if(t==="removeListener")continue;this.removeAllListeners(t)}this.removeAllListeners("removeListener");this._events={};return this}r=this._events[e];if(i(r)){this.removeListener(e,r)}else if(r){while(r.length)this.removeListener(e,r[r.length-1])}delete this._events[e];return this};n.prototype.listeners=function(e){var t;if(!this._events||!this._events[e])t=[];else if(i(this._events[e]))t=[this._events[e]];else t=this._events[e].slice();return t};n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;else if(t)return t.length}return 0};n.listenerCount=function(e,t){return e.listenerCount(t)};function i(e){return typeof e==="function"}function s(e){return typeof e==="number"}function o(e){return typeof e==="object"&&e!==null}function a(e){return e===void 0}},{}],45:[function(e,t,r){var n=e("stream").Readable;var i=e("inherits");var s=/^.*\.(\w+)$/;var o=e("typedarray-to-buffer");function a(e,t){var r=this;if(!(this instanceof a)){return new a(e,t)}t=t||{};n.call(this,t);this._offset=0;this._ready=false;this._file=e;this._size=e.size;this._chunkSize=t.chunkSize||Math.max(this._size/1e3,200*1024);this.reader=new FileReader;this._generateHeaderBlocks(e,t,function(e,t){if(e){return r.emit("error",e)}if(Array.isArray(t)){t.forEach(function(e){r.push(e)})}r._ready=true;r.emit("_ready")})}i(a,n);t.exports=a;a.prototype._generateHeaderBlocks=function(e,t,r){r(null,[])};a.prototype._read=function(){if(!this._ready){this.once("_ready",this._read.bind(this));return}var e=this;var t=this.reader;var r=this._offset;var n=this._offset+this._chunkSize;if(n>this._size)n=this._size;if(r===this._size){this.destroy();this.push(null);return}t.onload=function(){e._offset=n;e.push(o(t.result))};t.onerror=function(){e.emit("error",t.error)};t.readAsArrayBuffer(this._file.slice(r,n))};a.prototype.destroy=function(){this._file=null;if(this.reader){this.reader.onload=null;this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}},{inherits:52,stream:101,"typedarray-to-buffer":111}],46:[function(e,t,r){t.exports=function n(e,t){t=typeof t=="number"?t:Infinity;return r(e,1);function r(e,n){return e.reduce(function(e,i){if(Array.isArray(i)&&n=Math.pow(2,e)){return n(e,t)}else return o};n.rack=function(e,t,r){var i=function(i){var o=0;do{if(o++>10){if(r)e+=r;else throw new Error("too many ID collisions, use more bits")}var a=n(e,t)}while(Object.hasOwnProperty.call(s,a));s[a]=i;return a};var s=i.hats={};i.get=function(e){return i.hats[e]};i.set=function(e,t){i.hats[e]=t;return i};i.bits=e||128;i.base=t||16;return i}},{}],49:[function(e,t,r){var n=e("http");var i=t.exports;for(var s in n){if(n.hasOwnProperty(s))i[s]=n[s]}i.request=function(e,t){if(!e)e={};e.scheme="https";e.protocol="https:";return n.request.call(this,e,t)}},{http:102}],50:[function(e,t,r){r.read=function(e,t,r,n,i){var s,o;var a=i*8-n-1;var f=(1<>1;var h=-7;var l=r?i-1:0;var c=r?-1:1;var d=e[t+l];l+=c;s=d&(1<<-h)-1;d>>=-h;h+=a;for(;h>0;s=s*256+e[t+l],l+=c,h-=8){}o=s&(1<<-h)-1;s>>=-h;h+=n;for(;h>0;o=o*256+e[t+l],l+=c,h-=8){}if(s===0){s=1-u}else if(s===f){return o?NaN:(d?-1:1)*Infinity}else{o=o+Math.pow(2,n);s=s-u}return(d?-1:1)*o*Math.pow(2,s-n)};r.write=function(e,t,r,n,i,s){var o,a,f;var u=s*8-i-1;var h=(1<>1;var c=i===23?Math.pow(2,-24)-Math.pow(2,-77):0;var d=n?0:s-1;var p=n?1:-1;var m=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){a=isNaN(t)?1:0;o=h}else{o=Math.floor(Math.log(t)/Math.LN2);if(t*(f=Math.pow(2,-o))<1){o--;f*=2}if(o+l>=1){t+=c/f}else{t+=c*Math.pow(2,1-l)}if(t*f>=2){o++;f/=2}if(o+l>=h){a=0;o=h}else if(o+l>=1){a=(t*f-1)*Math.pow(2,i);o=o+l}else{a=t*Math.pow(2,l-1)*Math.pow(2,i);o=0}}for(;i>=8;e[r+d]=a&255,d+=p,a/=256,i-=8){}o=o<0;e[r+d]=o&255,d+=p,o/=256,u-=8){}e[r+d-p]|=m*128}},{}],51:[function(e,t,r){(function(e){t.exports=r;function r(e){if(!(this instanceof r))return new r(e);this.store=e;if(!this.store||!this.store.get||!this.store.put){throw new Error("First argument must be abstract-chunk-store compliant")}this.mem=[]}r.prototype.put=function(e,t,r){var n=this;n.mem[e]=t;n.store.put(e,t,function(t){n.mem[e]=null;if(r)r(t)})};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);var i=t&&t.offset||0;var s=t&&t.length&&i+t.length;var o=this.mem[e];if(o)return n(r,null,t?o.slice(i,s):o);this.store.get(e,t,r)};r.prototype.close=function(e){this.store.close(e)};r.prototype.destroy=function(e){this.store.destroy(e)};function n(t,r,n){e.nextTick(function(){if(t)t(r,n)})}}).call(this,e("_process"))},{_process:76}],52:[function(e,t,r){if(typeof Object.create==="function"){t.exports=function n(e,t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}else{t.exports=function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype;e.prototype=new r;e.prototype.constructor=e}}},{}],53:[function(e,t,r){var n=Array.isArray;var i=Object.prototype.toString;t.exports=n||function(e){return!!e&&"[object Array]"==i.call(e)}},{}],54:[function(e,t,r){t.exports=function(e){return!!(e!=null&&(e._isBuffer||e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)))}},{}],55:[function(e,t,r){"use strict";var n=e("fs");t.exports=function s(e,t){if(!t)return i(e);n.stat(e,function(e,r){if(e)return t(e);return t(null,r.isFile())})};t.exports.sync=i;function i(e){return n.existsSync(e)&&n.statSync(e).isFile()}},{fs:32}],56:[function(e,t,r){t.exports=s;s.strict=o;s.loose=a;var n=Object.prototype.toString;var i={"[object Int8Array]":true,"[object Int16Array]":true,"[object Int32Array]":true,"[object Uint8Array]":true,"[object Uint8ClampedArray]":true,"[object Uint16Array]":true,"[object Uint32Array]":true,"[object Float32Array]":true,"[object Float64Array]":true};function s(e){return o(e)||a(e)}function o(e){return e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array}function a(e){return i[n.call(e)]}},{}],57:[function(e,t,r){t.exports=Array.isArray||function(e){return Object.prototype.toString.call(e)=="[object Array]"}},{}],58:[function(e,t,r){"use strict";r.re=/^npm-debug\.log$|^\..*\.swp$|^\.DS_Store$|^\.AppleDouble$|^\.LSOverride$|^Icon[\r\?]?|^\._.*|^\.Spotlight-V100$|\.Trashes|^__MACOSX$|~$|^Thumbs\.db$|^ehthumbs\.db$|^Desktop\.ini$/;r.is=function(e){return r.re.test(e)};r.not=r.isnt=function(e){return!r.is(e)}},{}],59:[function(e,t,r){(function(r){t.exports=o;t.exports.decode=o;t.exports.encode=a;var n=e("thirty-two");var i=e("xtend");var s=e("uniq");function o(e){var t={};var i=e.split("magnet:?")[1];var o=i&&i.length>=0?i.split("&"):[];o.forEach(function(e){var r=e.split("=");if(r.length!==2)return;var n=r[0];var i=r[1];if(n==="dn")i=decodeURIComponent(i).replace(/\+/g," ");if(n==="tr"||n==="xs"||n==="as"||n==="ws"){i=decodeURIComponent(i)}if(n==="kt")i=decodeURIComponent(i).split("+");if(t[n]){if(Array.isArray(t[n])){t[n].push(i)}else{var s=t[n];t[n]=[s,i]}}else{t[n]=i}});var a;if(t.xt){var f=Array.isArray(t.xt)?t.xt:[t.xt];f.forEach(function(e){if(a=e.match(/^urn:btih:(.{40})/)){t.infoHash=a[1]}else if(a=e.match(/^urn:btih:(.{32})/)){var i=n.decode(a[1]);t.infoHash=new r(i,"binary").toString("hex")}})}if(t.infoHash)t.infoHashBuffer=new r(t.infoHash,"hex");if(t.dn)t.name=t.dn;if(t.kt)t.keywords=t.kt;if(typeof t.tr==="string")t.announce=[t.tr];else if(Array.isArray(t.tr))t.announce=t.tr;else t.announce=[];s(t.announce);t.urlList=[];if(typeof t.as==="string"||Array.isArray(t.as)){t.urlList=t.urlList.concat(t.as)}if(typeof t.ws==="string"||Array.isArray(t.ws)){t.urlList=t.urlList.concat(t.ws)}return t}function a(e){e=i(e);if(e.infoHashBuffer)e.xt="urn:btih:"+e.infoHashBuffer.toString("hex");if(e.infoHash)e.xt="urn:btih:"+e.infoHash;if(e.name)e.dn=e.name;if(e.keywords)e.kt=e.keywords;if(e.announce)e.tr=e.announce;if(e.urlList){e.ws=e.urlList;delete e.as}var t="magnet:?";Object.keys(e).filter(function(e){return e.length===2}).forEach(function(r,n){var i=Array.isArray(e[r])?e[r]:[e[r]];i.forEach(function(e,i){if((n>0||i>0)&&(r!=="kt"||i===0))t+="&";if(r==="dn")e=encodeURIComponent(e).replace(/%20/g,"+");if(r==="tr"||r==="xs"||r==="as"||r==="ws"){e=encodeURIComponent(e)}if(r==="kt")e=encodeURIComponent(e);if(r==="kt"&&i>0)t+="+"+e;else t+=r+"="+e})});return t}}).call(this,e("buffer").Buffer)},{buffer:33,"thirty-two":107,uniq:112,xtend:119}],60:[function(e,t,r){t.exports=o;var n=e("inherits");var i=e("stream");var s=typeof window!=="undefined"&&window.MediaSource;n(o,i.Writable);function o(e,t){var r=this;if(!(r instanceof o))return new o(e,t);i.Writable.call(r,t);if(!s)throw new Error("web browser lacks MediaSource support");if(!t)t={};r._elem=e;r._mediaSource=new s;r._sourceBuffer=null;r._cb=null;r._type=t.type||a(t.extname); +if(!r._type)throw new Error("missing `opts.type` or `opts.extname` options");r._elem.src=window.URL.createObjectURL(r._mediaSource);r._mediaSource.addEventListener("sourceopen",function(){if(s.isTypeSupported(r._type)){r._sourceBuffer=r._mediaSource.addSourceBuffer(r._type);r._sourceBuffer.addEventListener("updateend",r._flow.bind(r));r._flow()}else{r._mediaSource.endOfStream("decode")}});r.on("finish",function(){r._mediaSource.endOfStream()})}o.prototype._write=function(e,t,r){var n=this;if(!n._sourceBuffer){n._cb=function(i){if(i)return r(i);n._write(e,t,r)};return}if(n._sourceBuffer.updating){return r(new Error("Cannot append buffer while source buffer updating"))}n._sourceBuffer.appendBuffer(e);n._cb=r};o.prototype._flow=function(){var e=this;if(e._cb){e._cb(null)}};function a(e){if(!e)return null;if(e[0]!==".")e="."+e;return{".m4a":'audio/mp4; codecs="mp4a.40.5"',".m4v":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".mp3":"audio/mpeg",".mp4":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".webm":'video/webm; codecs="vorbis, vp8"'}[e]}},{inherits:52,stream:101}],61:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(!(this instanceof r))return new r(e,t);if(!t)t={};this.chunkLength=Number(e);if(!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[];this.closed=false;this.length=Number(t.length)||Infinity;if(this.length!==Infinity){this.lastChunkLength=this.length%this.chunkLength||this.chunkLength;this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1}}r.prototype.put=function(e,t,r){if(this.closed)return n(r,new Error("Storage is closed"));var i=e===this.lastChunkIndex;if(i&&t.length!==this.lastChunkLength){return n(r,new Error("Last chunk length must be "+this.lastChunkLength))}if(!i&&t.length!==this.chunkLength){return n(r,new Error("Chunk length must be "+this.chunkLength))}this.chunks[e]=t;n(r,null)};r.prototype.get=function(e,t,r){if(typeof t==="function")return this.get(e,null,t);if(this.closed)return n(r,new Error("Storage is closed"));var i=this.chunks[e];if(!i)return n(r,new Error("Chunk not found"));if(!t)return n(r,null,i);var s=t.offset||0;var o=t.length||i.length-s;n(r,null,i.slice(s,o+s))};r.prototype.close=r.prototype.destroy=function(e){if(this.closed)return n(e,new Error("Storage is closed"));this.closed=true;this.chunks=null;n(e,null)};function n(t,r,n){e.nextTick(function(){if(t)t(r,n)})}}).call(this,e("_process"))},{_process:76}],62:[function(e,t,r){var n=function(e,t,r){this._byteOffset=t||0;if(e instanceof ArrayBuffer){this.buffer=e}else if(typeof e=="object"){this.dataView=e;if(t){this._byteOffset+=t}}else{this.buffer=new ArrayBuffer(e||0)}this.position=0;this.endianness=r==null?n.LITTLE_ENDIAN:r};t.exports=n;n.prototype={};n.prototype.save=function(e){var t=new Blob([this.buffer]);var r=window.webkitURL||window.URL;if(r&&r.createObjectURL){var n=r.createObjectURL(t);var i=document.createElement("a");i.setAttribute("href",n);i.setAttribute("download",e);i.click();r.revokeObjectURL(n)}else{throw"DataStream.save: Can't create object URL."}};n.BIG_ENDIAN=false;n.LITTLE_ENDIAN=true;n.prototype._dynamicSize=true;Object.defineProperty(n.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(e){if(!e){this._trimAlloc()}this._dynamicSize=e}});n.prototype._byteLength=0;Object.defineProperty(n.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}});Object.defineProperty(n.prototype,"buffer",{get:function(){this._trimAlloc();return this._buffer},set:function(e){this._buffer=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(n.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._buffer.byteLength}});Object.defineProperty(n.prototype,"dataView",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset;this._buffer=e.buffer;this._dataView=new DataView(this._buffer,this._byteOffset);this._byteLength=this._byteOffset+e.byteLength}});n.prototype._realloc=function(e){if(!this._dynamicSize){return}var t=this._byteOffset+this.position+e;var r=this._buffer.byteLength;if(t<=r){if(t>this._byteLength){this._byteLength=t}return}if(r<1){r=1}while(t>r){r*=2}var n=new ArrayBuffer(r);var i=new Uint8Array(this._buffer);var s=new Uint8Array(n,0,i.length);s.set(i);this.buffer=n;this._byteLength=t};n.prototype._trimAlloc=function(){if(this._byteLength==this._buffer.byteLength){return}var e=new ArrayBuffer(this._byteLength);var t=new Uint8Array(e);var r=new Uint8Array(this._buffer,0,t.length);t.set(r);this.buffer=e};n.prototype.shift=function(e){var t=new ArrayBuffer(this._byteLength-e);var r=new Uint8Array(t);var n=new Uint8Array(this._buffer,e,r.length);r.set(n);this.buffer=t;this.position-=e};n.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t};n.prototype.isEof=function(){return this.position>=this._byteLength};n.prototype.mapInt32Array=function(e,t){this._realloc(e*4);var r=new Int32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.mapInt16Array=function(e,t){this._realloc(e*2);var r=new Int16Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};n.prototype.mapInt8Array=function(e){this._realloc(e*1);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};n.prototype.mapUint32Array=function(e,t){this._realloc(e*4);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.mapUint16Array=function(e,t){this._realloc(e*2);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*2;return r};n.prototype.mapUint8Array=function(e){this._realloc(e*1);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);this.position+=e*1;return t};n.prototype.mapFloat64Array=function(e,t){this._realloc(e*8);var r=new Float64Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*8;return r};n.prototype.mapFloat32Array=function(e,t){this._realloc(e*4);var r=new Float32Array(this._buffer,this.byteOffset+this.position,e);n.arrayToNative(r,t==null?this.endianness:t);this.position+=e*4;return r};n.prototype.readInt32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Int32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readInt16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Int16Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readInt8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Int8Array(e);n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};n.prototype.readUint32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Uint32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readUint16Array=function(e,t){e=e==null?this.byteLength-this.position/2:e;var r=new Uint16Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readUint8Array=function(e){e=e==null?this.byteLength-this.position:e;var t=new Uint8Array(e);n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT);this.position+=t.byteLength;return t};n.prototype.readFloat64Array=function(e,t){e=e==null?this.byteLength-this.position/8:e;var r=new Float64Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.readFloat32Array=function(e,t){e=e==null?this.byteLength-this.position/4:e;var r=new Float32Array(e);n.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT);n.arrayToNative(r,t==null?this.endianness:t);this.position+=r.byteLength;return r};n.prototype.writeInt32Array=function(e,t){this._realloc(e.length*4);if(e instanceof Int32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0){n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength);this.mapInt32Array(e.length,t)}else{for(var r=0;r0;n.memcpy=function(e,t,r,n,i){var s=new Uint8Array(e,t,i);var o=new Uint8Array(r,n,i);s.set(o)};n.arrayToNative=function(e,t){if(t==this.endianness){return e}else{return this.flipArrayEndianness(e)}};n.nativeToEndian=function(e,t){if(this.endianness==t){return e}else{return this.flipArrayEndianness(e)}};n.flipArrayEndianness=function(e){var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);for(var r=0;ri;n--,i++){var s=t[i];t[i]=t[n];t[n]=s}}return e};n.prototype.failurePosition=0;n.prototype.readStruct=function(e){var t={},r,n,i;var s=this.position;for(var o=0;o>16);this.writeUint8((e&65280)>>8);this.writeUint8(e&255)};n.prototype.adjustUint32=function(e,t){var r=this.position;this.seek(e);this.writeUint32(t);this.seek(r)}},{}],63:[function(e,t,r){var n=e("./DataStream");var s=e("./descriptor");var o=e("./log");var a={ERR_NOT_ENOUGH_DATA:0,OK:1,boxCodes:["mdat","avcC","hvcC","ftyp","payl","vmhd","smhd","hmhd","dref","elst"],fullBoxCodes:["mvhd","tkhd","mdhd","hdlr","smhd","hmhd","nhmd","url ","urn ","ctts","cslg","stco","co64","stsc","stss","stsz","stz2","stts","stsh","mehd","trex","mfhd","tfhd","trun","tfdt","esds","subs","txtC"],containerBoxCodes:[["moov",["trak"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl"],["mvex",["trex"]],["moof",["traf"]],["traf",["trun"]],["vttc"],["tref"]],sampleEntryCodes:[{prefix:"Visual",types:["mp4v","avc1","avc2","avc3","avc4","avcp","drac","encv","mjp2","mvc1","mvc2","resv","s263","svc1","vc-1","hvc1","hev1"]},{prefix:"Audio",types:["mp4a","ac-3","alac","dra1","dtsc","dtse",,"dtsh","dtsl","ec-3","enca","g719","g726","m4ae","mlpa","raw ","samr","sawb","sawp","sevc","sqcp","ssmv","twos"]},{prefix:"Hint",types:["fdp ","m2ts","pm2t","prtp","rm2t","rrtp","rsrp","rtp ","sm2t","srtp"]},{prefix:"Metadata",types:["metx","mett","urim"]},{prefix:"Subtitle",types:["stpp","wvtt","sbtt","tx3g","stxt"]}],trackReferenceTypes:["scal"],initialize:function(){var e,t;var r;a.FullBox.prototype=new a.Box;a.ContainerBox.prototype=new a.Box;a.stsdBox.prototype=new a.FullBox;a.SampleEntry.prototype=new a.FullBox;a.TrackReferenceTypeBox.prototype=new a.Box;r=a.boxCodes.length;for(e=0;ee.byteLength){e.seek(n);o.w("BoxParser",'Not enough data in stream to parse the entire "'+f+'" box');return{code:a.ERR_NOT_ENOUGH_DATA,type:f,size:s,hdr_size:i}}if(a[f+"Box"]){r=new a[f+"Box"](s-i)}else{if(t){r=new a.SampleEntry(f,s-i)}else{r=new a.Box(f,s-i)}}r.hdr_size=i;r.start=n;r.fileStart=n+e.buffer.fileStart;r.parse(e);e.seek(n+s);return{code:a.OK,box:r,size:s}}};t.exports=a;a.initialize();a.Box.prototype.parse=function(e){if(this.type!="mdat"){this.data=e.readUint8Array(this.size)}else{e.seek(this.start+this.size+this.hdr_size)}};a.FullBox.prototype.parseFullHeader=function(e){this.version=e.readUint8();this.flags=e.readUint24();this.size-=4};a.ContainerBox.prototype.parse=function(e){var t;var r;var n;n=e.position;while(e.position=4){this.compatible_brands[t]=e.readString(4);this.size-=4;t++}};a.mvhdBox.prototype.parse=function(e){this.flags=0;this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.rate=e.readUint32();this.volume=e.readUint16()>>8;e.readUint16();e.readUint32Array(2);this.matrix=e.readUint32Array(9);e.readUint32Array(6);this.next_track_id=e.readUint32()};a.TKHD_FLAG_ENABLED=1;a.TKHD_FLAG_IN_MOVIE=2;a.TKHD_FLAG_IN_PREVIEW=4;a.tkhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.track_id=e.readUint32();e.readUint32();this.duration=e.readUint32()}e.readUint32Array(2);this.layer=e.readInt16();this.alternate_group=e.readInt16();this.volume=e.readInt16()>>8;e.readUint16();this.matrix=e.readInt32Array(9);this.width=e.readUint32();this.height=e.readUint32()};a.mdhdBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version==1){this.creation_time=e.readUint64();this.modification_time=e.readUint64();this.timescale=e.readUint32();this.duration=e.readUint64()}else{this.creation_time=e.readUint32();this.modification_time=e.readUint32();this.timescale=e.readUint32();this.duration=e.readUint32()}this.language=e.readUint16();var t=[];t[0]=this.language>>10&31;t[1]=this.language>>5&31;t[2]=this.language&31;this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96);e.readUint16()};a.hdlrBox.prototype.parse=function(e){this.parseFullHeader(e);if(this.version===0){e.readUint32();this.handler=e.readString(4);e.readUint32Array(3);this.name=e.readCString()}else{this.data=e.readUint8Array(size)}};a.stsdBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);r=e.readUint32();for(i=1;i<=r;i++){t=a.parseOneBox(e,true); +this.entries.push(t.box)}};a.avcCBox.prototype.parse=function(e){var t;var r;var n;this.configurationVersion=e.readUint8();this.AVCProfileIndication=e.readUint8();this.profile_compatibility=e.readUint8();this.AVCLevelIndication=e.readUint8();this.lengthSizeMinusOne=e.readUint8()&3;r=e.readUint8()&31;this.size-=6;this.SPS=new Array(r);for(t=0;t0){this.ext=e.readUint8Array(this.size)}};a.hvcCBox.prototype.parse=function(e){var t;var r;var n;var i;this.configurationVersion=e.readUint8();i=e.readUint8();this.general_profile_space=i>>6;this.general_tier_flag=(i&32)>>5;this.general_profile_idc=i&31;this.general_profile_compatibility=e.readUint32();this.general_constraint_indicator=e.readUint8Array(6);this.general_level_idc=e.readUint8();this.min_spatial_segmentation_idc=e.readUint16()&4095;this.parallelismType=e.readUint8()&3;this.chromaFormat=e.readUint8()&3;this.bitDepthLumaMinus8=e.readUint8()&7;this.bitDepthChromaMinus8=e.readUint8()&7;this.avgFrameRate=e.readUint16();i=e.readUint8();this.constantFrameRate=i>>6;this.numTemporalLayers=(i&13)>>3;this.temporalIdNested=(i&4)>>2;this.lengthSizeMinusOne=i&3;this.nalu_arrays=[];numOfArrays=e.readUint8();for(t=0;t>7;s.nalu_type=i&63;numNalus=e.readUint16();for(j=0;j>=1}t+=f(n,0);t+=".";if(this.hvcC.general_tier_flag===0){t+="L"}else{t+="H"}t+=this.hvcC.general_level_idc;var i=false;var s="";for(e=5;e>=0;e--){if(this.hvcC.general_constraint_indicator[e]||i){s="."+f(this.hvcC.general_constraint_indicator[e],0)+s;i=true}}t+=s}return t};a.mp4aBox.prototype.getCodec=function(){var e=a.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var t=this.esds.esd.getOTI();var r=this.esds.esd.getAudioConfig();return e+"."+f(t)+(r?"."+r:"")}else{return e}};a.esdsBox.prototype.parse=function(e){this.parseFullHeader(e);this.data=e.readUint8Array(this.size);this.size=0;var t=new s;this.esd=t.parseOneDescriptor(new n(this.data.buffer,0,n.BIG_ENDIAN))};a.txtCBox.prototype.parse=function(e){this.parseFullHeader(e);this.config=e.readCString()};a.cttsBox.prototype.parse=function(e){var t;var r;this.parseFullHeader(e);t=e.readUint32();this.sample_counts=[];this.sample_offsets=[];if(this.version===0){for(r=0;rt&&this.flags&a.TFHD_FLAG_BASE_DATA_OFFSET){this.base_data_offset=e.readUint64();t+=8}else{this.base_data_offset=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_DESC){this.default_sample_description_index=e.readUint32();t+=4}else{this.default_sample_description_index=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_DUR){this.default_sample_duration=e.readUint32();t+=4}else{this.default_sample_duration=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_SIZE){this.default_sample_size=e.readUint32();t+=4}else{this.default_sample_size=0}if(this.size>t&&this.flags&a.TFHD_FLAG_SAMPLE_FLAGS){this.default_sample_flags=e.readUint32();t+=4}else{this.default_sample_flags=0}};a.TRUN_FLAGS_DATA_OFFSET=1;a.TRUN_FLAGS_FIRST_FLAG=4;a.TRUN_FLAGS_DURATION=256;a.TRUN_FLAGS_SIZE=512;a.TRUN_FLAGS_FLAGS=1024;a.TRUN_FLAGS_CTS_OFFSET=2048;a.trunBox.prototype.parse=function(e){var t=0;this.parseFullHeader(e);this.sample_count=e.readUint32();t+=4;if(this.size>t&&this.flags&a.TRUN_FLAGS_DATA_OFFSET){this.data_offset=e.readInt32();t+=4}else{this.data_offset=0}if(this.size>t&&this.flags&a.TRUN_FLAGS_FIRST_FLAG){this.first_sample_flags=e.readUint32();t+=4}else{this.first_sample_flags=0}this.sample_duration=[];this.sample_size=[];this.sample_flags=[];this.sample_composition_time_offset=[];if(this.size>t){for(var r=0;r0){for(r=0;rn.MAX_SIZE){this.size+=8}o.d("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.position+(t||""));if(this.size>n.MAX_SIZE){e.writeUint32(1)}else{this.sizePosition=e.position;e.writeUint32(this.size)}e.writeString(this.type,null,4);if(this.size>n.MAX_SIZE){e.writeUint64(this.size)}};a.FullBox.prototype.writeHeader=function(e){this.size+=4;a.Box.prototype.writeHeader.call(this,e," v="+this.version+" f="+this.flags);e.writeUint8(this.version);e.writeUint24(this.flags)};a.Box.prototype.write=function(e){if(this.type==="mdat"){if(this.data){this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}}else{this.size=this.data.length;this.writeHeader(e);e.writeUint8Array(this.data)}};a.ContainerBox.prototype.write=function(e){this.size=0;this.writeHeader(e);for(var t=0;t>3}else{return null}};a.DecoderConfigDescriptor=function(e){a.Descriptor.call(this,t,e)};a.DecoderConfigDescriptor.prototype=new a.Descriptor;a.DecoderConfigDescriptor.prototype.parse=function(e){this.oti=e.readUint8();this.streamType=e.readUint8();this.bufferSize=e.readUint24();this.maxBitrate=e.readUint32();this.avgBitrate=e.readUint32();this.size-=13;this.parseRemainingDescriptors(e)};a.DecoderSpecificInfo=function(e){a.Descriptor.call(this,r,e)};a.DecoderSpecificInfo.prototype=new a.Descriptor;a.SLConfigDescriptor=function(e){a.Descriptor.call(this,i,e)};a.SLConfigDescriptor.prototype=new a.Descriptor;return this};t.exports=i},{"./log":66}],65:[function(e,t,r){var n=e("./box");var i=e("./DataStream");var s=e("./log");var o=function(e){this.stream=e;this.boxes=[];this.mdats=[];this.moofs=[];this.isProgressive=false;this.lastMoofIndex=0;this.lastBoxStartPosition=0;this.parsingMdat=null;this.moovStartFound=false;this.samplesDataSize=0;this.nextParsePosition=0};t.exports=o;o.prototype.mergeNextBuffer=function(){var e;if(this.stream.bufferIndex+1"+this.stream.buffer.byteLength+")");return true}else{return false}}else{return false}};o.prototype.parse=function(){var e;var t;var r;s.d("ISOFile","Starting parsing with buffer #"+this.stream.bufferIndex+" (fileStart: "+this.stream.buffer.fileStart+" - Length: "+this.stream.buffer.byteLength+") from position "+this.lastBoxStartPosition+" ("+(this.stream.buffer.fileStart+this.lastBoxStartPosition)+" in the file)");this.stream.seek(this.lastBoxStartPosition);while(true){if(this.parsingMdat!==null){r=this.parsingMdat;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){s.d("ISOFile","Found 'mdat' end in buffer #"+this.stream.bufferIndex);this.parsingMdat=null;continue}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex);return}}else{this.lastBoxStartPosition=this.stream.position;t=n.parseOneBox(this.stream);if(t.code===n.ERR_NOT_ENOUGH_DATA){if(t.type==="mdat"){r=new n[t.type+"Box"](t.size-t.hdr_size);this.parsingMdat=r;this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+this.stream.position;r.hdr_size=t.hdr_size;this.stream.buffer.usedBytes+=t.hdr_size;e=this.reposition(false,r.fileStart+r.hdr_size+r.size);if(e){this.parsingMdat=null;continue}else{if(!this.moovStartFound){this.nextParsePosition=r.fileStart+r.size+r.hdr_size}else{this.nextParsePosition=this.findEndContiguousBuf(this.stream.bufferIndex)}return}}else{if(t.type==="moov"){this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}}else if(t.type==="free"){e=this.reposition(false,this.stream.buffer.fileStart+this.stream.position+t.size);if(e){continue}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size;return}}merged=this.mergeNextBuffer();if(merged){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength;continue}else{if(!t.type){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{if(this.moovStartFound){this.nextParsePosition=this.stream.buffer.fileStart+this.stream.buffer.byteLength}else{this.nextParsePosition=this.stream.buffer.fileStart+this.stream.position+t.size}}return}}}else{r=t.box;this.boxes.push(r);switch(r.type){case"mdat":this.mdats.push(r);r.fileStart=this.stream.buffer.fileStart+r.start;break;case"moof":this.moofs.push(r);break;case"moov":this.moovStartFound=true;if(this.mdats.length===0){this.isProgressive=true}default:if(this[r.type]!==undefined){s.w("ISOFile","Duplicate Box of type: "+r.type+", overriding previous occurrence")}this[r.type]=r;break}if(r.type==="mdat"){this.stream.buffer.usedBytes+=r.hdr_size}else{this.stream.buffer.usedBytes+=t.size}}}}};o.prototype.reposition=function(e,t){var r;r=this.findPosition(e,t);if(r!==-1){this.stream.buffer=this.stream.nextBuffers[r];this.stream.bufferIndex=r;this.stream.position=t-this.stream.buffer.fileStart;s.d("ISOFile","Repositioning parser at buffer position: "+this.stream.position);return true}else{return false}};o.prototype.findPosition=function(e,t){var r;var n=null;var i=-1;if(e===true){r=0}else{r=this.stream.bufferIndex}while(r=t){s.d("ISOFile","Found position in existing buffer #"+i);return i}else{return-1}}else{return-1}};o.prototype.findEndContiguousBuf=function(e){var t;var r;var n;r=this.stream.nextBuffers[e];if(this.stream.nextBuffers.length>e+1){for(t=e+1;t-1){this.moov.boxes.splice(r,1)}this.moov.mvex=null}this.moov.mvex=new n.mvexBox;this.moov.boxes.push(this.moov.mvex);this.moov.mvex.mehd=new n.mehdBox;this.moov.mvex.boxes.push(this.moov.mvex.mehd);this.moov.mvex.mehd.fragment_duration=this.initial_duration;for(t=0;t0?this.moov.traks[t].samples[0].duration:0;o.default_sample_size=0;o.default_sample_flags=1<<16}this.moov.write(e)};o.prototype.resetTables=function(){var e;var t,r,n,i,s,o,a,f;this.initial_duration=this.moov.mvhd.duration;this.moov.mvhd.duration=0;for(e=0;eg){_++;if(g<0){g=0}g+=a.sample_counts[_]}if(t>0){n.samples[t-1].duration=a.sample_deltas[_];x.dts=n.samples[t-1].dts+n.samples[t-1].duration}else{x.dts=0}if(f){if(t>y){b++;y+=f.sample_counts[b]}x.cts=n.samples[t].dts+f.sample_offsets[b]}else{x.cts=x.dts}if(u){if(t==u.sample_numbers[w]-1){x.is_rap=true;w++}else{x.is_rap=false}}else{x.is_rap=true}if(l){if(l.samples[subs_entry_index].sample_delta+last_subs_sample_index==t){x.subsamples=l.samples[subs_entry_index].subsamples;last_subs_sample_index+=l.samples[subs_entry_index].sample_delta}}}if(t>0)n.samples[t-1].duration=n.mdia.mdhd.duration-n.samples[t-1].dts}};o.prototype.updateSampleLists=function(){var e,t,r;var i,s,o,a;var f;var u,h,l,c,d;var p;while(this.lastMoofIndex0){p.dts=c.samples[c.samples.length-2].dts+c.samples[c.samples.length-2].duration}else{if(l.tfdt){p.dts=l.tfdt.baseMediaDecodeTime}else{p.dts=0}c.first_traf_merged=true}p.cts=p.dts;if(m.flags&n.TRUN_FLAGS_CTS_OFFSET){p.cts=p.dts+m.sample_composition_time_offset[r]}sample_flags=a;if(m.flags&n.TRUN_FLAGS_FLAGS){sample_flags=m.sample_flags[r]}else if(r===0&&m.flags&n.TRUN_FLAGS_FIRST_FLAG){sample_flags=m.first_sample_flags}p.is_rap=sample_flags>>16&1?false:true;var v=l.tfhd.flags&n.TFHD_FLAG_BASE_DATA_OFFSET?true:false;var g=l.tfhd.flags&n.TFHD_FLAG_DEFAULT_BASE_IS_MOOF?true:false;var _=m.flags&n.TRUN_FLAGS_DATA_OFFSET?true:false;var y=0;if(!v){if(!g){if(t===0){y=h.fileStart}else{y=f}}else{y=h.fileStart}}else{y=l.tfhd.base_data_offset}if(t===0&&r===0){if(_){p.offset=y+m.data_offset}else{p.offset=y}}else{p.offset=f}f=p.offset+p.size}}if(l.subs){var b=l.first_sample_index;for(t=0;t0){t+=","}t+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return t};o.prototype.getTrexById=function(e){var t;if(!this.originalMvex)return null;for(t=0;t=r.fileStart&&o.offset+o.alreadyRead=o){console.debug("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},i:function(t,r){if(i>=o){console.info("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",r)}},w:function(t,i){if(r>=o){console.warn("["+n.getDurationString(new Date-e,1e3)+"]","["+t+"]",i)}},e:function(r,i){if(t>=o){console.error("["+n.getDurationString(new Date-e,1e3)+"]","["+r+"]",i)}}};return a}();t.exports=n;n.getDurationString=function(e,t){function r(e,t){var r=""+e;var n=r.split(".");while(n[0].length0){var r="";for(var i=0;i0)r+=",";r+="["+n.getDurationString(e.start(i))+","+n.getDurationString(e.end(i))+"]"}return r}else{return"(empty)"}}},{}],67:[function(e,t,r){var n=e("./box");var s=e("./DataStream");var o=e("./isofile");var a=e("./log");var f=function(){this.inputStream=null;this.nextBuffers=[];this.inputIsoFile=null;this.onMoovStart=null;this.moovStartSent=false;this.onReady=null;this.readySent=false;this.onSegment=null;this.onSamples=null;this.onError=null;this.sampleListBuilt=false;this.fragmentedTracks=[];this.extractedTracks=[];this.isFragmentationStarted=false;this.nextMoofNumber=0};t.exports=f;f.prototype.setSegmentOptions=function(e,t,r){var n=this.inputIsoFile.getTrackById(e);if(n){var i={};this.fragmentedTracks.push(i);i.id=e;i.user=t;i.trak=n;n.nextSample=0;i.segmentStream=null;i.nb_samples=1e3;i.rapAlignement=true;if(r){if(r.nbSamples)i.nb_samples=r.nbSamples;if(r.rapAlignement)i.rapAlignement=r.rapAlignement}}};f.prototype.unsetSegmentOptions=function(e){var t=-1;for(var r=0;r-1){this.fragmentedTracks.splice(t,1)}};f.prototype.setExtractionOptions=function(e,t,r){var n=this.inputIsoFile.getTrackById(e);if(n){var i={};this.extractedTracks.push(i);i.id=e;i.user=t;i.trak=n;n.nextSample=0;i.nb_samples=1e3;i.samples=[];if(r){if(r.nbSamples)i.nb_samples=r.nbSamples}}};f.prototype.unsetExtractionOptions=function(e){var t=-1;for(var r=0;r-1){this.extractedTracks.splice(t,1)}};f.prototype.createSingleSampleMoof=function(e){var t=new n.moofBox;var r=new n.mfhdBox;r.sequence_number=this.nextMoofNumber;this.nextMoofNumber++;t.boxes.push(r);var i=new n.trafBox;t.boxes.push(i);var s=new n.tfhdBox;i.boxes.push(s);s.track_id=e.track_id;s.flags=n.TFHD_FLAG_DEFAULT_BASE_IS_MOOF;var o=new n.tfdtBox;i.boxes.push(o);o.baseMediaDecodeTime=e.dts;var a=new n.trunBox;i.boxes.push(a);t.trun=a;a.flags=n.TRUN_FLAGS_DATA_OFFSET|n.TRUN_FLAGS_DURATION|n.TRUN_FLAGS_SIZE|n.TRUN_FLAGS_FLAGS|n.TRUN_FLAGS_CTS_OFFSET;a.data_offset=0;a.first_sample_flags=0;a.sample_count=1;a.sample_duration=[];a.sample_duration[0]=e.duration;a.sample_size=[];a.sample_size[0]=e.size;a.sample_flags=[];a.sample_flags[0]=0;a.sample_composition_time_offset=[];a.sample_composition_time_offset[0]=e.cts-e.dts;return t};f.prototype.createFragment=function(e,t,r,i){var o=this.inputIsoFile.getTrackById(t);var f=this.inputIsoFile.getSample(o,r);if(f==null){if(this.nextSeekPosition){this.nextSeekPosition=Math.min(o.samples[r].offset,this.nextSeekPosition)}else{this.nextSeekPosition=o.samples[r].offset}return null}var u=i||new s;u.endianness=s.BIG_ENDIAN;var h=this.createSingleSampleMoof(f);h.write(u);h.trun.data_offset=h.size+8;a.d("BoxWriter","Adjusting data_offset with new value "+h.trun.data_offset);u.adjustUint32(h.trun.data_offset_position,h.trun.data_offset);var l=new n.mdatBox;l.data=f.data;l.write(u);return u};ArrayBuffer.concat=function(e,t){a.d("ArrayBuffer","Trying to create a new buffer of size: "+(e.byteLength+t.byteLength));var r=new Uint8Array(e.byteLength+t.byteLength);r.set(new Uint8Array(e),0);r.set(new Uint8Array(t),e.byteLength);return r.buffer};f.prototype.reduceBuffer=function(e,t,r){var n;n=new Uint8Array(r);n.set(new Uint8Array(e,t,r));n.buffer.fileStart=e.fileStart+t;n.buffer.usedBytes=0;return n.buffer};f.prototype.insertBuffer=function(e){var t=true;for(var r=0;rn.byteLength){this.nextBuffers.splice(r,1);r--;continue}else{a.w("MP4Box","Buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+") already appended, ignoring")}}else{if(e.fileStart+e.byteLength<=n.fileStart){}else{e=this.reduceBuffer(e,0,n.fileStart-e.fileStart)}a.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.splice(r,0,e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}t=false;break}else if(e.fileStart0){e=this.reduceBuffer(e,i,s)}else{t=false;break}}}if(t){a.d("MP4Box","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")");this.nextBuffers.push(e);if(r===0&&this.inputStream!==null){this.inputStream.buffer=e}}};f.prototype.processSamples=function(){var e;var t;if(this.isFragmentationStarted&&this.onSegment!==null){for(e=0;e=t.samples.length){a.i("MP4Box","Sending fragmented data on track #"+r.id+" for samples ["+(t.nextSample-r.nb_samples)+","+(t.nextSample-1)+"]");if(this.onSegment){this.onSegment(r.id,r.user,r.segmentStream.buffer,t.nextSample)}r.segmentStream=null;if(r!==this.fragmentedTracks[e]){break}}}}}if(this.onSamples!==null){for(e=0;e=t.samples.length){a.d("MP4Box","Sending samples on track #"+i.id+" for sample "+t.nextSample);if(this.onSamples){this.onSamples(i.id,i.user,i.samples)}i.samples=[];if(i!==this.extractedTracks[e]){break}}}}}};f.prototype.appendBuffer=function(e){var t;var r;if(e===null||e===undefined){throw"Buffer must be defined and non empty"}if(e.fileStart===undefined){throw"Buffer must have a fileStart property"}if(e.byteLength===0){a.w("MP4Box","Ignoring empty buffer (fileStart: "+e.fileStart+")");return}e.usedBytes=0;this.insertBuffer(e);if(!this.inputStream){if(this.nextBuffers.length>0){r=this.nextBuffers[0];if(r.fileStart===0){this.inputStream=new s(r,0,s.BIG_ENDIAN);this.inputStream.nextBuffers=this.nextBuffers;this.inputStream.bufferIndex=0}else{a.w("MP4Box","The first buffer should have a fileStart of 0");return}}else{a.w("MP4Box","No buffer to start parsing from");return}}if(!this.inputIsoFile){this.inputIsoFile=new o(this.inputStream)}this.inputIsoFile.parse();if(this.inputIsoFile.moovStartFound&&!this.moovStartSent){this.moovStartSent=true;if(this.onMoovStart)this.onMoovStart()}if(this.inputIsoFile.moov){if(!this.sampleListBuilt){this.inputIsoFile.buildSampleLists();this.sampleListBuilt=true}this.inputIsoFile.updateSampleLists();if(this.onReady&&!this.readySent){var n=this.getInfo();this.readySent=true;this.onReady(n)}this.processSamples();if(this.nextSeekPosition){t=this.nextSeekPosition;this.nextSeekPosition=undefined}else{t=this.inputIsoFile.nextParsePosition}var i=this.inputIsoFile.findPosition(true,t);if(i!==-1){t=this.inputIsoFile.findEndContiguousBuf(i)}a.i("MP4Box","Next buffer to fetch should have a fileStart position of "+t);return t}else{if(this.inputIsoFile!==null){return this.inputIsoFile.nextParsePosition}else{return 0}}};f.prototype.getInfo=function(){var e={};var t;var r;var n;var s=new Date(4,0,1,0,0,0,0).getTime();e.duration=this.inputIsoFile.moov.mvhd.duration;e.timescale=this.inputIsoFile.moov.mvhd.timescale;e.isFragmented=this.inputIsoFile.moov.mvex!=null;if(e.isFragmented&&this.inputIsoFile.moov.mvex.mehd){e.fragment_duration=this.inputIsoFile.moov.mvex.mehd.fragment_duration}else{e.fragment_duration=0}e.isProgressive=this.inputIsoFile.isProgressive;e.hasIOD=this.inputIsoFile.moov.iods!=null;e.brands=[];e.brands.push(this.inputIsoFile.ftyp.major_brand);e.brands=e.brands.concat(this.inputIsoFile.ftyp.compatible_brands);e.created=new Date(s+this.inputIsoFile.moov.mvhd.creation_time*1e3);e.modified=new Date(s+this.inputIsoFile.moov.mvhd.modification_time*1e3);e.tracks=[];e.audioTracks=[];e.videoTracks=[];e.subtitleTracks=[];e.metadataTracks=[];e.hintTracks=[];e.otherTracks=[];for(i=0;ie*i.timescale){f=r.samples[n-1].offset;h=n-1;break}if(t&&i.is_rap){s=i.offset;o=i.cts;u=n}}if(t){r.nextSample=u;a.i("MP4Box","Seeking to RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+a.getDurationString(o,l)+" and offset: "+s);return{offset:s,time:o/l}}else{r.nextSample=h;a.i("MP4Box","Seeking to non-RAP sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+a.getDurationString(e)+" and offset: "+s);return{offset:f,time:e}}};f.prototype.seek=function(e,t){var r=this.inputIsoFile.moov;var n;var i;var s;var o={offset:Infinity,time:Infinity};if(!this.inputIsoFile.moov){throw"Cannot seek: moov not received!"}else{for(s=0;s1e4)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);var f=(t[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return r*a;case"days":case"day":case"d":return r*o;case"hours":case"hour":case"hrs":case"hr":case"h":return r*s;case"minutes":case"minute":case"mins":case"min":case"m":return r*i;case"seconds":case"second":case"secs":case"sec":case"s":return r*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r}}function u(e){if(e>=o)return Math.round(e/o)+"d";if(e>=s)return Math.round(e/s)+"h";if(e>=i)return Math.round(e/i)+"m";if(e>=n)return Math.round(e/n)+"s";return e+"ms"}function h(e){return l(e,o,"day")||l(e,s,"hour")||l(e,i,"minute")||l(e,n,"second")||e+" ms"}function l(e,t,r){if(e0?[e["url-list"]]:[]}t.urlList=(e["url-list"]||[]).map(function(e){return e.toString()});var a=e.info.files||[e.info];t.files=a.map(function(e,r){var n=[].concat(t.name,e["path.utf-8"]||e.path||[]).map(function(e){return e.toString()});return{path:i.join.apply(null,[i.sep].concat(n)).slice(1),name:n[n.length-1],length:e.length,offset:a.slice(0,r).reduce(u,0)}});t.length=a.reduce(u,0);var f=t.files[t.files.length-1];t.pieceLength=e.info["piece length"];t.lastPieceLength=(f.offset+f.length)%t.pieceLength||t.pieceLength;t.pieces=h(e.info.pieces);return t}function f(e){var t={info:e.info};t["announce-list"]=e.announce.map(function(e){if(!t.announce)t.announce=e;e=new r(e,"utf8");return[e]});if(e.created){t["creation date"]=e.created.getTime()/1e3|0}if(e.urlList){t["url-list"]=e.urlList}return n.encode(t)}function u(e,t){return e+t.length}function h(e){var t=[];for(var r=0;r=0;n--){var i=e[n];if(i==="."){e.splice(n,1)}else if(i===".."){e.splice(n,1);r++}else if(r){e.splice(n,1);r--}}if(t){for(;r--;r){e.unshift("..")}}return e}var n=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var i=function(e){return n.exec(e).slice(1)};r.resolve=function(){var r="",n=false;for(var i=arguments.length-1;i>=-1&&!n;i--){var o=i>=0?arguments[i]:e.cwd();if(typeof o!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!o){continue}r=o+"/"+r;n=o.charAt(0)==="/"}r=t(s(r.split("/"),function(e){return!!e}),!n).join("/");return(n?"/":"")+r||"."};r.normalize=function(e){var n=r.isAbsolute(e),i=o(e,-1)==="/";e=t(s(e.split("/"),function(e){return!!e}),!n).join("/");if(!e&&!n){e="."}if(e&&i){e+="/"}return(n?"/":"")+e};r.isAbsolute=function(e){return e.charAt(0)==="/"};r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(s(e,function(e,t){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))};r.relative=function(e,t){e=r.resolve(e).substr(1);t=r.resolve(t).substr(1);function n(e){var t=0;for(;t=0;r--){if(e[r]!=="")break}if(t>r)return[];return e.slice(t,r-t+1)}var i=n(e.split("/"));var s=n(t.split("/"));var o=Math.min(i.length,s.length);var a=o;for(var f=0;f0){t.exports=e.nextTick}else{t.exports=r}function r(t){var r=new Array(arguments.length-1);var n=0;while(n1){for(var r=1;r0;return h(i,o,a,function(e){if(!r)r=e;if(e)n.forEach(l);if(o)return;n.forEach(l);t(r)})});return e.reduce(c)};t.exports=d},{"end-of-stream":43,fs:32,once:70}],78:[function(t,r,n){(function(t){(function(i){var s=typeof n=="object"&&n&&!n.nodeType&&n;var o=typeof r=="object"&&r&&!r.nodeType&&r;var a=typeof t=="object"&&t;if(a.global===a||a.window===a||a.self===a){i=a}var f,u=2147483647,h=36,l=1,c=26,d=38,p=700,m=72,v=128,g="-",_=/^xn--/,y=/[^\x20-\x7E]/,b=/[\x2E\u3002\uFF0E\uFF61]/g,w={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},S=h-l,x=Math.floor,k=String.fromCharCode,E;function A(e){throw RangeError(w[e])}function U(e,t){var r=e.length;var n=[];while(r--){n[r]=t(e[r])}return n}function T(e,t){var r=e.split("@");var n="";if(r.length>1){n=r[0]+"@";e=r[1]}e=e.replace(b,".");var i=e.split(".");var s=U(i,t).join(".");return n+s}function I(e){var t=[],r=0,n=e.length,i,s;while(r=55296&&i<=56319&&r65535){e-=65536;t+=k(e>>>10&1023|55296);e=56320|e&1023}t+=k(e);return t}).join("")}function B(e){if(e-48<10){return e-22}if(e-65<26){return e-65}if(e-97<26){return e-97}return h}function C(e,t){return e+22+75*(e<26)-((t!=0)<<5)}function R(e,t,r){var n=0;e=r?x(e/p):e>>1;e+=x(e/t);for(;e>S*c>>1;n+=h){e=x(e/S)}return x(n+(S+1)*e/(e+d))}function P(e){var t=[],r=e.length,n,i=0,s=v,o=m,a,f,d,p,_,y,b,w,S;a=e.lastIndexOf(g);if(a<0){a=0}for(f=0;f=128){A("not-basic")}t.push(e.charCodeAt(f))}for(d=a>0?a+1:0;d=r){A("invalid-input")}b=B(e.charCodeAt(d++));if(b>=h||b>x((u-i)/_)){A("overflow")}i+=b*_;w=y<=o?l:y>=o+c?c:y-o;if(bx(u/S)){A("overflow")}_*=S}n=t.length+1;o=R(i-p,n,p==0);if(x(i/n)>u-s){A("overflow")}s+=x(i/n);i%=n;t.splice(i++,0,s)}return L(t)}function F(e){var t,r,n,i,s,o,a,f,d,p,_,y=[],b,w,S,E;e=I(e);b=e.length;t=v;r=0;s=m;for(o=0;o=t&&_x((u-r)/w)){A("overflow")}r+=(a-t)*w;t=a;for(o=0;ou){A("overflow")}if(_==t){for(f=r,d=h;;d+=h){p=d<=s?l:d>=s+c?c:d-s;if(f0&&u>f){u=f}for(var h=0;h=0){d=l.substr(0,c);p=l.substr(c+1)}else{d=l;p=""}m=decodeURIComponent(d);v=decodeURIComponent(p);if(!n(o,m)){o[m]=v}else if(i(o[m])){o[m].push(v)}else{o[m]=[o[m],v]}}return o};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}},{}],80:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,a){t=t||"&";r=r||"=";if(e===null){e=undefined}if(typeof e==="object"){return s(o(e),function(o){var a=encodeURIComponent(n(o))+r;if(i(e[o])){return s(e[o],function(e){return a+encodeURIComponent(n(e))}).join(t)}else{return a+encodeURIComponent(n(e[o]))}}).join(t)}if(!a)return"";return encodeURIComponent(n(a))+r+encodeURIComponent(n(e))};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};function s(e,t){if(e.map)return e.map(t);var r=[];for(var n=0;n0){if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var o=new Error("stream.unshift() after end event");e.emit("error",o)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)S(e)}k(e,t)}}else if(!i){t.reading=false}return v(t)}function v(e){return!e.ended&&(e.needReadable||e.length=g){e=g}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function y(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(e===null||isNaN(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=_(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else{return t.length}}return e}p.prototype.read=function(e){l("read",e);var t=this._readableState;var r=e;if(typeof e!=="number"||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){l("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)C(this);else S(this);return null}e=y(e,t);if(e===0&&t.ended){if(t.length===0)C(this);return null}var n=t.needReadable;l("need readable",n);if(t.length===0||t.length-e0)i=B(e,t);else i=null;if(i===null){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)C(this);if(i!==null)this.emit("data",i);return i};function b(e,t){var r=null;if(!s.isBuffer(t)&&typeof t!=="string"&&t!==null&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function w(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;S(e)}function S(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){l("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)n(x,e);else x(e)}}function x(e){l("emit readable");e.emit("readable");L(e)}function k(e,t){if(!t.readingMore){t.readingMore=true;n(E,e,t)}}function E(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(i)a=r.join("");else if(r.length===1)a=r[0];else a=s.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;n(R,t,e)}}function R(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function P(e,t){for(var r=0,n=e.length;r-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e};function p(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=new i(t,r)}return t}function m(e,t,r,n,s){r=p(t,r,n);if(i.isBuffer(r))n="buffer";var o=t.objectMode?1:r.length;t.length+=o;var a=t.length0;e+=1);return e};var o=function(e,t){for(var r=t>>2;r>2]|=128<<24-(t%4<<3);e[((t>>2)+2&~15)+14]=r>>29;e[((t>>2)+2&~15)+15]=r<<3};var f=function(e,t,r,n,i){var s=this,o,a=i%4,f=n%4,u=n-f;if(u>0){switch(a){case 0:e[i+3|0]=s.charCodeAt(r);case 1:e[i+2|0]=s.charCodeAt(r+1);case 2:e[i+1|0]=s.charCodeAt(r+2);case 3:e[i|0]=s.charCodeAt(r+3)}}for(o=a;o>2]=s.charCodeAt(r+o)<<24|s.charCodeAt(r+o+1)<<16|s.charCodeAt(r+o+2)<<8|s.charCodeAt(r+o+3)}switch(f){case 3:e[i+u+1|0]=s.charCodeAt(r+u+2);case 2:e[i+u+2|0]=s.charCodeAt(r+u+1);case 1:e[i+u+3|0]=s.charCodeAt(r+u)}};var u=function(e,t,r,n,i){var s=this,o,a=i%4,f=n%4,u=n-f;if(u>0){switch(a){case 0:e[i+3|0]=s[r];case 1:e[i+2|0]=s[r+1];case 2:e[i+1|0]=s[r+2];case 3:e[i|0]=s[r+3]}}for(o=4-a;o>2]=s[r+o]<<24|s[r+o+1]<<16|s[r+o+2]<<8|s[r+o+3]}switch(f){case 3:e[i+u+1|0]=s[r+u+2];case 2:e[i+u+2|0]=s[r+u+1];case 1:e[i+u+3|0]=s[r+u]}};var h=function(e,t,r,n,s){var o=this,a,f=s%4,u=n%4,h=n-u;var l=new Uint8Array(i.readAsArrayBuffer(o.slice(r,r+n)));if(h>0){switch(f){case 0:e[s+3|0]=l[0];case 1:e[s+2|0]=l[1];case 2:e[s+1|0]=l[2];case 3:e[s|0]=l[3]}}for(a=4-f;a>2]=l[a]<<24|l[a+1]<<16|l[a+2]<<8|l[a+3]}switch(u){case 3:e[s+h+1|0]=l[h+2];case 2:e[s+h+2|0]=l[h+1];case 1:e[s+h+3|0]=l[h]}};var l=function(e){switch(r.getDataType(e)){case"string":return f.bind(e);case"array":return u.bind(e);case"buffer":return u.bind(e);case"arraybuffer":return u.bind(new Uint8Array(e));case"view":return u.bind(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));case"blob":return h.bind(e)}};var c=function(e,t){switch(r.getDataType(e)){case"string":return e.slice(t);case"array":return e.slice(t);case"buffer":return e.slice(t);case"arraybuffer":return e.slice(t);case"view":return e.buffer.slice(t)}};var d=function(e){var t,r,n="0123456789abcdef",i=[],s=new Uint8Array(e);for(t=0;t>4&15)+n.charAt(r>>0&15)}return i.join("")};var p=function(e){var t;if(e<=65536)return 65536;if(e<16777216){for(t=1;t0){throw new Error("Chunk size must be a multiple of 128 bit")}t.maxChunkLen=e;t.padMaxChunkLen=s(e);t.heap=new ArrayBuffer(p(t.padMaxChunkLen+320+20));t.h32=new Int32Array(t.heap);t.h8=new Int8Array(t.heap);t.core=new n._core({Int32Array:Int32Array,DataView:DataView},{},t.heap);t.buffer=null};m(e||64*1024);var v=function(e,t){var r=new Int32Array(e,t+320,5);r[0]=1732584193;r[1]=-271733879;r[2]=-1732584194;r[3]=271733878;r[4]=-1009589776};var g=function(e,r){var n=s(e);var i=new Int32Array(t.heap,0,n>>2);o(i,e);a(i,e,r);return n};var _=function(e,r,n){l(e)(t.h8,t.h32,r,n,0)};var y=function(e,r,n,i,s){var o=n;if(s){o=g(n,i)}_(e,r,n);t.core.hash(o,t.padMaxChunkLen)};var b=function(e,t){var r=new Int32Array(e,t+320,5);var n=new Int32Array(5);var i=new DataView(n.buffer);i.setInt32(0,r[0],false);i.setInt32(4,r[1],false);i.setInt32(8,r[2],false);i.setInt32(12,r[3],false);i.setInt32(16,r[4],false);return n};var w=this.rawDigest=function(e){var r=e.byteLength||e.length||e.size||0;v(t.heap,t.padMaxChunkLen);var n=0,i=t.maxChunkLen,s;for(n=0;r>n+i;n+=i){y(e,n,i,r,false)}y(e,n,r-n,r,true);return b(t.heap,t.padMaxChunkLen)};this.digest=this.digestFromString=this.digestFromBuffer=this.digestFromArrayBuffer=function(e){return d(w(e).buffer)}}n._core=function o(e,t,r){"use asm";var n=new e.Int32Array(r);function i(e,t){e=e|0;t=t|0;var r=0,i=0,s=0,o=0,a=0,f=0,u=0,h=0,l=0,c=0,d=0,p=0,m=0,v=0;s=n[t+320>>2]|0;a=n[t+324>>2]|0;u=n[t+328>>2]|0;l=n[t+332>>2]|0;d=n[t+336>>2]|0;for(r=0;(r|0)<(e|0);r=r+64|0){o=s;f=a;h=u;c=l;p=d;for(i=0;(i|0)<64;i=i+4|0){v=n[r+i>>2]|0;m=((s<<5|s>>>27)+(a&u|~a&l)|0)+((v+d|0)+1518500249|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[e+i>>2]=v}for(i=e+64|0;(i|0)<(e+80|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a&u|~a&l)|0)+((v+d|0)+1518500249|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+80|0;(i|0)<(e+160|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a^u^l)|0)+((v+d|0)+1859775393|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+160|0;(i|0)<(e+240|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a&u|a&l|u&l)|0)+((v+d|0)-1894007588|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}for(i=e+240|0;(i|0)<(e+320|0);i=i+4|0){v=(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])<<1|(n[i-12>>2]^n[i-32>>2]^n[i-56>>2]^n[i-64>>2])>>>31;m=((s<<5|s>>>27)+(a^u^l)|0)+((v+d|0)-899497514|0)|0;d=l;l=u;u=a<<30|a>>>2;a=s;s=m;n[i>>2]=v}s=s+o|0;a=a+f|0;u=u+h|0;l=l+c|0;d=d+p|0}n[t+320>>2]=s;n[t+324>>2]=a;n[t+328>>2]=u;n[t+332>>2]=l;n[t+336>>2]=d}return{hash:i}};if(typeof t!=="undefined"){t.exports=n}else if(typeof window!=="undefined"){window.Rusha=n}if(typeof FileReaderSync!=="undefined"){var i=new FileReaderSync,s=new n(4*1024*1024);self.onmessage=function a(e){var t,r=e.data.data;try{t=s.digest(r);self.postMessage({id:e.data.id,hash:t})}catch(n){self.postMessage({id:e.data.id,error:n.name})}}}})()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],96:[function(e,t,r){(function(r){t.exports=u;var n=e("xtend");var i=e("http");var s=e("https");var o=e("once");var a=e("unzip-response");var f=e("url");function u(e,t){e=typeof e==="string"?{url:e}:n(e);t=o(t);if(e.url)h(e);if(e.headers==null)e.headers={};if(e.maxRedirects==null)e.maxRedirects=10;var r=e.body;e.body=undefined;if(r&&!e.method)e.method="POST";var f=Object.keys(e.headers).some(function(e){return e.toLowerCase()==="accept-encoding"});if(!f)e.headers["accept-encoding"]="gzip, deflate";var l=e.protocol==="https:"?s:i;var c=l.request(e,function(r){if(r.statusCode>=300&&r.statusCode<400&&"location"in r.headers){e.url=r.headers.location;h(e);r.resume();e.maxRedirects-=1;if(e.maxRedirects>0)u(e,t);else t(new Error("too many redirects"));return}t(null,typeof a==="function"?a(r):r)});c.on("error",t);c.end(r);return c}t.exports.concat=function(e,t){return u(e,function(e,n){if(e)return t(e);var i=[];n.on("data",function(e){i.push(e)});n.on("end",function(){t(null,r.concat(i),n)})})};["get","post","put","patch","head","delete"].forEach(function(e){t.exports[e]=function(t,r){if(typeof t==="string")t={url:t};t.method=e.toUpperCase();return u(t,r)}});function h(e){var t=f.parse(e.url);if(t.hostname)e.hostname=t.hostname;if(t.port)e.port=t.port;if(t.protocol)e.protocol=t.protocol;e.path=t.path;delete e.url}}).call(this,e("buffer").Buffer)},{buffer:33,http:102,https:49,once:70,"unzip-response":31,url:113,xtend:119}],97:[function(e,t,r){(function(r){t.exports=l;var n=e("debug")("simple-peer");var i=e("get-browser-rtc");var s=e("hat");var o=e("inherits");var a=e("is-typedarray");var f=e("once");var u=e("stream");var h=e("typedarray-to-buffer");o(l,u.Duplex);function l(e){var t=this;if(!(t instanceof l))return new l(e);t._debug("new peer %o",e);if(!e)e={};e.allowHalfOpen=false;if(e.highWaterMark==null)e.highWaterMark=1024*1024;u.Duplex.call(t,e);t.initiator=e.initiator||false;t.channelConfig=e.channelConfig||l.channelConfig;t.channelName=e.channelName||s(160);if(!e.initiator)t.channelName=null;t.config=e.config||l.config;t.constraints=e.constraints||l.constraints;t.reconnectTimer=e.reconnectTimer||0;t.sdpTransform=e.sdpTransform||function(e){return e};t.stream=e.stream||false;t.trickle=e.trickle!==undefined?e.trickle:true;t.destroyed=false;t.connected=false;t.remoteAddress=undefined;t.remoteFamily=undefined;t.remotePort=undefined;t.localAddress=undefined;t.localPort=undefined;t._wrtc=e.wrtc||i();if(!t._wrtc){if(typeof window==="undefined"){throw new Error("No WebRTC support: Specify `opts.wrtc` option in this environment")}else{throw new Error("No WebRTC support: Not a supported browser")}}t._maxBufferedAmount=e.highWaterMark;t._pcReady=false;t._channelReady=false;t._iceComplete=false;t._channel=null;t._pendingCandidates=[];t._chunk=null;t._cb=null;t._interval=null;t._reconnectTimeout=null;t._pc=new t._wrtc.RTCPeerConnection(t.config,t.constraints);t._pc.oniceconnectionstatechange=t._onIceConnectionStateChange.bind(t);t._pc.onsignalingstatechange=t._onSignalingStateChange.bind(t);t._pc.onicecandidate=t._onIceCandidate.bind(t);if(t.stream)t._pc.addStream(t.stream);t._pc.onaddstream=t._onAddStream.bind(t);if(t.initiator){t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)});t._pc.onnegotiationneeded=f(t._createOffer.bind(t));if(typeof window==="undefined"||!window.webkitRTCPeerConnection){t._pc.onnegotiationneeded()}}else{t._pc.ondatachannel=t._setupData.bind(t)}t.on("finish",function(){if(t.connected){setTimeout(function(){t._destroy(); +},100)}else{t.once("connect",function(){setTimeout(function(){t._destroy()},100)})}})}l.WEBRTC_SUPPORT=!!i();l.config={iceServers:[{url:"stun:23.21.150.121",urls:"stun:23.21.150.121"}]};l.constraints={};l.channelConfig={};Object.defineProperty(l.prototype,"bufferSize",{get:function(){var e=this;return e._channel&&e._channel.bufferedAmount||0}});l.prototype.address=function(){var e=this;return{port:e.localPort,family:"IPv4",address:e.localAddress}};l.prototype.signal=function(e){var t=this;if(t.destroyed)throw new Error("cannot signal after peer is destroyed");if(typeof e==="string"){try{e=JSON.parse(e)}catch(r){e={}}}t._debug("signal()");function n(e){try{t._pc.addIceCandidate(new t._wrtc.RTCIceCandidate(e),c,t._onError.bind(t))}catch(r){t._destroy(new Error("error adding candidate: "+r.message))}}if(e.sdp){t._pc.setRemoteDescription(new t._wrtc.RTCSessionDescription(e),function(){if(t.destroyed)return;if(t._pc.remoteDescription.type==="offer")t._createAnswer();t._pendingCandidates.forEach(n);t._pendingCandidates=[]},t._onError.bind(t))}if(e.candidate){if(t._pc.remoteDescription)n(e.candidate);else t._pendingCandidates.push(e.candidate)}if(!e.sdp&&!e.candidate){t._destroy(new Error("signal() called with invalid signal data"))}};l.prototype.send=function(e){var t=this;if(!a.strict(e)&&!(e instanceof ArrayBuffer)&&!r.isBuffer(e)&&typeof e!=="string"&&(typeof Blob==="undefined"||!(e instanceof Blob))){e=JSON.stringify(e)}if(r.isBuffer(e)&&!a.strict(e)){e=new Uint8Array(e)}var n=e.length||e.byteLength||e.size;t._channel.send(e);t._debug("write: %d bytes",n)};l.prototype.destroy=function(e){var t=this;t._destroy(null,e)};l.prototype._destroy=function(e,t){var r=this;if(r.destroyed)return;if(t)r.once("close",t);r._debug("destroy (error: %s)",e&&e.message);r.readable=r.writable=false;if(!r._readableState.ended)r.push(null);if(!r._writableState.finished)r.end();r.destroyed=true;r.connected=false;r._pcReady=false;r._channelReady=false;r._chunk=null;r._cb=null;clearInterval(r._interval);clearTimeout(r._reconnectTimeout);if(r._pc){try{r._pc.close()}catch(e){}r._pc.oniceconnectionstatechange=null;r._pc.onsignalingstatechange=null;r._pc.onicecandidate=null}if(r._channel){try{r._channel.close()}catch(e){}r._channel.onmessage=null;r._channel.onopen=null;r._channel.onclose=null}r._pc=null;r._channel=null;if(e)r.emit("error",e);r.emit("close")};l.prototype._setupData=function(e){var t=this;t._channel=e.channel;t.channelName=t._channel.label;t._channel.binaryType="arraybuffer";t._channel.onmessage=t._onChannelMessage.bind(t);t._channel.onopen=t._onChannelOpen.bind(t);t._channel.onclose=t._onChannelClose.bind(t)};l.prototype._read=function(){};l.prototype._write=function(e,t,r){var n=this;if(n.destroyed)return r(new Error("cannot write after peer is destroyed"));if(n.connected){try{n.send(e)}catch(i){return n._onError(i)}if(n._channel.bufferedAmount>n._maxBufferedAmount){n._debug("start backpressure: bufferedAmount %d",n._channel.bufferedAmount);n._cb=r}else{r(null)}}else{n._debug("write before connect");n._chunk=e;n._cb=r}};l.prototype._createOffer=function(){var e=this;if(e.destroyed)return;e._pc.createOffer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,c,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.offerConstraints)};l.prototype._createAnswer=function(){var e=this;if(e.destroyed)return;e._pc.createAnswer(function(t){if(e.destroyed)return;t.sdp=e.sdpTransform(t.sdp);e._pc.setLocalDescription(t,c,e._onError.bind(e));var r=function(){var r=e._pc.localDescription||t;e._debug("signal");e.emit("signal",{type:r.type,sdp:r.sdp})};if(e.trickle||e._iceComplete)r();else e.once("_iceComplete",r)},e._onError.bind(e),e.answerConstraints)};l.prototype._onIceConnectionStateChange=function(){var e=this;if(e.destroyed)return;var t=e._pc.iceGatheringState;var r=e._pc.iceConnectionState;e._debug("iceConnectionStateChange %s %s",t,r);e.emit("iceConnectionStateChange",t,r);if(r==="connected"||r==="completed"){clearTimeout(e._reconnectTimeout);e._pcReady=true;e._maybeReady()}if(r==="disconnected"){if(e.reconnectTimer){clearTimeout(e._reconnectTimeout);e._reconnectTimeout=setTimeout(function(){e._destroy()},e.reconnectTimer)}else{e._destroy()}}if(r==="closed"){e._destroy()}};l.prototype._maybeReady=function(){var e=this;e._debug("maybeReady pc %s channel %s",e._pcReady,e._channelReady);if(e.connected||e._connecting||!e._pcReady||!e._channelReady)return;e._connecting=true;if(!e._pc.getStats){t([])}else if(typeof window!=="undefined"&&!!window.mozRTCPeerConnection){e._pc.getStats(null,function(e){var r=[];e.forEach(function(e){r.push(e)});t(r)},e._onError.bind(e))}else{e._pc.getStats(function(e){var r=[];e.result().forEach(function(e){var t={};e.names().forEach(function(r){t[r]=e.stat(r)});t.id=e.id;t.type=e.type;t.timestamp=e.timestamp;r.push(t)});t(r)})}function t(t){t.forEach(function(t){if(t.type==="remotecandidate"){e.remoteAddress=t.ipAddress;e.remotePort=Number(t.portNumber);e.remoteFamily="IPv4";e._debug("connect remote: %s:%s (%s)",e.remoteAddress,e.remotePort,e.remoteFamily)}else if(t.type==="localcandidate"&&t.candidateType==="host"){e.localAddress=t.ipAddress;e.localPort=Number(t.portNumber);e._debug("connect local: %s:%s",e.localAddress,e.localPort)}});e._connecting=false;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(r){return e._onError(r)}e._chunk=null;e._debug('sent chunk from "write before connect"');var n=e._cb;e._cb=null;n(null)}e._interval=setInterval(function(){if(!e._cb||!e._channel||e._channel.bufferedAmount>e._maxBufferedAmount)return;e._debug("ending backpressure: bufferedAmount %d",e._channel.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref();e._debug("connect");e.emit("connect")}};l.prototype._onSignalingStateChange=function(){var e=this;if(e.destroyed)return;e._debug("signalingStateChange %s",e._pc.signalingState);e.emit("signalingStateChange",e._pc.signalingState)};l.prototype._onIceCandidate=function(e){var t=this;if(t.destroyed)return;if(e.candidate&&t.trickle){t.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}})}else if(!e.candidate){t._iceComplete=true;t.emit("_iceComplete")}};l.prototype._onChannelMessage=function(e){var t=this;if(t.destroyed)return;var r=e.data;t._debug("read: %d bytes",r.byteLength||r.length);if(r instanceof ArrayBuffer){r=h(new Uint8Array(r));t.push(r)}else{try{r=JSON.parse(r)}catch(n){}t.emit("data",r)}};l.prototype._onChannelOpen=function(){var e=this;if(e.connected||e.destroyed)return;e._debug("on channel open");e._channelReady=true;e._maybeReady()};l.prototype._onChannelClose=function(){var e=this;if(e.destroyed)return;e._debug("on channel close");e._destroy()};l.prototype._onAddStream=function(e){var t=this;if(t.destroyed)return;t._debug("on add stream");t.emit("stream",e.stream)};l.prototype._onError=function(e){var t=this;if(t.destroyed)return;t._debug("error %s",e.message||e);t._destroy(e)};l.prototype._debug=function(){var e=this;var t=[].slice.call(arguments);var r=e.channelName&&e.channelName.substring(0,7);t[0]="["+r+"] "+t[0];n.apply(null,t)};function c(){}}).call(this,{isBuffer:e("../is-buffer/index.js")})},{"../is-buffer/index.js":54,debug:39,"get-browser-rtc":47,hat:48,inherits:52,"is-typedarray":56,once:70,stream:101,"typedarray-to-buffer":111}],98:[function(e,t,r){var n=e("rusha");var i=new n;var s=window.crypto||window.msCrypto||{};var o=s.subtle||s.webkitSubtle;var a=i.digest.bind(i);try{o.digest({name:"sha-1"},new Uint8Array).catch(function(){o=false})}catch(f){o=false}function u(e,t){if(!o){setTimeout(t,0,a(e));return}if(typeof e==="string"){e=h(e)}o.digest({name:"sha-1"},e).then(function r(e){t(l(new Uint8Array(e)))},function n(r){t(a(e))})}function h(e){var t=e.length;var r=new Uint8Array(t);for(var n=0;n>>4).toString(16));r.push((i&15).toString(16))}return r.join("")}t.exports=u;t.exports.sync=a},{rusha:95}],99:[function(e,t,r){(function(r){t.exports=h;var n=e("debug")("simple-websocket");var i=e("inherits");var s=e("is-typedarray");var o=e("stream");var a=e("typedarray-to-buffer");var f=e("ws");var u=typeof window!=="undefined"?window.WebSocket:f;i(h,o.Duplex);function h(e,t){var r=this;if(!(r instanceof h))return new h(e,t);if(!t)t={};n("new websocket: %s %o",e,t);t.allowHalfOpen=false;if(t.highWaterMark==null)t.highWaterMark=1024*1024;o.Duplex.call(r,t);r.url=e;r.connected=false;r.destroyed=false;r._maxBufferedAmount=t.highWaterMark;r._chunk=null;r._cb=null;r._interval=null;r._ws=new u(r.url);r._ws.binaryType="arraybuffer";r._ws.onopen=r._onOpen.bind(r);r._ws.onmessage=r._onMessage.bind(r);r._ws.onclose=r._onClose.bind(r);r._ws.onerror=function(){r._onError(new Error("connection error to "+r.url))};r.on("finish",function(){if(r.connected){setTimeout(function(){r._destroy()},100)}else{r.once("connect",function(){setTimeout(function(){r._destroy()},100)})}})}h.WEBSOCKET_SUPPORT=!!u;h.prototype.send=function(e){var t=this;if(!s.strict(e)&&!(e instanceof ArrayBuffer)&&!r.isBuffer(e)&&typeof e!=="string"&&(typeof Blob==="undefined"||!(e instanceof Blob))){e=JSON.stringify(e)}var i=e.length||e.byteLength||e.size;t._ws.send(e);n("write: %d bytes",i)};h.prototype.destroy=function(e){var t=this;t._destroy(null,e)};h.prototype._destroy=function(e,t){var r=this;if(r.destroyed)return;if(t)r.once("close",t);n("destroy (error: %s)",e&&e.message);this.readable=this.writable=false;if(!r._readableState.ended)r.push(null);if(!r._writableState.finished)r.end();r.connected=false;r.destroyed=true;clearInterval(r._interval);r._interval=null;r._chunk=null;r._cb=null;if(r._ws){var i=r._ws;var s=function(){i.onclose=null;r.emit("close")};if(i.readyState===u.CLOSED){s()}else{try{i.onclose=s;i.close()}catch(e){s()}}i.onopen=null;i.onmessage=null;i.onerror=null}r._ws=null;if(e)r.emit("error",e)};h.prototype._read=function(){};h.prototype._write=function(e,t,r){var i=this;if(i.destroyed)return r(new Error("cannot write after socket is destroyed"));if(i.connected){try{i.send(e)}catch(s){return i._onError(s)}if(typeof f!=="function"&&i._ws.bufferedAmount>i._maxBufferedAmount){n("start backpressure: bufferedAmount %d",i._ws.bufferedAmount);i._cb=r}else{r(null)}}else{n("write before connect");i._chunk=e;i._cb=r}};h.prototype._onMessage=function(e){var t=this;if(t.destroyed)return;var i=e.data;n("read: %d bytes",i.byteLength||i.length);if(i instanceof ArrayBuffer){i=a(new Uint8Array(i));t.push(i)}else if(r.isBuffer(i)){t.push(i)}else{try{i=JSON.parse(i)}catch(s){}t.emit("data",i)}};h.prototype._onOpen=function(){var e=this;if(e.connected||e.destroyed)return;e.connected=true;if(e._chunk){try{e.send(e._chunk)}catch(t){return e._onError(t)}e._chunk=null;n('sent chunk from "write before connect"');var r=e._cb;e._cb=null;r(null)}if(typeof f!=="function"){e._interval=setInterval(function(){if(!e._cb||!e._ws||e._ws.bufferedAmount>e._maxBufferedAmount){return}n("ending backpressure: bufferedAmount %d",e._ws.bufferedAmount);var t=e._cb;e._cb=null;t(null)},150);if(e._interval.unref)e._interval.unref()}n("connect");e.emit("connect")};h.prototype._onClose=function(){var e=this;if(e.destroyed)return;n("on close");e._destroy()};h.prototype._onError=function(e){var t=this;if(t.destroyed)return;n("error: %s",e.message||e);t._destroy(e)}}).call(this,{isBuffer:e("../is-buffer/index.js")})},{"../is-buffer/index.js":54,debug:39,inherits:52,"is-typedarray":56,stream:101,"typedarray-to-buffer":111,ws:31}],100:[function(e,t,r){var n=1;var i=65535;var s=4;var o=function(){n=n+1&i};var a=setInterval(o,1e3/s|0);if(a.unref)a.unref();t.exports=function(e){var t=s*(e||5);var r=[0];var o=1;var a=n-1&i;return function(e){var f=n-a&i;if(f>t)f=t;a=n;while(f--){if(o===t)o=0;r[o]=r[o===0?t-1:o-1];o++}if(e)r[o-1]+=e;var u=r[o-1];var h=r.lengthe._pos){var o=r.substr(e._pos);if(e._charset==="x-user-defined"){var a=new i(o.length);for(var u=0;ue._pos){e.push(new i(new Uint8Array(h.result.slice(e._pos))));e._pos=h.result.byteLength}};h.onload=function(){e.push(null)};h.readAsArrayBuffer(r);break}if(e._xhr.readyState===f.DONE&&e._mode!=="ms-stream"){e.push(null)}}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{"./capability":103,_process:76,buffer:33,inherits:52,stream:101}],106:[function(e,t,r){var n=e("buffer").Buffer;var i=n.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function s(e){if(e&&!i(e)){throw new Error("Unknown encoding: "+e)}}var o=r.StringDecoder=function(e){this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,"");s(e);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=f;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=u;break;default:this.write=a;return}this.charBuffer=new n(6);this.charReceived=0;this.charLength=0};o.prototype.write=function(e){var t="";while(this.charLength){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;e.copy(this.charBuffer,this.charReceived,0,r);this.charReceived+=r;if(this.charReceived=55296&&n<=56319){this.charLength+=this.surrogateSize;t="";continue}this.charReceived=this.charLength=0;if(e.length===0){return t}break}this.detectIncompleteChar(e);var i=e.length;if(this.charLength){e.copy(this.charBuffer,0,e.length-this.charReceived,i);i-=this.charReceived}t+=e.toString(this.encoding,0,i);var i=t.length-1;var n=t.charCodeAt(i);if(n>=55296&&n<=56319){var s=this.surrogateSize;this.charLength+=s;this.charReceived+=s;this.charBuffer.copy(this.charBuffer,s,0,s);e.copy(this.charBuffer,0,0,s);return t.substring(0,i)}return t};o.prototype.detectIncompleteChar=function(e){var t=e.length>=3?3:e.length;for(;t>0;t--){var r=e[e.length-t];if(t==1&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t};o.prototype.end=function(e){var t="";if(e&&e.length)t=this.write(e);if(this.charReceived){var r=this.charReceived;var n=this.charBuffer;var i=this.encoding;t+=n.slice(0,r).toString(i)}return t};function a(e){return e.toString(this.encoding)}function f(e){this.charReceived=e.length%2;this.charLength=this.charReceived?2:0}function u(e){this.charReceived=e.length%3;this.charLength=this.charReceived?3:0}},{buffer:33}],107:[function(e,t,r){var n=e("./thirty-two");r.encode=n.encode;r.decode=n.decode},{"./thirty-two":108}],108:[function(e,t,r){(function(e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";var n=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,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,255,255,255,255,255,255,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,255,255,255,255,255];function i(e){var t=Math.floor(e.length/5);return e.length%5==0?t:t+1}r.encode=function(r){if(!e.isBuffer(r)){r=new e(r)}var n=0;var s=0;var o=0;var a=0;var f=new e(i(r)*8);while(n3){a=u&255>>o;o=(o+5)%8;a=a<>8-o;n++}else{a=u>>8-(o+5)&31;o=(o+5)%8;if(o==0)n++}f[s]=t.charCodeAt(a);s++}for(n=s;n>>r;a[o]=s;o++;s=255&i<<8-r}}else{throw new Error("Invalid input - it is not base32 encoded string")}}return a.slice(0,o)}}).call(this,e("buffer").Buffer)},{buffer:33}],109:[function(e,t,r){(function(r,n){t.exports=c;var i=e("debug")("torrent-discovery");var s=e("bittorrent-dht/client");var o=e("events").EventEmitter;var a=e("xtend/mutable");var f=e("inherits");var u=e("run-parallel");var h=e("re-emitter");var l=e("bittorrent-tracker/client");f(c,o);function c(e){var t=this;if(!(t instanceof c))return new c(e);o.call(t);a(t,{announce:[],dht:typeof s==="function",rtcConfig:null,peerId:null,port:0,tracker:true,wrtc:null},e);t.infoHash=null;t.infoHashBuffer=null;t.torrent=null;t._externalDHT=typeof t.dht==="object";t._performedDHTLookup=false;if(!t.peerId)throw new Error("peerId required");if(!r.browser&&!t.port)throw new Error("port required");if(t.dht)t._createDHT(t.dhtPort)}c.prototype.setTorrent=function(e){var t=this;if(!t.infoHash&&(typeof e==="string"||n.isBuffer(e))){t.infoHash=typeof e==="string"?e:e.toString("hex")}else if(!t.torrent&&e&&e.infoHash){t.torrent=e;t.infoHash=typeof e.infoHash==="string"?e.infoHash:e.infoHash.toString("hex")}else{return}t.infoHashBuffer=new n(t.infoHash,"hex");i("setTorrent %s",t.infoHash);if(t.tracker&&t.tracker!==true){t.tracker.torrentLength=e.length}else{t._createTracker()}if(t.dht){if(t.dht.ready)t._dhtLookupAndAnnounce();else t.dht.on("ready",t._dhtLookupAndAnnounce.bind(t))}};c.prototype.updatePort=function(e){var t=this;if(e===t.port)return;t.port=e;if(t.dht&&t.infoHash){t._performedDHTLookup=false;t._dhtLookupAndAnnounce()}if(t.tracker&&t.tracker!==true){t.tracker.stop();t.tracker.destroy(function(){t._createTracker()})}};c.prototype.stop=function(e){var t=this;var r=[];if(t.tracker&&t.tracker!==true){t.tracker.stop();r.push(function(e){t.tracker.destroy(e)})}if(!t._externalDHT&&t.dht&&t.dht!==true){r.push(function(e){t.dht.destroy(e)})}u(r,e)};c.prototype._createDHT=function(e){var t=this;if(!t._externalDHT)t.dht=new s;h(t.dht,t,["error","warning"]);t.dht.on("peer",function(e,r){if(r===t.infoHash)t.emit("peer",e)});if(!t._externalDHT)t.dht.listen(e)};c.prototype._createTracker=function(){var e=this;if(!e.tracker)return;var t=e.torrent?a({announce:[]},e.torrent):{infoHash:e.infoHash,announce:[]};if(e.announce)t.announce=t.announce.concat(e.announce);var r={rtcConfig:e.rtcConfig,wrtc:e.wrtc};e.tracker=new l(e.peerId,e.port,t,r);h(e.tracker,e,["peer","warning","error"]);e.tracker.on("update",function(t){e.emit("trackerAnnounce",t)});e.tracker.start()};c.prototype._dhtLookupAndAnnounce=function(){var e=this;if(e._performedDHTLookup)return;e._performedDHTLookup=true;i("dht lookup");e.dht.lookup(e.infoHash,function(t){if(t||!e.port)return;i("dht announce");e.dht.announce(e.infoHash,e.port,function(){i("dht announce complete");e.emit("dhtAnnounce")})})}}).call(this,e("_process"),e("buffer").Buffer)},{_process:76,"bittorrent-dht/client":31,"bittorrent-tracker/client":20,buffer:33,debug:39,events:44,inherits:52,"re-emitter":83,"run-parallel":94,"xtend/mutable":120}],110:[function(e,t,r){(function(e){t.exports=n;var r=1<<14;function n(e){if(!(this instanceof n))return new n(e);this.length=e;this.missing=e;this.sources=null;this._chunks=Math.ceil(e/r);this._remainder=e%r||r;this._buffered=0;this._buffer=null;this._cancellations=null;this._reservations=0;this._flushed=false}n.BLOCK_LENGTH=r;n.prototype.chunkLength=function(e){return e===this._chunks-1?this._remainder:r};n.prototype.chunkOffset=function(e){return e*r};n.prototype.reserve=function(){if(!this.init())return-1;if(this._cancellations.length)return this._cancellations.pop();if(this._reservations",'"',"`"," ","\r","\n"," "],h=["{","}","|","\\","^","`"].concat(u),l=["'"].concat(h),c=["%","/","?",";","#"].concat(l),d=["/","?","#"],p=255,m=/^[+a-z0-9A-Z_-]{0,63}$/,v=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:true,"javascript:":true},_={javascript:true,"javascript:":true},y={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},b=e("querystring");function w(e,t,r){if(e&&i.isObject(e)&&e instanceof s)return e;var n=new s;n.parse(e,t,r);return n}s.prototype.parse=function(e,t,r){if(!i.isString(e)){throw new TypeError("Parameter 'url' must be a string, not "+typeof e)}var s=e.indexOf("?"),a=s!==-1&&s127){F+="x"}else{F+=P[O]}}if(!F.match(m)){var D=C.slice(0,U);var N=C.slice(U+1);var z=P.match(v);if(z){D.push(z[1]);N.unshift(z[2])}if(N.length){w="/"+N.join(".")+w}this.hostname=D.join(".");break}}}}if(this.hostname.length>p){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!B){this.hostname=n.toASCII(this.hostname)}var j=this.port?":"+this.port:"";var H=this.hostname||"";this.host=H+j;this.href+=this.host;if(B){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(w[0]!=="/"){w="/"+w}}}if(!g[k]){for(var U=0,R=l.length;U0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}r.search=e.search;r.query=e.query;if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.href=r.format();return r}if(!x.length){r.pathname=null;if(r.search){r.path="/"+r.search}else{r.path=null}r.href=r.format();return r}var A=x.slice(-1)[0];var U=(r.host||e.host||x.length>1)&&(A==="."||A==="..")||A==="";var T=0;for(var I=x.length;I>=0;I--){A=x[I];if(A==="."){x.splice(I,1)}else if(A===".."){x.splice(I,1);T++}else if(T){x.splice(I,1);T--}}if(!w&&!S){for(;T--;T){x.unshift("..")}}if(w&&x[0]!==""&&(!x[0]||x[0].charAt(0)!=="/")){x.unshift("")}if(U&&x.join("/").substr(-1)!=="/"){x.push("")}var L=x[0]===""||x[0]&&x[0].charAt(0)==="/";if(k){r.hostname=r.host=L?"":x.length?x.shift():"";var E=r.host&&r.host.indexOf("@")>0?r.host.split("@"):false;if(E){r.auth=E.shift();r.host=r.hostname=E.shift()}}w=w||r.host&&x.length;if(w&&!L){x.unshift("")}if(!x.length){r.pathname=null;r.path=null}else{r.pathname=x.join("/")}if(!i.isNull(r.pathname)||!i.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.auth=e.auth||r.auth;r.slashes=r.slashes||e.slashes;r.href=r.format();return r};s.prototype.parseHost=function(){var e=this.host;var t=a.exec(e);if(t){t=t[0];if(t!==":"){this.port=t.substr(1)}e=e.substr(0,e.length-t.length)}if(e)this.hostname=e}},{"./util":114,punycode:78,querystring:81}],114:[function(e,t,r){"use strict";t.exports={isString:function(e){return typeof e==="string"},isObject:function(e){return typeof e==="object"&&e!==null},isNull:function(e){return e===null},isNullOrUndefined:function(e){return e==null}}},{}],115:[function(e,t,r){(function(r){var n=e("bencode");var i=e("bitfield");var s=e("events").EventEmitter;var o=e("inherits");var a=e("simple-sha1");var f=1e7;var u=1e3;var h=16*1024;t.exports=function(e){o(t,s);function t(t){s.call(this);this._wire=t;this._metadataComplete=false;this._metadataSize=null;this._remainingRejects=null;this._fetching=false;this._bitfield=new i(0,{grow:u});if(r.isBuffer(e)){this.setMetadata(e)}}t.prototype.name="ut_metadata";t.prototype.onHandshake=function(e,t,r){this._infoHash=e};t.prototype.onExtendedHandshake=function(e){if(!e.m||!e.m.ut_metadata){return this.emit("warning",new Error("Peer does not support ut_metadata"))}if(!e.metadata_size){return this.emit("warning",new Error("Peer does not have metadata"))}if(e.metadata_size>f){return this.emit("warning",new Error("Peer gave maliciously large metadata size"))}this._metadataSize=e.metadata_size;this._numPieces=Math.ceil(this._metadataSize/h);this._remainingRejects=this._numPieces*2;if(this._fetching){this._requestPieces()}};t.prototype.onMessage=function(e){var t,r;try{var i=e.toString();var s=i.indexOf("ee")+2;t=n.decode(i.substring(0,s));r=e.slice(s)}catch(o){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,r,t.total_size);break;case 2:this._onReject(t.piece);break}};t.prototype.fetch=function(){if(this._metadataComplete){return}this._fetching=true;if(this._metadataSize){this._requestPieces()}};t.prototype.cancel=function(){this._fetching=false};t.prototype.setMetadata=function(e){if(this._metadataComplete)return true;try{var t=n.decode(e).info;if(t){e=n.encode(t)}}catch(r){}if(this._infoHash&&this._infoHash!==a.sync(e)){return false}this.cancel();this.metadata=e;this._metadataComplete=true;this._metadataSize=this.metadata.length;this._wire.extendedHandshake.metadata_size=this._metadataSize;this.emit("metadata",n.encode({info:n.decode(this.metadata)}));return true};t.prototype._send=function(e,t){var i=n.encode(e);if(r.isBuffer(t)){i=r.concat([i,t])}this._wire.extended("ut_metadata",i)};t.prototype._request=function(e){this._send({msg_type:0,piece:e})};t.prototype._data=function(e,t,r){var n={msg_type:1,piece:e};if(typeof r==="number"){n.total_size=r}this._send(n,t)};t.prototype._reject=function(e){this._send({msg_type:2,piece:e})};t.prototype._onRequest=function(e){if(!this._metadataComplete){this._reject(e);return}var t=e*h;var r=t+h;if(r>this._metadataSize){r=this._metadataSize}var n=this.metadata.slice(t,r);this._data(e,n,this._metadataSize)};t.prototype._onData=function(e,t,r){if(t.length>h){return}t.copy(this.metadata,e*h);this._bitfield.set(e);this._checkDone()};t.prototype._onReject=function(e){if(this._remainingRejects>0&&this._fetching){this._request(e);this._remainingRejects-=1}else{this.emit("warning",new Error('Peer sent "reject" too much'))}};t.prototype._requestPieces=function(){this.metadata=new r(this._metadataSize);for(var e=0;e0){this._requestPieces()}else{this.emit("warning",new Error("Peer sent invalid metadata"))}};return t}}).call(this,e("buffer").Buffer)},{bencode:11,bitfield:15,buffer:33,events:44,inherits:52,"simple-sha1":98}],116:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(n("noDeprecation")){return e}var r=false;function i(){if(!r){if(n("throwDeprecation")){throw new Error(t)}else if(n("traceDeprecation")){console.trace(t)}else{console.warn(t)}r=true}return e.apply(this,arguments)}return i}function n(t){try{if(!e.localStorage)return false}catch(r){return false}var n=e.localStorage[t];if(null==n)return false;return String(n).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],117:[function(e,t,r){var n=e("debug")("videostream");var i=e("mp4box");var s=.01;var o=60;t.exports=function(e,t,r){r=r||{};var f=r.debugTrack||-1;var u=[];function h(){t.addEventListener("waiting",S);t.addEventListener("timeupdate",E)}h();var l=false;function c(e){l=true;t.removeEventListener("waiting",S);t.removeEventListener("timeupdate",E);if(p.readyState==="open")p.endOfStream(e)}function d(e){var r=e.buffer.buffered;var i=t.currentTime;var a=-1;for(var f=0;fi){break}else if(a>=0||i<=h){a=h}}var l=a-i;if(l<0)l=0;n("Buffer length: %f",l);return l<=o}var p=new MediaSource;p.addEventListener("sourceopen",function(){w(0)});t.src=window.URL.createObjectURL(p);var m=new i;m.onError=function(e){n("MP4Box error: %s",e.message);if(b){b()}if(p.readyState==="open"){c("decode")}};var v=false;var g={};m.onReady=function(e){n("MP4 info: %o",e);e.tracks.forEach(function(e){var t;if(e.video){t="video/mp4"}else if(e.audio){t="audio/mp4"}else{return}t+='; codecs="'+e.codec+'"';if(MediaSource.isTypeSupported(t)){var r=p.addSourceBuffer(t);var n={buffer:r,arrayBuffers:[],meta:e,ended:false};r.addEventListener("updateend",A.bind(null,n));m.setSegmentOptions(e.id,null,{nbSamples:e.video?1:100});g[e.id]=n}});if(Object.keys(g).length===0){c("decode");return}var t=m.initializeSegmentation();t.forEach(function(e){k(g[e.id],e.buffer);if(e.id===f){a("init-track-"+f+".mp4",[e.buffer]);u.push(e.buffer)}});v=true};m.onSegment=function(e,t,r,n){var i=g[e];k(i,r,n===i.meta.nb_samples);if(e===f&&u){u.push(r);if(n>1e3){a("track-"+f+".mp4",u);u=null}}};var _;var y=null;var b=null;function w(t){if(t===e.length){m.flush();return}if(y&&t===_){var r=y;setTimeout(function(){if(y===r)y.resume()});return}if(y){y.destroy();b()}_=t;var i={start:_,end:e.length-1};y=e.createReadStream(i);function s(e){y.pause();var t=e.toArrayBuffer();t.fileStart=_;_+=t.byteLength;var r;try{r=m.appendBuffer(t)}catch(i){n("MP4Box threw exception: %s",i.message);if(p.readyState==="open"){c("decode")}y.destroy();b();return}w(r)}y.on("data",s);function o(){b();w(_)}y.on("end",o);function a(e){n("Stream error: %s",e.message);if(p.readyState==="open"){c("network")}}y.on("error",a);b=function(){y.removeListener("data",s);y.removeListener("end",o);y.removeListener("error",a);y=null;b=null}}function S(){if(v){x(t.currentTime)}}function x(e){if(l)h();var t=m.seek(e,true);n("Seeking to time: %d",e);n("Seeked file offset: %d",t.offset);w(t.offset)}function k(e,t,r){e.arrayBuffers.push({buffer:t,ended:r||false});A(e)}function E(){Object.keys(g).forEach(function(e){var t=g[e];if(t.blocked){A(t)}})}function A(e){if(e.buffer.updating)return;e.blocked=!d(e);if(e.blocked)return;if(e.arrayBuffers.length===0)return;var t=e.arrayBuffers.shift();var r=false;try{e.buffer.appendBuffer(t.buffer);e.ended=t.ended;r=true}catch(i){n("SourceBuffer error: %s",i.message);c("decode");return}if(r){U()}}function U(){if(p.readyState!=="open"){return}var e=Object.keys(g).every(function(e){var t=g[e];return t.ended&&!t.buffer.updating});if(e){c()}}};function a(e,t){var r=new Blob(t);var n=URL.createObjectURL(r);var i=document.createElement("a");i.setAttribute("href",n);i.setAttribute("download",e);i.click()}},{debug:39,mp4box:67}],118:[function(e,t,r){t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=="function")throw new TypeError("need wrapper function");Object.keys(e).forEach(function(t){r[t]=e[t]});return r;function r(){var t=new Array(arguments.length);for(var r=0;r0)return new Array(e+(/\./.test(t)?2:1)).join(r)+t;return t+""}},{}],122:[function(e,t,r){t.exports={name:"webtorrent",description:"Streaming torrent client",version:"0.63.2",author:{name:"Feross Aboukhadijeh",email:"feross@feross.org",url:"http://feross.org/"},bin:{webtorrent:"./bin/cmd.js"},browser:{"./lib/server.js":false,"bittorrent-dht/client":false,"fs-chunk-store":"memory-chunk-store","load-ip-set":false,os:false,"path-exists":false,ut_pex:false},bugs:{url:"https://github.com/feross/webtorrent/issues"},dependencies:{"addr-to-ip-port":"^1.0.1",bitfield:"^1.0.2","bittorrent-dht":"^5.0.0","bittorrent-swarm":"^6.0.0","chunk-store-stream":"^2.0.0",clivas:"^0.2.0","create-torrent":"^3.4.0","cross-spawn-async":"^2.0.0",debug:"^2.1.0","end-of-stream":"^1.0.0",executable:"^2.1.0","fs-chunk-store":"^1.3.4",hat:"0.0.3","immediate-chunk-store":"^1.0.7",inherits:"^2.0.1",inquirer:"^0.11.0","load-ip-set":"^1.0.3",mediasource:"^1.0.0","memory-chunk-store":"^1.2.0",mime:"^1.2.11",minimist:"^1.1.0",moment:"^2.8.3",multistream:"^2.0.2","network-address":"^1.0.0","parse-torrent":"^5.1.0","path-exists":"^2.1.0","pretty-bytes":"^2.0.1",pump:"^1.0.0","random-iterate":"^1.0.1","range-parser":"^1.0.2","re-emitter":"^1.0.0","run-parallel":"^1.0.0","simple-sha1":"^2.0.0",speedometer:"^1.0.0",thunky:"^0.1.0","torrent-discovery":"^4.0.0","torrent-piece":"^1.0.0",uniq:"^1.0.1",ut_metadata:"^3.0.1",ut_pex:"^1.0.1",videostream:"^1.1.4","windows-no-runnable":"0.0.6",xtend:"^4.0.0","zero-fill":"^2.2.0"},devDependencies:{"bittorrent-tracker":"^6.0.0",brfs:"^1.2.0",browserify:"^12.0.1",finalhandler:"^0.4.0","run-auto":"^1.0.0","serve-static":"^1.9.3","simple-get":"^1.0.0",standard:"^5.1.0",tape:"^4.0.0","uglify-js":"^2.4.15",zelda:"^2.0.0",zuul:"^3.0.0"},homepage:"http://webtorrent.io",keywords:["torrent","bittorrent","bittorrent client","streaming","download","webrtc","webrtc data","webtorrent","mad science"],license:"MIT",main:"index.js",optionalDependencies:{"airplay-js":"^0.2.3",chromecasts:"^1.5.3",nodebmc:"0.0.5"},repository:{type:"git",url:"git://github.com/feross/webtorrent.git"},scripts:{build:"browserify -s WebTorrent -e ./ | uglifyjs -m > webtorrent.min.js","build-debug":"browserify -s WebTorrent -e ./ > webtorrent.debug.js",size:"npm run build && cat webtorrent.min.js | gzip | wc -c",test:"standard && node ./bin/test.js","test-browser":"zuul -- test/basic.js","test-browser-local":"zuul --local -- test/basic.js","test-node":"tape test/*.js"}}},{}],123:[function(e,t,r){(function(r,n,i){t.exports=S;var s=e("create-torrent");var o=e("debug")("webtorrent");var a=e("bittorrent-dht/client");var f=e("events").EventEmitter;var u=e("xtend");var h=e("hat");var l=e("inherits");var c=e("load-ip-set");var d=e("run-parallel");var p=e("parse-torrent");var m=e("speedometer");var v=e("zero-fill");var g=e("path");var _=e("./lib/torrent");l(S,f);var y=e("./package.json").version;var b=y.match(/([0-9]+)/g).slice(0,2).map(v(2)).join("");var w="-WW"+b+"-";function S(e){var t=this;if(!(t instanceof S))return new S(e);f.call(t);if(!e)e={};if(!o.enabled)t.setMaxListeners(0);t.destroyed=false;t.torrentPort=e.torrentPort||0;t.tracker=e.tracker!==undefined?e.tracker:true;t._rtcConfig=e.rtcConfig;t._wrtc=e.wrtc||n.WRTC;t.torrents=[];t.downloadSpeed=m();t.uploadSpeed=m();t.peerId=typeof e.peerId==="string"?e.peerId:(e.peerId||new i(w+h(48))).toString("hex");t.peerIdBuffer=new i(t.peerId,"hex");t.nodeId=typeof e.nodeId==="string"?e.nodeId:e.nodeId&&e.nodeId.toString("hex")||h(160);t.nodeIdBuffer=new i(t.nodeId,"hex");if(e.dht!==false&&typeof a==="function"){t.dht=new a(u({nodeId:t.nodeId},e.dht));t.dht.listen(e.dhtPort)}o("new webtorrent (peerId %s, nodeId %s)",t.peerId,t.nodeId);if(typeof c==="function"){c(e.blocklist,{headers:{"user-agent":"WebTorrent/"+y+" (http://webtorrent.io)"}},function(e,r){if(e)return t.error("Failed to load blocklist: "+e.message);t.blocked=r;s()})}else r.nextTick(s);function s(){if(t.destroyed)return;t.ready=true;t.emit("ready")}}Object.defineProperty(S.prototype,"ratio",{get:function(){var e=this;var t=e.torrents.reduce(function(e,t){return e+t.uploaded},0);var r=e.torrents.reduce(function(e,t){return e+t.downloaded},0)||1;return t/r}});S.prototype.get=function(e){var t=this;if(e instanceof _)return e;var r;try{r=p(e)}catch(n){}if(!r)return null;if(!r.infoHash)throw new Error("Invalid torrent identifier");for(var i=0,s=t.torrents.length;i Date: Sat, 5 Dec 2015 03:21:34 -0800 Subject: [PATCH 29/44] zelda@3 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index a4d2ea6bb3..308afdb69d 100644 --- a/package.json +++ b/package.json @@ -79,7 +79,7 @@ "standard": "^5.1.0", "tape": "^4.0.0", "uglify-js": "^2.4.15", - "zelda": "^2.0.0", + "zelda": "^3.0.0", "zuul": "^3.0.0" }, "homepage": "http://webtorrent.io", From cbe31a86cc5556792fe25ccbfbc8e2f412ce176d Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Sat, 5 Dec 2015 03:21:39 -0800 Subject: [PATCH 30/44] add debug log --- lib/torrent.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/torrent.js b/lib/torrent.js index ba13d8e604..b9dc705fef 100644 --- a/lib/torrent.js +++ b/lib/torrent.js @@ -470,6 +470,7 @@ Torrent.prototype.addPeer = function (peer) { */ Torrent.prototype.addWebSeed = function (url) { var self = this + debug('add web seed %s', url) self.swarm.addWebSeed(url, self) } From 721ffa79e00a432d5978abfd5708fab648e5a466 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 7 Dec 2015 04:14:46 -0800 Subject: [PATCH 31/44] fix talk links --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 792daa29cf..ede3d58e03 100644 --- a/README.md +++ b/README.md @@ -757,10 +757,11 @@ makes it easier to send PRs: ### Talks about WebTorrent -- Nov 2014 (NodeConf Asia) - [WebTorrent](https://www.youtube.com/watch?v=kxHRATfvnlw) -- Sep 2014 (NodeConf EU) – WebTorrent & WebRTC: Mad Science (first working demo of WebTorrent) +- May 2015 (Data Terra Nemo) - [WebTorrent: Mother of all demos](https://www.youtube.com/watch?v=RRtNEcAaUO8) +- Nov 2014 (JSConf Asia) - [How WebTorrent Works](https://www.youtube.com/watch?v=kxHRATfvnlw) +- Sep 2014 (NodeConf EU) – [WebTorrent Mad Science](https://www.youtube.com/watch?v=BVBXkzVjvPc) (first working WebTorrent demo) - May 2014 (JS.LA) – [How I Built a BitTorrent Client in the Browser](https://vimeo.com/97324247) (progress update; node client working) -- Oct 2013 (RealtimeConf) – [WebRTC Black Magic (RealtimeConf)](https://vimeo.com/77265280) (where I first shared the idea of WebTorrent) +- Oct 2013 (RealtimeConf) – [WebRTC Black Magic](https://vimeo.com/77265280) (first mention of idea for WebTorrent) ### Known issues From 7f01f07f06525aaba88434dd9c557adde21caeca Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 7 Dec 2015 04:15:23 -0800 Subject: [PATCH 32/44] remove clone script MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `zelda` doesn’t work reliably on npm3 yet. this script is currently more trouble than it’s worth --- README.md | 19 ------------------- bin/clone.sh | 27 --------------------------- 2 files changed, 46 deletions(-) delete mode 100755 bin/clone.sh diff --git a/README.md b/README.md index ede3d58e03..3b902b425e 100644 --- a/README.md +++ b/README.md @@ -703,15 +703,6 @@ WebTorrent is only possible due to the excellent work of the following contribut Diego Rodríguez B.GitHub/DiegoRBaqueroTwitter/@DiegoRBaquero -#### Clone the code - -```bash -git clone https://github.com/feross/webtorrent.git -cd webtorrent -npm install -./bin/cmd.js --help -``` - #### JavaScript Standard Style WebTorrent uses [JavaScript Standard Style](https://github.com/feross/standard). @@ -745,16 +736,6 @@ Disable by running this: localStorage.removeItem('debug') ``` -#### Clone all dependencies - -WebTorrent is a modular BitTorrent client, so functionality is split up into many -npm modules. You can `git clone` all the relevant dependencies with one command. This -makes it easier to send PRs: - -```bash -./bin/clone.sh -``` - ### Talks about WebTorrent - May 2015 (Data Terra Nemo) - [WebTorrent: Mother of all demos](https://www.youtube.com/watch?v=RRtNEcAaUO8) diff --git a/bin/clone.sh b/bin/clone.sh deleted file mode 100755 index 3b6ae9dcd7..0000000000 --- a/bin/clone.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash - -if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then - echo "Usage: $0 DIRECTORY_TO_CLONE_INTO" >&2 - exit 1 -fi - -pushd $1 -git clone git@github.com:feross/addr-to-ip-port.git -git clone git@github.com:feross/bittorrent-dht.git -git clone git@github.com:feross/bittorrent-protocol.git -git clone git@github.com:feross/bittorrent-swarm.git -git clone git@github.com:feross/bittorrent-tracker.git -git clone git@github.com:feross/create-torrent.git -git clone git@github.com:feross/load-ip-set.git -git clone git@github.com:feross/magnet-uri.git -git clone git@github.com:feross/parse-torrent-file.git -git clone git@github.com:feross/parse-torrent.git -git clone git@github.com:feross/simple-peer.git -git clone git@github.com:feross/string2compact.git -git clone git@github.com:feross/torrent-discovery.git -git clone git@github.com:feross/ut_metadata.git -git clone git@github.com:feross/ut_pex.git -git clone git@github.com:fisch0920/bittorrent-peerid.git -git clone git@github.com:fisch0920/ip-set.git -popd -./node_modules/.bin/zelda $1 From d084f3f1d80a8b35fe8c655233987e28943b75f5 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 7 Dec 2015 04:15:34 -0800 Subject: [PATCH 33/44] move js standard style logo to top of readme --- README.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 3b902b425e..f64d826d28 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ ### Streaming torrent client for node & the browser +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](http://standardjs.com) + **WebTorrent** is a streaming torrent client for **node.js** and the **browser**. YEP, THAT'S RIGHT. THE BROWSER. It's written completely in JavaScript – the language of the web – so the same code works in both runtimes. @@ -703,12 +705,6 @@ WebTorrent is only possible due to the excellent work of the following contribut Diego Rodríguez B.GitHub/DiegoRBaqueroTwitter/@DiegoRBaquero -#### JavaScript Standard Style - -WebTorrent uses [JavaScript Standard Style](https://github.com/feross/standard). - -[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) - #### Enable debug logs In **node**, enable debug logs by setting the `DEBUG` environment variable to the name of the From 23dbefe009545c208445d0e14fd878cd76082b5b Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 7 Dec 2015 04:16:36 -0800 Subject: [PATCH 34/44] remove ip-set from readme --- README.md | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/README.md b/README.md index f64d826d28..c642cf7eea 100644 --- a/README.md +++ b/README.md @@ -582,8 +582,6 @@ These are the main modules that make up WebTorrent: | [bittorrent-swarm][bittorrent-swarm] | [![][bittorrent-swarm-ti]][bittorrent-swarm-tu] | [![][bittorrent-swarm-ni]][bittorrent-swarm-nu] | bittorrent connection manager | [bittorrent-tracker][bittorrent-tracker] | [![][bittorrent-tracker-ti]][bittorrent-tracker-tu] | [![][bittorrent-tracker-ni]][bittorrent-tracker-nu] | bittorrent tracker server/client | [create-torrent][create-torrent] | [![][create-torrent-ti]][create-torrent-tu] | [![][create-torrent-ni]][create-torrent-nu] | create .torrent files -| [ip-set][ip-set] | [![][ip-set-ti]][ip-set-tu] | [![][ip-set-ni]][ip-set-nu] | efficient mutable ip set -| [load-ip-set][load-ip-set] | [![][load-ip-set-ti]][load-ip-set-tu] | [![][load-ip-set-ni]][load-ip-set-nu] | load ip sets from local/network | [magnet-uri][magnet-uri] | [![][magnet-uri-ti]][magnet-uri-tu] | [![][magnet-uri-ni]][magnet-uri-nu] | parse magnet uris | [parse-torrent][parse-torrent] | [![][parse-torrent-ti]][parse-torrent-tu] | [![][parse-torrent-ni]][parse-torrent-nu] | parse torrent identifiers | [torrent-discovery][torrent-discovery] | [![][torrent-discovery-ti]][torrent-discovery-tu] | [![][torrent-discovery-ni]][torrent-discovery-nu] | find peers via dht and tracker @@ -640,18 +638,6 @@ These are the main modules that make up WebTorrent: [create-torrent-ni]: https://img.shields.io/npm/v/create-torrent.svg?style=flat [create-torrent-nu]: https://npmjs.org/package/create-torrent -[ip-set]: https://github.com/fisch0920/ip-set -[ip-set-ti]: https://img.shields.io/travis/fisch0920/ip-set.svg?style=flat -[ip-set-tu]: https://travis-ci.org/fisch0920/ip-set -[ip-set-ni]: https://img.shields.io/npm/v/ip-set.svg?style=flat -[ip-set-nu]: https://npmjs.org/package/ip-set - -[load-ip-set]: https://github.com/feross/load-ip-set -[load-ip-set-ti]: https://img.shields.io/travis/feross/load-ip-set.svg?style=flat -[load-ip-set-tu]: https://travis-ci.org/feross/load-ip-set -[load-ip-set-ni]: https://img.shields.io/npm/v/load-ip-set.svg?style=flat -[load-ip-set-nu]: https://npmjs.org/package/load-ip-set - [magnet-uri]: https://github.com/feross/magnet-uri [magnet-uri-ti]: https://img.shields.io/travis/feross/magnet-uri.svg?style=flat [magnet-uri-tu]: https://travis-ci.org/feross/magnet-uri From 4a96eab396304ac9501e799d12557318edd9c8eb Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 7 Dec 2015 04:16:49 -0800 Subject: [PATCH 35/44] readme: remove old "known issues" section --- README.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/README.md b/README.md index c642cf7eea..7dddc68f1b 100644 --- a/README.md +++ b/README.md @@ -726,16 +726,6 @@ localStorage.removeItem('debug') - May 2014 (JS.LA) – [How I Built a BitTorrent Client in the Browser](https://vimeo.com/97324247) (progress update; node client working) - Oct 2013 (RealtimeConf) – [WebRTC Black Magic](https://vimeo.com/77265280) (first mention of idea for WebTorrent) -### Known issues - -#### Downloads don't start on Chromebook - -Chromebooks are set to refuse all incoming connections by default. To change this, run: - -```bash -sudo iptables -P INPUT ACCEPT -``` - ### License MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). From 377e7dcbe6379eefc4cdbba958fa4061cca3abd5 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 7 Dec 2015 04:20:50 -0800 Subject: [PATCH 36/44] only test last two browsers --- .zuul.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.zuul.yml b/.zuul.yml index 0142da14c0..6f2c7b62a8 100644 --- a/.zuul.yml +++ b/.zuul.yml @@ -1,6 +1,6 @@ ui: tape browsers: - name: chrome - version: -2..latest + version: -1..latest - name: firefox - version: -2..latest + version: -1..latest From 7c48a6b078ae916ac11fea83079e0b94e79bbece Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Mon, 7 Dec 2015 04:21:20 -0800 Subject: [PATCH 37/44] move sauce labs badge to top --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7dddc68f1b..9b75aa142a 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ ### Streaming torrent client for node & the browser +[![Sauce Test Status][webtorrent-sauce-image]][webtorrent-sauce-url] +      [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](http://standardjs.com) **WebTorrent** is a streaming torrent client for **node.js** and the **browser**. YEP, @@ -68,8 +70,6 @@ connect to both normal *and* web peers. - Stream video torrents into a `