/**
 * This file is automatically generated. Do not edit it.
 * $Id: videostream.js,v 5.5.3 2025/05/03 10:10:07 dc Exp $
 */
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
var inherits = require("/bundle/utils").inherit, EventEmitter = require("eventemitter3").EventEmitter, Buffer = require("buffer").Buffer;

module.exports = AudioStream;

var log = console.warn.bind(console, "audiostream");

function AudioStream(file, mediaElem, opts) {
  var self = this;
  if (!(this instanceof AudioStream)) return new AudioStream(file, mediaElem, opts);
  EventEmitter.call(self);
  function destroy(ex) {
    log(ex);
    self.destroy(ex);
  }
  var context = new AudioContext();
  self._file = file;
  self._decTick = 0;
  self._buffer = null;
  self._ended = !1;
  self._bytesRead = 0;
  self._playOffset = 0;
  self._stopOffset = 0;
  self._timeOffset = 0;
  self._played = !1;
  self._hasAudio = !0;
  self._stopping = !1;
  self._decoding = !1;
  self._complete = !1;
  self._elem = mediaElem;
  self._visualiser = null;
  self._audioSource = null;
  self._audioBuffer = null;
  self._videoStream = null;
  self._audioStream = null;
  self._outputStream = null;
  self._videoCanvas = null;
  self._videoContext = null;
  self._audioContext = context;
  self._audioAnalyser = null;
  self._isWebkitSafari = window.safari || "Webkit" === ua.details.engine;
  var fileStream = file.createReadStream({
    start: 0
  });
  (self._fileStream = fileStream).on("data", tryCatch(function(data) {
    if (self._bytesRead > 0) {
      self._buffer.set(data, self._bytesRead);
      self._bytesRead += data.byteLength;
    } else if (self._buffer) {
      var tmp = new Uint8Array(data.byteLength + self._buffer.byteLength);
      tmp.set(self._buffer);
      tmp.set(data, self._buffer.byteLength);
      self._buffer = tmp;
    } else if (file.filesize > 0) {
      self._buffer = new Uint8Array(file.filesize);
      self._buffer.set(data, self._bytesRead);
      self._bytesRead += data.byteLength;
    } else self._buffer = data;
    if (self._isWebkitSafari && !AudioStream.patched) {
      AudioStream.patched = !0;
      log("patching decode-audio-data if needed...");
      require("promise-decode-audio-data");
    }
    if (opts.partial) {
      self._feed(opts);
      var read = self._bytesRead || self._buffer.byteLength, size = Math.min(file.fetchChunkSize << 1, AudioStream.maxChunkSize);
      if (read > size) {
        file.fetchChunkSize = size;
        file.readerChunkSize = size;
      }
    }
  }, destroy));
  fileStream.on("end", tryCatch(function() {
    fileStream.destroy();
    fileStream._file.reset();
    self._complete = !0;
    self._feed(opts);
  }, destroy));
  self._onError = function(err) {
    self.destroy(err);
  };
  self._onPause = function() {
    self._audioStream && self._stop();
  };
  self._onPlay = function() {
    if (self._audioStream) {
      self._played = !0;
      self._play(self._ended ? 0 : self._timeOffset);
    }
  };
  mediaElem.addEventListener("play", self._onPlay);
  mediaElem.addEventListener("pause", self._onPause);
  mediaElem.addEventListener("error", self._onError);
  "suspended" === context.state && self._resume();
  if (self._isWebkitSafari) {
    self._onVisibilityChange = function() {
      "suspended" !== context.state && "interrupted" !== context.state || self._resume();
    };
    window.addEventListener("visibilitychange", context.onstatechange = self._onVisibilityChange);
  }
}

inherits(AudioStream, EventEmitter);

Object.defineProperty(AudioStream, "maxChunkSize", {
  value: 4194304
});

Object.defineProperty(AudioStream, "partialChunkSize", {
  value: 262144
});

Object.defineProperty(AudioStream.prototype, "ready", {
  get: function() {
    return this._complete && !this._decoding;
  }
});

AudioStream.prototype.destroy = function(err) {
  if (!this.destroyed) {
    var elm = this._elem;
    this.destroyed = !0;
    this._buffer = null;
    this._fileStream.destroy();
    this._onVisibilityChange && window.removeEventListener("visibilitychange", this._onVisibilityChange);
    elm.removeEventListener("play", this._onPlay);
    elm.removeEventListener("pause", this._onPause);
    elm.removeEventListener("error", this._onError);
    elm.removeAttribute("src");
    elm.srcObject = null;
    this._stop();
    var audioStream = this._audioStream;
    if (audioStream) try {
      audioStream.disconnect();
    } catch (ex) {}
    var visualiser = this._visualiser;
    visualiser && visualiser.destroy();
    var audioContext = this._audioContext;
    audioContext && audioContext.close();
    this.emit("close");
    err && this.emit("error", err);
  }
};

AudioStream.prototype._decode = function(opts) {
  var self = this;
  if (self._buffer && !self._decoding) {
    var len, data = self._buffer, done = !!self._complete;
    if (done) {
      self.emit("audio-buffer", data = data.buffer);
      self._buffer = null;
    } else {
      if (this._bufTime > 20) {
        self._decoding = !0;
        delay("vs.decode-audio-holder", function() {
          self._decoding = !1;
          self._decode(opts);
        }, 2e3);
        return;
      }
      try {
        data = data.buffer.slice(0, self._bytesRead || void 0);
      } catch (ex) {
        log(ex);
        return;
      }
    }
    len = data.byteLength;
    d > 1 && log("Decoding new chunk...", done, len);
    self._decoding = !0;
    self._audioContext.decodeAudioData(data).then(function(buffer) {
      (done || !opts.startTime || buffer.duration > opts.startTime) && self._setup(opts.autoplay, opts.startTime, buffer);
    }).catch(function(ex) {
      (d && done || d > 1) && log(ex);
      done && self.destroy(ex);
      self._decTick = 1e11;
    }).finally(function() {
      self._decoding = !1;
      var c, b, again = !done && self._complete;
      !again && self._buffer && (c = self._buffer, again = ((b = self._bytesRead) > 0 ? Math.min(b, c.byteLength) : c.byteLength) !== len);
      again && self._decode(opts);
    });
  }
};

AudioStream.prototype._feed = function(opts) {
  var self = this;
  if (!self._decoding) return self._decode(opts);
  delay("vs.decode-audio-data", function() {
    self._decTick = 0;
    self._decode(opts);
  }, self._complete || ++self._decTick > 31 ? 90 : 4e3);
};

AudioStream.prototype._setup = function(autoplay, time, buffer) {
  var elm = this._elem;
  if (this.destroyed) log("This instance has been destroyed.", [ this ]); else {
    Object.defineProperty(elm, "duration", {
      writable: !0,
      enumerable: !0,
      configurable: !0,
      value: buffer.duration
    });
    if (this._audioBuffer) {
      time = this.currentTime;
      d > 1 && log("new chunk arrived...", [ buffer ], buffer.duration, time);
      var o = this._stopOffset;
      o && o < this._audioBuffer.duration && (this._played = -1);
      this._audioBuffer = buffer;
      this._play(time);
      this.emit("duration", buffer.duration);
    } else {
      var audioContext = this._audioContext, audioStream = audioContext.createMediaStreamDestination(), videoCanvas = document.createElement("canvas"), videoContext = videoCanvas.getContext("2d"), videoStream = this._captureStream(videoCanvas), tracks = [ audioStream.stream.getTracks()[0], videoStream.getTracks()[0] ], audioAnalyser = audioContext.createAnalyser();
      d > 1 && log("setup", buffer, autoplay, tracks);
      this._visualiser = new Visualiser(this);
      this._audioAnalyser = audioAnalyser;
      this._videoCanvas = videoCanvas;
      this._videoContext = videoContext;
      this._videoStream = videoStream;
      this._audioStream = audioStream;
      this._audioBuffer = buffer;
      audioStream.numberOfOutputs > 0 && (this._audioStream = audioContext.destination);
      autoplay && (this._played = 1);
      this._play(0 | time);
      elm.srcObject = new MediaStream(tracks);
    }
  }
};

AudioStream.prototype._stop = function() {
  if (!this._stopping) {
    this._stopping = !0;
    var audioSource = this._audioSource, visualiser = this._visualiser, ctx = this._audioContext, pos = this.currentTime;
    if (audioSource) try {
      audioSource.disconnect();
      audioSource.stop(0);
    } catch (ex) {}
    visualiser && visualiser._stop();
    if (this._played) {
      this._timeOffset = pos;
      this._stopOffset = pos;
      this._playOffset = ctx.currentTime;
    }
    this._stopping = !1;
  }
};

AudioStream.prototype._play = function(time) {
  try {
    return this.__tryPlay(time);
  } catch (ex) {
    try {
      this.destroy(ex);
    } catch (ex) {
      this.emit("error", ex);
    }
  }
};

AudioStream.prototype.__tryPlay = function(time) {
  var self = this, rate = self.playbackRate, context = self._audioContext, visualiser = self._visualiser, audioBuffer = self._audioBuffer;
  if (audioBuffer) {
    this._stop();
    if ("interrupted" !== context.state) {
      var source = context.createBufferSource();
      source.buffer = audioBuffer;
      source.connect(self._audioAnalyser);
      source.connect(self._audioStream);
      source.start(0, time);
      source.playbackRate.value = rate;
      self._audioSource = source;
      if (self._played > 0) {
        self._playOffset = context.currentTime;
        self._stopOffset = 0;
        self._timeOffset = time;
        self._ended = !1;
        self._setPBS(1);
      }
      visualiser && visualiser._start();
    } else context.resume().then(function() {
      self._play(time);
    }).catch(dump);
  } else log("Cannot play, audio buffer not yet ready.");
};

AudioStream.prototype._setPBS = function(v) {
  var self = this;
  delay("vs.audio.playback", function() {
    var f = self._file;
    if (f && !self.destroyed) {
      var s = f.playing;
      f.paused = !v;
      (f.playing = !!v) ? self.emit("activity") : s && self.emit("inactivity");
    }
  });
};

AudioStream.prototype._resume = SoonFc(40, function() {
  Promise.resolve(this._audioContext.resume()).catch(dump);
});

AudioStream.prototype._endOfStream = tryCatch(function() {
  if (!this._ended) {
    var v = this._elem, dsp = function() {
      v.removeEventListener("pause", dsp);
      v.dispatchEvent(new Event("ended"));
    };
    this._ended = !0;
    if (v.paused) dsp(); else {
      v.addEventListener("pause", dsp);
      v.pause();
    }
  }
});

AudioStream.prototype._captureStream = function(canvas) {
  var stream, raf = !parseInt(localStorage.vsnraf);
  if (!raf) try {
    var t = window.CanvasCaptureMediaStreamTrack;
    if (t && "function" === typeof t.prototype.requestFrame) {
      var tmp = canvas.captureStream(0), track = tmp.getTracks()[0];
      track.requestFrame();
      this.requestFrame = function() {
        track.requestFrame();
      };
      stream = tmp;
    }
  } catch (ex) {
    log(ex);
  }
  if (!stream) {
    raf || log("This browser does lack CanvasCaptureMediaStreamTrack.requestFrame");
    stream = canvas.captureStream(24);
  }
  return stream;
};

Object.defineProperty(AudioStream.prototype, "_bufTime", {
  get: function() {
    return (this._audioBuffer || !1).duration - this.currentTime;
  }
});

Object.defineProperty(AudioStream.prototype, "playbackRate", {
  get: function() {
    var s = this._audioSource;
    return s && s.playbackRate && s.playbackRate.value || 1;
  },
  set: function(v) {
    var s = this._audioSource;
    if (s && s.playbackRate) {
      var t = this.currentTime;
      s.playbackRate.value = v;
      this._play(t);
    }
  }
});

Object.defineProperty(AudioStream.prototype, "currentTime", {
  get: function() {
    if (this._stopOffset || !this._played) return this._stopOffset;
    var audioBuffer = this._audioBuffer || !1, result = this._timeOffset + (this._audioContext.currentTime - this._playOffset) * this.playbackRate;
    if (result >= audioBuffer.duration) if (this.ready) {
      this._endOfStream();
      result = audioBuffer.duration;
    } else if (!this._stopping) {
      this._onPause();
      this._setPBS(0);
    }
    return result;
  }
});

function AudioVisualiser(stream, fftSize) {
  var self = this;
  self._tick = 0;
  self._image = null;
  self._barWidth = 4;
  self._byteData = null;
  self._stream = stream;
  self._fftSize = fftSize || 2048;
  self._hasFocus = document.hasFocus();
  var timer = null;
  self._onResize = function() {
    clearTimeout(timer);
    timer = setTimeout(function() {
      self._start();
    }, 50);
  };
  window.addEventListener("resize", self._onResize);
  window.addEventListener("focus", self._onFocus = function() {
    self._hasFocus = !0;
    self._start();
  });
  window.addEventListener("blur", self._onBlur = function() {
    self._hasFocus = !1;
    self._stop();
  });
}

inherits(AudioVisualiser, null);

AudioVisualiser.prototype.destroy = function() {
  if (!this.destroyed) {
    this.destroyed = !0;
    window.removeEventListener("blur", this._onBlur);
    window.removeEventListener("focus", this._onFocus);
    window.removeEventListener("resize", this._onResize);
    this._stop();
  }
};

AudioVisualiser.prototype._start = function() {
  this._stop();
  this._draw();
};

AudioVisualiser.prototype._stop = function() {
  this._tick++;
  this._byteData = !1;
};

AudioVisualiser.prototype._draw = function() {
  var self = this, tick = ++self._tick, stream = self._stream, ctx = stream._videoContext, canvas = stream._videoCanvas, analyser = stream._audioAnalyser, $video = $(stream._elem).parent();
  canvas.width = $video.outerWidth() + 15 & -15;
  canvas.height = $video.outerHeight() + 15 & -15;
  self.init(ctx, canvas.width, canvas.height, canvas);
  analyser.fftSize = self._fftSize;
  analyser.smoothingTimeConstant = .85;
  self._byteData = new Uint8Array(analyser.frequencyBinCount);
  self._barWidth = Math.max(4, canvas.width / self._byteData.byteLength * 8);
  self._stop = function() {
    if (tick === this._tick++) {
      this._byteData = !1;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      stream.requestFrame && stream.requestFrame();
      self._hasFocus || ++tick;
    }
  };
  !function _draw() {
    if (tick === self._tick) {
      self.draw(ctx, canvas.width, canvas.height);
      if (stream.requestFrame) {
        stream.requestFrame();
        requestIdleCallback(_draw);
      } else requestAnimationFrame(_draw);
    }
  }();
};

function Visualiser(stream, fftSize) {
  AudioVisualiser.call(this, stream, fftSize);
  this.stars = [];
  this.volume = 0;
  this.gradient = null;
}

inherits(Visualiser, AudioVisualiser);

Visualiser.prototype.init = function(ctx, width, height, canvas) {
  var _gradient = ctx.createLinearGradient(0, ~~(height / 3), 0, ~~(height / 1.5));
  _gradient.addColorStop(1, "rgba(96, 96, 98, .3)");
  _gradient.addColorStop(.35, "rgba(74, 69, 74, .6)");
  this.gradient = _gradient;
};

Visualiser.prototype.draw = function(ctx, width, height) {
  ctx.clearRect(0, 0, width, height);
  if (this._hasFocus) {
    var data = this._byteData, analyser = this._stream._audioAnalyser;
    analyser.getByteFrequencyData(data);
    for (var value, vol = 0, i = data.byteLength, r = 0; r < 80; r++) vol += data[r];
    value = (this.volume = vol) / 1e3;
    r = 31 + (Math.sin(value) + 1);
    ctx.beginPath();
    ctx.fillStyle = this.gradient;
    r = this._barWidth;
    while (i--) ctx.fillRect(i * (r + 1), (height - (value = data[i] / 1.4)) / 1.2, r, value / 1.3);
    ctx.closePath();
    analyser.getByteTimeDomainData(data);
    ctx.beginPath();
    ctx.lineWidth = 2;
    ctx.strokeStyle = "rgba(217, 0, 7, 0.8)";
    i = data.byteLength;
    while (i--) {
      var x = i / data.byteLength * width, y = (255 - data[i]) / 255 * (.34 * height) + .66 * height;
      i === data.byteLength - 1 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
    }
    ctx.stroke();
    ctx.closePath();
  }
};

function Star(x, y, starSize, ctx, width, height, parent) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
  this.angle = Math.atan(Math.abs(y) / Math.abs(x));
  this.starSize = starSize;
  this.ctx = ctx;
  this.high = 0;
  this.parent = parent;
}

Star.prototype.drawStar = function() {
  var distanceFromCentre = Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)), brightness = 200 + Math.min(Math.round(5 * this.high), 55);
  this.ctx.lineWidth = .5 + distanceFromCentre / 2e3 * Math.max(this.starSize / 2, 1);
  this.ctx.strokeStyle = "rgba(" + brightness + ", " + brightness + ", " + brightness + ", 0.8)";
  this.ctx.beginPath();
  this.ctx.moveTo(this.x, this.y);
  var lengthFactor = 1 + Math.min(Math.pow(distanceFromCentre, 2) / 3e4 * Math.pow(this.parent.volume, 2) / 6e6, distanceFromCentre / 16), toX = Math.cos(this.angle) * -lengthFactor, toY = Math.sin(this.angle) * -lengthFactor;
  this.ctx.lineTo(this.x + (toX *= this.x > 0 ? 1 : -1), this.y + (toY *= this.y > 0 ? 1 : -1));
  this.ctx.stroke();
  this.ctx.closePath();
  var speed = lengthFactor / 20 * this.starSize;
  this.high -= Math.max(this.high - 1e-4, 0);
  speed > this.high && (this.high = speed);
  var dX = Math.cos(this.angle) * this.high, dY = Math.sin(this.angle) * this.high;
  this.x += this.x > 0 ? dX : -dX;
  this.y += this.y > 0 ? dY : -dY;
  var limitY = this.height / 2 + 500, limitX = this.width / 2 + 500;
  if (this.y > limitY || this.y < -limitY || this.x > limitX || this.x < -limitX) {
    this.x = (Math.random() - .5) * this.width / 3;
    this.y = (Math.random() - .5) * this.height / 3;
    this.angle = Math.atan(Math.abs(this.y) / Math.abs(this.x));
  }
};
},{"/bundle/utils":4,"buffer":10,"eventemitter3":15,"promise-decode-audio-data":26}],2:[function(require,module,exports){
var bcp47iso639={aar:"aa",abk:"ab",afr:"af",aka:"ak",alb:"sq",sqi:"sq",amh:"am",ara:"ar",arg:"an",arm:"hy",hye:"hy",asm:"as",ava:"av",ave:"ae",aym:"ay",aze:"az",bak:"ba",bam:"bm",baq:"eu",eus:"eu",bel:"be",ben:"bn",bih:"bh",bis:"bi",tib:"bo",bod:"bo",bos:"bs",bre:"br",bul:"bg",bur:"my",mya:"my",cat:"ca",cze:"cs",ces:"cs",cha:"ch",che:"ce",chi:"zh",zho:"zh",chu:"cu",chv:"cv",cor:"kw",cos:"co",cre:"cr",wel:"cy",cym:"cy",dan:"da",ger:"de",deu:"de",div:"dv",dut:"nl",nld:"nl",dzo:"dz",gre:"el",ell:"el",eng:"en",epo:"eo",est:"et",ewe:"ee",fao:"fo",per:"fa",fas:"fa",fij:"fj",fin:"fi",fre:"fr",fra:"fr",fry:"fy",ful:"ff",geo:"ka",kat:"ka",gla:"gd",gle:"ga",glg:"gl",glv:"gv",grn:"gn",guj:"gu",hat:"ht",hau:"ha",heb:"he",her:"hz",hin:"hi",hmo:"ho",hrv:"hr",hun:"hu",ibo:"ig",ice:"is",isl:"is",ido:"io",iii:"ii",iku:"iu",ind:"id",ipk:"ik",ita:"it",jav:"jv",jpn:"ja",kal:"kl",kan:"kn",kas:"ks",kau:"kr",kaz:"kk",khm:"km",kik:"ki",kin:"rw",kir:"ky",kom:"kv",kon:"kg",kor:"ko",kua:"kj",kur:"ku",lao:"lo",lat:"la",lav:"lv",lim:"li",lin:"ln",lit:"lt",ltz:"lb",lub:"lu",lug:"lg",mac:"mk",mkd:"mk",mah:"mh",mal:"ml",mao:"mi",mri:"mi",mar:"mr",may:"ms",msa:"ms",mlg:"mg",mlt:"mt",mon:"mn",nau:"na",nav:"nv",nbl:"nr",nde:"nd",ndo:"ng",nep:"ne",nno:"nn",nob:"nb",nor:"no",nya:"ny",oci:"oc",oji:"oj",ori:"or",orm:"om",oss:"os",pan:"pa",pli:"pi",pol:"pl",por:"pt",pus:"ps",que:"qu",roh:"rm",rum:"ro",ron:"ro",run:"rn",rus:"ru",sag:"sg",san:"sa",sin:"si",slo:"sk",slk:"sk",slv:"sl",sme:"se",smo:"sm",sna:"sn",snd:"sd",som:"so",sot:"st",spa:"es",srd:"sc",srp:"sr",ssw:"ss",sun:"su",swa:"sw",swe:"sv",tah:"ty",tam:"ta",tat:"tt",tel:"te",tgk:"tg",tgl:"tl",tha:"th",tir:"ti",ton:"to",tsn:"tn",tso:"ts",tuk:"tk",tur:"tr",twi:"tw",uig:"ug",ukr:"uk",urd:"ur",uzb:"uz",ven:"ve",vie:"vi",vol:"vo",wln:"wa",wol:"wo",xho:"xh",yid:"yi",yor:"yo",zha:"za",zul:"zu"},ns=Object.create(null);lazy(ns,"lang",function(){return String(localStorage.vslang||navigator.language||mega.intl.locale).split("-")[0]||"en"});ns.decodeMP4LangCode=function(code){return String.fromCharCode.apply(null,[96+(code>>10&31),96+(code>>5&31),96+(31&code)])};ns.bcp47match=function(lang){"number"===typeof lang&&(lang=ns.decodeMP4LangCode(lang));if((lang=bcp47iso639[lang])&&lang===(localStorage.vslang||$.vslang))return lang;for(var locales=["nn-"+mega.ipcc,mega.intl.locale,navigator.language].concat(navigator.languages),i=0;i<locales.length;++i){var locale=String(locales[i]).split("-");if(locale[1]&&String(locale[1]).toLowerCase()===lang)return lang;if(lang&&lang===locale[0])return lang}return!1};module.exports=ns;
},{}],3:[function(require,module,exports){
"use strict";

var MAX_CACHE = 0 | localStorage.maxStreamingCache || 524288e3, MIN_CACHE = 0 | localStorage.minStreamingCache || 419430400, REQUEST_SIZE = 4194304, MAX_BUF_SECONDS = 25, SIMULATE_RESUME_FROM_STALLED = !1, VideoStream = require("../videostream"), AudioStream = require("../audiostream"), inherits = require("/bundle/utils").inherit, Readable = require("readable-stream").Readable, Buffer = require("buffer").Buffer;

if (window.safari) {
  MIN_CACHE >>= 2;
  MAX_CACHE >>= 2;
}

function CacheStream(pos, file) {
  if (!(this instanceof CacheStream)) return new CacheStream(pos, file);
  Readable.call(this);
  if (!file.cache) return this;
  this.pos = pos;
  this._file = file;
  this._file.stream = this;
  var bytesleft = file.minCache, p = file.cachefind(pos);
  p < 0 && (p = -p - 1);
  file.mru++;
  while (p < file.cachepos.length && bytesleft > 0) {
    pos = file.cachepos[p++];
    bytesleft -= file.cache[pos].byteLength;
    file.cachemru[pos] = file.mru;
  }
}

inherits(CacheStream, Readable);

CacheStream.prototype._read = function(size) {
  if (this._file && this._file._vs) {
    size = this._file.readerChunkSize;
    var videoFile = this._file, videoStream = videoFile._vs, fileSize = videoFile.filesize, currentTime = videoStream._elem.currentTime, bufTime = currentTime && !(videoFile.seeking || videoFile.streamer.playbackSeeking) && videoStream.bufTime;
    if (bufTime > MAX_BUF_SECONDS) {
      videoFile.throttle = currentTime + bufTime;
      d && console.debug("[CacheStream._read()] Max buffered seconds reached, throttling until %s (current playback time is %s)...", secondsToTime(videoFile.throttle), secondsToTime(currentTime));
    } else {
      while (size) {
        var p = videoFile.cachefind(this.pos);
        if (p < 0) {
          videoFile.fetch(this.pos);
          break;
        }
        var offset = this.pos - (p = videoFile.cachepos[p]), t = size;
        videoFile.cache[p].byteLength - offset < t && (t = videoFile.cache[p].byteLength - offset);
        if (t <= 0) break;
        size -= t;
        this.pos += t;
        videoFile.cachemru[this.pos] = videoFile.mru++;
        if (!this.push(Buffer.from(videoFile.cache[p], offset, t))) break;
      }
      fileSize && this.pos === fileSize && this.push(null);
    }
  }
};

CacheStream.prototype._destroy = function(err, cb) {
  var file = this._file || !1;
  file.cache && (file.stream = !1);
  cb(err || !file.cache);
};

function VideoFile(data, streamer) {
  this.data = data;
  this.stream = null;
  this.streamer = streamer;
  this.cache = Object.create(null);
  this.cachemru = Object.create(null);
  this.fetching = Object.create(null);
  this.cachepos = [];
  this.cachesize = 0;
  this.mru = 0;
  this.curfetch = 0;
  this.filesize = -1;
  this.fetchChunkSize = REQUEST_SIZE;
  this.readerChunkSize = window.chrome ? REQUEST_SIZE >> 2 : 262144;
  this.throttle = 0;
  this.backoff = 200;
  this.paused = !0;
  this.playing = !1;
  this.canplay = !1;
  this.overquota = !1;
  this.bgtask = !streamer.options.autoplay;
  this.retryq = [];
  this.minCache = MIN_CACHE;
  this.maxCache = MAX_CACHE;
  if (data instanceof Blob) {
    if (!(d > 1)) {
      this.minCache = 67108864;
      this.maxCache = 83886080;
    }
    this.fetcher = this.fileReader;
  } else {
    var o = streamer.options || {};
    if (o.filesize > 0) {
      this.filesize = o.filesize;
      if (o.bitrate > this.fetchChunkSize) {
        this.fetchChunkSize = o.bitrate + 16777216 & -16777216;
        d && console.debug("chunk-size set to %s", this.fetchChunkSize);
      }
    }
  }
  window.addEventListener("online", this);
}

VideoFile.prototype = Object.create(null);

Object.defineProperty(VideoFile.prototype, "isOnline", {
  get: function() {
    return !1 !== navigator.onLine;
  }
});

VideoFile.prototype.handleEvent = function(ev) {
  d && console.debug("[VideoFile.handleEvent()]", ev.type, ev);
  "online" !== ev.type || this.overquota || this.flushRetryQueue();
};

VideoFile.prototype.destroy = function() {
  for (var keys = Object.keys(this), i = keys.length; i--; ) delete this[keys[i]];
  window.removeEventListener("online", this);
  Object.freeze(this);
};

VideoFile.prototype.reset = function() {
  window.removeEventListener("online", this);
  VideoFile.call(this, this.data, this.streamer);
};

VideoFile.prototype.flushRetryQueue = function() {
  if (this.retryq && this.retryq.length) {
    for (var i = 0; i < this.retryq.length; i++) later(this.retryq[i]);
    this.retryq = [];
    this.overquota = !1;
  }
};

VideoFile.prototype.createReadStream = function(opts) {
  return new CacheStream(opts.start || 0, this);
};

VideoFile.prototype.cachefind = function(pos) {
  var max = this.cachepos.length;
  if (!max) return -1;
  if (pos < this.cachepos[0]) return -1;
  for (var min = 0; ;) {
    var mid = min + max >> 1;
    if (pos >= this.cachepos[mid]) {
      var n = this.cache[this.cachepos[mid]];
      if (!n) return -1;
      if (pos < this.cachepos[mid] + n.byteLength) return mid;
      min = 1 + mid;
    } else max = mid;
    if (min == max) return -max - 1;
  }
};

VideoFile.prototype.cacheadd = function(pos, data) {
  var gap = this.cachefind(pos);
  if (gap >= 0) console.error("*** Mediacache: Internal error - clash"); else if ((gap = -gap - 1) < this.cachepos.length && pos + data.byteLength > this.cachepos[gap]) console.error("*** Mediacache: Internal error - overlap"); else {
    this.cachepos.splice(gap, 0, pos);
    this.cache[pos] = data;
    this.cachemru[pos] = this.mru++;
    this.cachesize += data.byteLength;
    if (this.cachesize > this.maxCache) {
      var self = this, purge = this.cachepos.slice(0);
      purge.sort(function(a, b) {
        return (self.cachemru[a] > self.cachemru[b]) - (self.cachemru[a] < self.cachemru[b]);
      });
      for (var i = 0; this.cachesize > this.minCache; i++) {
        var p = purge[i];
        this.cachesize -= this.cache[p].byteLength;
        delete this.cache[p];
        delete this.cachemru[p];
        this.cachepos.splice(this.cachepos.indexOf(p), 1);
      }
    }
  }
};

VideoFile.prototype.fetcher = function(data, byteOffset, byteLength) {
  return SIMULATE_RESUME_FROM_STALLED && byteOffset > 8 * REQUEST_SIZE ? Promise.reject({
    target: {
      status: 509
    }
  }, data) : M.gfsfetch(data, byteOffset, byteLength);
};

VideoFile.prototype.fileReader = function(data, byteOffset, byteLength) {
  return byteOffset > data.size ? Promise.reject(ERANGE) : new Promise(function(resolve, reject) {
    var blob = data.slice(byteOffset, byteLength), reader = new FileReader();
    reader.onload = function() {
      var chunk = new Uint8Array(this.result);
      chunk.payload = {
        s: data.size
      };
      resolve(chunk);
    };
    reader.onerror = reject;
    reader.readAsArrayBuffer(blob);
  });
};

VideoFile.prototype.fetch = function(startpos, recycle) {
  var p, length, self = this, pos = startpos;
  if (recycle && this.paused && this.cachesize >= this.minCache && this.canplay) d && console.debug("[VideoFile.fetch()] MIN_CACHE reached, will not fetch more data until no longer %s...", this.paused ? "paused" : "throttled"); else if (void 0 !== this.mru) {
    this.curfetch += !recycle;
    do {
      length = this.fetchChunkSize || REQUEST_SIZE;
      while ((p = this.cachefind(pos)) >= 0) {
        pos = this.cachepos[p] + this.cache[this.cachepos[p]].byteLength;
        length = 0;
      }
      while (this.fetching[pos]) {
        pos += this.fetching[pos];
        length = 0;
      }
    } while (!length);
    if ((p = -p - 1) < this.cachepos.length) {
      var t = this.cachepos[p] - pos;
      t < length && (length = t);
    }
    for (p in this.fetching) {
      if (pos >= (p = +p) && pos < p + this.fetching[p]) return;
      p >= pos && p - pos < length && (length = p - pos);
    }
    this.filesize >= 0 && pos + length >= this.filesize && (length = this.filesize - pos);
    if (!(length < 1)) {
      this.fetching[pos] = length;
      var thisfetch = this.curfetch;
      d && console.debug("Fetching %s-%s, length=%s...", pos, pos + length, length);
      this.fetcher(this.data, pos, pos + length).then(function(chunk) {
        var data = chunk.payload, buffer = chunk.buffer;
        if (void 0 !== self.mru) {
          if ("string" === typeof self.data) {
            data._ticket = self.data;
            self.data = data;
          }
          self.filesize < 0 && (self.filesize = data.s);
          delete self.fetching[pos];
          self.cacheadd(pos, buffer);
          pos += buffer.byteLength;
          thisfetch === self.curfetch && setTimeout(self.fetch.bind(self, pos, 1), 100);
          self.backoff = 200;
          self.feedPlayer();
        }
      }).catch(function(ev) {
        var data = self.data, xhr = ev && ev.target || !1;
        if (void 0 !== self.mru) {
          delete self.fetching[pos];
          var retry = function() {
            queueMicrotask(self.fetch.bind(self, startpos, recycle));
          };
          if ("number" === typeof ev) {
            if (ev !== ERANGE || data && pos < data.s) {
              d && console.warn("Unrecoverable stream fetch error, aborting...", self.isOnline, ev, pos);
              self.streamer.notify("error", new Error(api_strerror(ev)));
            }
          } else if (509 === xhr.status) {
            d && console.warn("stream overquota, holding...", ev);
            "object" === typeof self.data && (self.data = self.data._ticket);
            self.overquota = !0;
            self.retryq.push(retry);
            self.streamer._setActivityTimer(50);
          } else {
            d && console.warn("stream fetch error, retrying...", self.isOnline, ev);
            if (self.isOnline) {
              self.backoff = Math.min(self.backoff << 1, 7e3);
              setTimeout(retry, self.backoff);
              403 === xhr.status && "object" === typeof self.data && (self.data = self.data._ticket || self.data);
            } else self.retryq.push(retry);
          }
        }
      });
      return this;
    }
    length < 0 && d && this.filesize >= 0 && console.error("*** Mediacache: Internal error - out of bound.", startpos, pos, length);
  }
};

VideoFile.prototype.feedPlayer = function() {
  if (this.stream) try {
    this.stream._read(0);
  } catch (ex) {
    this.streamer.notify("error", ex);
  }
};

/**
 * Start streaming a MEGA file.
 * @param {String} data The data needed by gfsfetch()
 * @param {Object} video The <video> element
 * @param {Object} [options] Additional options
 * @constructor
 * @preserve
 */ function Streamer(data, video, options) {
  var uad = ua.details;
  if (!(this instanceof Streamer)) return new Streamer(data, video, options);
  this.gecko = "Gecko" === uad.engine;
  this.options = options || Object.create(null);
  void 0 === this.options.autoplay && (this.options.autoplay = !0);
  this._events = [ "progress", "timeupdate", "canplay", "pause", "playing", "error", "abort", "updateend", "ended", "stalled", "suspend", "durationchange" ];
  if (video.parentNode && this.gecko && parseInt(uad.version) < 57) {
    this.sbflush = !0;
    this._events.push("seeking");
    this.WILL_AUTOPLAY_ONSEEK = !0;
  }
  for (var i = this._events.length; i--; ) video.addEventListener(this._events[i], this, !1);
  this.state = !1;
  this.video = video;
  this.timeupdate = 0;
  this.stalled = !1;
  this.evs = Object.create(null);
  this.presentationOffset = 0;
  this.playbackTook = Date.now();
  this.playbackEvent = !1;
  this.playbackSeeking = !1;
  d && window.vssrfs && (SIMULATE_RESUME_FROM_STALLED = !0);
  void 0 === this.options.type ? this.initTypeGuess(data) : this.init(data);
  if (d) {
    window.strm || (window.strm = new WeakSet());
    window.strm.add(this);
    window.strm.last = this;
  }
}

Streamer.prototype = Object.create(null);

Streamer.prototype.init = function(data) {
  var self = this;
  if (self.video) {
    self.file = new VideoFile(data, self);
    !1 === self.options.autoplay ? self.file.minCache = 16777216 : self.video.setAttribute("autoplay", !0);
    var options = Object.assign(self.options, {
      sbflush: self.sbflush,
      bufferDuration: 1.8 * MAX_BUF_SECONDS
    });
    if (this.goAudioStream) {
      void 0 === options.partial && (options.partial = !localStorage.vsNoPartialAudio);
      if (options.partial) {
        var s = AudioStream.partialChunkSize;
        self.file.fetchChunkSize = s;
        self.file.readerChunkSize = s;
      }
      self.stream = new AudioStream(self.file.fetch(0), self.video, options);
      [ "error", "audio-buffer", "duration", "activity", "inactivity" ].forEach(function(ev) {
        self.stream.on(ev, function(a) {
          self.notify(ev, a);
        });
      });
    } else {
      self.stream = new VideoStream(self.file.fetch(0), self.video, options);
      if (self.gecko) {
        var waiting = !1;
        !function _() {
          if (!waiting) {
            waiting = !0;
            self.on("stalled", function() {
              var range = this.stream.getBufferedRange();
              d && console.log("First range on stalled", range, this.timeupdate);
              if (!this.timeupdate && range[0] > 1) {
                console.warn("Applying presentation timestamp fixup...", range);
                this.presentationOffset = range[0];
                this.currentTime = 0;
              }
              return waiting = !range;
            });
            self.on("ended", _);
          }
        }();
      }
    }
    self.file._vs = self.stream;
  } else d && console.debug("Cannot initialize... already destroyed?", self);
};

Streamer.prototype.initTypeGuess = function(data) {
  function init(data) {
    file.destroy();
    self.init(data);
  }
  var self = this, file = new VideoFile(data, self);
  file.fetcher(data, 0, 16).then(function(chunk) {
    var dv = new DataView(chunk.buffer), long = dv.getUint32(0, !1);
    440786851 === long ? self.options.type = "WebM" : long >> 8 === 4801587 ? self.options.type = "MPEG Audio" : 1332176723 === long ? self.options.type = "Ogg" : 1716281667 === long ? self.options.type = "FLAC" : 1295270176 === dv.getUint32(8, !1) ? self.options.type = "M4A " : 1463899717 === dv.getUint32(8, !1) && (self.options.type = "Wave");
    init("string" === typeof data ? chunk.payload || chunk : data);
  }).catch(function(ex) {
    d && console.debug("Type guess failed...", ex);
    init(data);
  });
};

Streamer.prototype.destroy = function() {
  var i;
  d && console.debug("Destroying Streamer instance.", this);
  this._clearActivityTimer();
  try {
    this.stream && this.stream.destroy();
  } catch (ex) {
    console.warn(ex);
  }
  this.file && this.file.destroy();
  if (this.video) {
    for (i = this._events.length; i--; ) this.video.removeEventListener(this._events[i], this, !1);
    if (this.video.parentNode) {
      var video = this.video, clone = video.cloneNode(), parent = video.parentNode;
      try {
        clone.currentTime = 0;
      } catch (ex) {}
      clone.removeAttribute("src");
      clone.removeAttribute("style");
      clone.removeAttribute("poster");
      clone.removeAttribute("autoplay");
      parent.removeChild(video);
      parent.appendChild(clone);
    }
  }
  d && window.strm && window.strm.delete(this);
  delete this.evs;
  delete this.file;
  delete this.video;
  delete this.stream;
};

Streamer.prototype.onPlayBackEvent = function(playing) {
  var videoFile = this.file;
  if (videoFile.paused) {
    videoFile.paused = !1;
    if (videoFile.stream) {
      d && console.debug("Was paused, continuing fetching data...");
      videoFile.fetch(videoFile.stream.pos);
    }
  }
  if (playing) {
    videoFile.playing = !0;
    videoFile.seeking = !1;
    if (!this.playbackEvent) {
      this.playbackEvent = !0;
      this.playbackTook = Date.now() - this.playbackTook;
    }
    this.playbackSeeking = !1;
    this.stream._sbQuotaError && (this.stream._sbQuotaError = !1);
    delay.cancel("vs.force-track-pump");
    if (this.stalled) {
      this.stalled = !1;
      this.notify("activity");
    }
  }
};

Streamer.prototype.canSwitchAudioTrack = tryCatch(function(error) {
  var stream = this.stream || !1, muxer = stream._muxer || !1;
  if (stream instanceof VideoStream && muxer._chosenAudioTrack >= 0) {
    this.options.bat || (this.options.bat = Object.create(null));
    this.options.bat[muxer._chosenAudioTrack] = 1;
    d && error && console.info("Stream error, attempting to switch to another audio track...", error, this.options);
    var self = this;
    tryCatch(function() {
      self.stream.destroy();
    })();
    this.stream = new VideoStream(this.file, this.video, this.options);
    return !0;
  }
  return !1;
});

Streamer.prototype.handleEvent = function(ev) {
  var target = ev.target, videoFile = this.file;
  (d && "timeupdate" !== ev.type || d > 4) && console.debug("Event(%s)", ev.type, target, ev);
  this.state = ev.type;
  if (!videoFile) {
    d && console.warn("VideoFile instance is not available, already destroyed?", ev.type, [ this ]);
    return !1;
  }
  switch (ev.type) {
   case "seeking":
    videoFile.seeking = !0;
    this.stream.flushSourceBuffers();
    this.video.paused && queueMicrotask(this.play.bind(this));

   case "playing":
    this.onPlayBackEvent("playing" === ev.type);
    break;

   case "pause":
    videoFile.paused = !0;
    videoFile.playing = !1;
    this._clearActivityTimer();
    break;

   case "durationchange":
    this.duration > 0 && this.notify("duration", this.duration);
    break;

   case "progress":
    target.removeEventListener("progress", this);
    if (d > 1) {
      var ew = this.stream._elemWrapper, ms = ew && ew._mediaSource;
      if (ms) {
        ms.addEventListener("sourceclose", console.warn.bind(console));
        ms.addEventListener("sourceended", console.warn.bind(console));
      }
    }
    if (videoFile.playing) break;

   case "canplay":
    videoFile.canplay = !0;
    !this.options.autoplay || videoFile.playing || this.playbackEvent && videoFile.paused || this.play();
    if (videoFile.fetchChunkSize > REQUEST_SIZE) {
      videoFile.fetchChunkSize = REQUEST_SIZE;
      d && console.debug("chunk-size reset to %s", videoFile.fetchChunkSize);
    }
    break;

   case "ended":
    this._clearActivityTimer();
    this.stream instanceof VideoStream && this.stream.flushSourceBuffers(-1);
    break;

   case "stalled":
    var stream = this.stream;
    if (!this.isOverQuota && stream instanceof VideoStream) if (videoFile.playing) stream.findTimeGAPs() && stream._enqueueForcePump(); else if (this.playbackSeeking) {
      d && console.warn("Forcing pump while stalled on seeking...", this.video.currentTime, [ this ]);
      stream._enqueueForcePump(Math.max(1, this.video.currentTime - 2));
    }
    break;

   case "timeupdate":
    if (videoFile.throttle && videoFile.throttle - target.currentTime < MAX_BUF_SECONDS / 3) {
      d && console.debug("[Streamer.timeupdate] Throttle threshold %s reached at playback time %s, resuming...", secondsToTime(videoFile.throttle), secondsToTime(target.currentTime), !!videoFile.stream);
      videoFile.throttle = 0;
      videoFile.stream && videoFile.stream._read(0);
    }
    if (this.timeupdate !== target.currentTime) {
      this.timeupdate = target.currentTime;
      this.stalled && target.readyState > 2 && this.onPlayBackEvent(!0);
      videoFile.paused || this._setActivityTimer();
    }
  }
  if (this.evs[ev.type]) {
    if ("error" === ev.type) {
      var mediaError = target.error || !1, streamError = Object(this.stream._elemWrapper).detailedError, error = streamError && streamError.message || mediaError.message;
      mediaError.code && console.warn("MediaError %s", mediaError.code, mediaError.message);
      streamError && console.warn("StreamError", streamError);
      if (this.canSwitchAudioTrack(error || -13)) return;
    }
    this.notify(ev, error || !1);
  }
};

Streamer.prototype.retry = function() {
  SIMULATE_RESUME_FROM_STALLED = !1;
  dlmanager._onQuotaRetry(!0);
};

Streamer.prototype.play = function() {
  try {
    var self = this, stream = self.stream;
    if (stream instanceof AudioStream) {
      var ctx = stream._audioContext || !1;
      "suspended" === ctx.state && ctx.resume();
    }
    var promise = self.video.play();
    "undefined" !== typeof Promise && promise instanceof Promise && promise.then(function() {
      if (self.file) {
        d && console.debug("Playing, current time: %s, duration: %s", secondsToTime(self.currentTime), secondsToTime(self.duration));
        stream instanceof AudioStream && stream._play(self.currentTime);
      }
    }).catch(function(ex) {
      d && console.debug("video.play() failed...", ex);
      var f = self.file || !1;
      if (f.canplay && ex && "NotAllowedError" === ex.name) {
        f.bgtask = -1;
        f.minCache = 4194304;
        vsNT(self.notify.bind(self, "cannot-play", ex));
      }
    });
  } catch (ex) {}
  var videoFile = this.file || !1;
  if (videoFile.bgtask) {
    videoFile.bgtask = !1;
    videoFile.minCache = MIN_CACHE;
    videoFile.overquota || videoFile.flushRetryQueue();
    this.options.autoplay = !0;
  }
  if (videoFile) {
    videoFile.throttle = 0;
    this._setActivityTimer();
  }
};

Streamer.prototype.on = function(ev, success, error) {
  if (this.evs) {
    success = tryCatch(success.bind(this), error);
    this.evs[ev] ? this.evs[ev].push(success) : this.evs[ev] = [ success ];
  }
  return this;
};

Streamer.prototype.notify = function(ev) {
  var type = String("object" === typeof ev && ev.type || ev);
  if (this.evs && this.evs[type]) {
    for (var args = new Array(arguments.length), i = args.length; i--; ) args[i] = arguments[i];
    "object" !== typeof ev && (args[0] = {
      type: type,
      target: this
    });
    var result = this.evs[type].filter(function(cb) {
      return cb.apply(null, args);
    });
    if (this.evs) {
      this.evs[type] = result;
      this.evs[type].length || delete this.evs[type];
    }
  }
};

Streamer.prototype._clearActivityTimer = function() {
  delay.cancel("vs:activity-timer");
};

Streamer.prototype._setActivityTimer = function(force) {
  var self = this;
  !force && self.stream instanceof AudioStream || delay("vs:activity-timer", function() {
    var video = self.video || !1;
    if (!video.paused && !video.ended || !self.file.bgtask && self.isOverQuota) {
      self.stalled = !0;
      self.notify("inactivity");
      if ("suspend" === self.state && !self.playbackEvent) {
        d && console.warn("Got suspend event, performing time fixup...");
        self.currentTime += .1;
      }
      self.handleEvent({
        type: "stalled",
        fake: 1,
        target: video
      });
    }
  }, force || 1600);
};

Streamer.prototype.getImage = function(w, h) {
  var tick = 96, self = this, video = this.video;
  return new Promise(function _(resolve, reject) {
    if (video.videoWidth && !video.error) {
      var dim = self.dim(video.videoWidth, video.videoHeight, w || 1280, h || 720);
      d && console.debug("[Streamer.getImage()] Taking %sx%s image from %sx%s at %s", dim.width, dim.height, video.videoWidth, video.videoHeight, secondsToTime(video.currentTime));
      var canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
      canvas.width = Math.round(dim.width);
      canvas.height = Math.round(dim.height);
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      var i, ab = ctx.getImageData(0, 0, canvas.width, canvas.height).data, len = i = ab.byteLength, bp = 0;
      while (i--) ab[i] < 30 && bp++;
      if (Math.round(100 * bp / len) > 70) {
        d && console.debug("[Streamer.getImage()] Got +70% of black pixels, retrying...");
        video.paused || video.ended || !--tick ? queueMicrotask(function() {
          reject(-5);
        }) : setTimeout(_.bind(this, resolve, reject), 800);
      } else resolve(dataURLToAB(canvas.toDataURL("image/png")));
    } else queueMicrotask(function() {
      reject(video.error || -9);
    });
  });
};

Streamer.prototype.dim = function(srcWidth, srcHeight, maxWidth, maxHeight) {
  var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
  return {
    width: srcWidth * ratio,
    height: srcHeight * ratio,
    ratio: ratio
  };
};

Streamer.getThumbnail = function(data) {
  return new Promise(function(resolve, reject) {
    if (data.__getVTNPid) return reject(-5);
    Object.isExtensible(data) && Object.defineProperty(data, "__getVTNPid", {
      value: Streamer.pid
    });
    var video = document.createElement("video");
    video.muted = !0;
    function _reject(e) {
      s.destroy();
      reject(e);
    }
    function _resolve(ab) {
      resolve(ab);
      s.destroy();
    }
    function _pump() {
      delay(tid, _onstalled, 7e3);
      s.play();
    }
    var step = -1, offset = -1, tid = "vst." + makeUUID(), s = Streamer(data, video, {
      videoOnly: !0
    }), _onstalled = function() {
      var stream = s.stream;
      if (stream) {
        if (!(stream instanceof VideoStream)) return _reject(-9);
        queueMicrotask(_pump);
        offset < 1 && (offset = 0 | Math.min(2 + (0 | video.currentTime), video.duration - 3));
        if ((offset += 2.3) + 3 > video.duration) return _reject(-7);
        stream._enqueueForcePump(s.currentTime = offset);
        return !0;
      }
    };
    s.on("progress", _pump);
    s.on("stalled", _onstalled);
    s.on("playing", function() {
      if (!++step) {
        queueMicrotask(_pump);
        this.currentTime = 20 * (0 | video.duration) / 100;
        return !0;
      }
      delay.cancel(tid);
      s.getImage().then(_resolve).catch(_reject);
    });
    s.on("error", _reject);
  });
};

Streamer.prototype.getProperty = function(key) {
  var file = this.file || !1;
  switch (key) {
   case "server":
    var data = file.data, url = data && data.g;
    return url && String(url).split("//").pop().split(".")[0] || !1;

   case "bitrate":
    return file.filesize / this.duration || !1;
  }
  return !1;
};

Object.defineProperty(Streamer.prototype, "ended", {
  get: function() {
    var stream = this.stream;
    return (this.video || !1).ended || stream instanceof AudioStream && stream._ended;
  }
});

Object.defineProperty(Streamer.prototype, "paused", {
  get: function() {
    return (this.video || !1).paused;
  }
});

Object.defineProperty(Streamer.prototype, "interrupted", {
  get: function() {
    return this.paused || this.ended;
  }
});

Object.defineProperty(Streamer.prototype, "playing", {
  get: function() {
    return this.hasStartedPlaying && !this.interrupted;
  }
});

Object.defineProperty(Streamer.prototype, "playbackRate", {
  get: function() {
    var video = this.video, stream = this.stream;
    return stream instanceof AudioStream ? stream.playbackRate : video && video.playbackRate;
  },
  set: tryCatch(function(v) {
    var video = this.video, stream = this.stream;
    stream instanceof AudioStream ? stream.playbackRate = v : video && (video.playbackRate = v);
  })
});

Object.defineProperty(Streamer.prototype, "gain", {
  set: function(v) {
    var stream = this.stream;
    if (stream instanceof AudioStream) {
      var sn = stream._audioSource || !1;
      sn.gain && (sn.gain.value = v);
    }
  }
});

Object.defineProperty(Streamer.prototype, "volume", {
  get: function() {
    return (this.video || !1).volume;
  },
  set: function(v) {
    var video = this.video || !1, vol = v < .1 ? .1 : v > 1 ? 1 : v;
    this.gain = vol;
    video && (video.volume = vol);
  }
});

Object.defineProperty(Streamer.prototype, "muted", {
  get: function() {
    return (this.video || !1).muted;
  },
  set: function(v) {
    var video = this.video || !1;
    -1 === v && (v = !this.muted);
    this.gain = !v;
    video && (video.muted = v);
  }
});

Object.defineProperty(Streamer.prototype, "duration", {
  get: function() {
    var video = this.video || !1;
    return Infinity !== video.duration && video.duration - this.presentationOffset;
  }
});

Object.defineProperty(Streamer.prototype, "currentTime", {
  get: function() {
    var stream = this.stream || !1;
    return stream instanceof AudioStream ? stream.currentTime : (this.video || !1).currentTime - this.presentationOffset;
  },
  set: function(v) {
    var video = this.video || !1, stream = this.stream || !1;
    if (stream instanceof AudioStream) {
      stream._play(v);
      this.play();
    } else if (video.readyState) {
      video.currentTime = v + this.presentationOffset;
      this.play();
    } else d && console.debug("Ignoring seek attempt, invalid state...");
    this.playbackSeeking = !0;
  }
});

Object.defineProperty(Streamer.prototype, "goAudioStream", {
  get: function() {
    var type = (this.options || !1).type;
    return "M4A " === type ? mega.fullAudioContextSupport : "MPEG Audio" === type || "Wave" === type || "Ogg" === type || "FLAC" === type;
  }
});

Object.defineProperty(Streamer.prototype, "hasAudio", {
  get: function() {
    return this.stream && (Object(this.stream._muxer)._hasAudio || this.stream._hasAudio);
  }
});

Object.defineProperty(Streamer.prototype, "hasUnsupportedAudio", {
  get: function() {
    return this.stream && Object(this.stream._muxer)._hasUnsupportedAudio;
  }
});

Object.defineProperty(Streamer.prototype, "hasVideo", {
  get: function() {
    return this.stream && Object(this.stream._muxer)._hasVideo;
  }
});

Object.defineProperty(Streamer.prototype, "isOverQuota", {
  get: function() {
    var file = this.file || !1;
    return file.overquota && !Object.keys(file.fetching || {}).length;
  }
});

Object.defineProperty(Streamer.prototype, "hasStartedPlaying", {
  get: function() {
    return this.playbackEvent && (this.playbackTook || !0);
  }
});

Object.defineProperty(Streamer.prototype, "gotIntoBuffering", {
  get: function() {
    return this.stalled && this.hasStartedPlaying && this.currentTime < this.duration && !this.playbackSeeking;
  }
});

Object.defineProperty(Streamer, "pid", {
  value: Symbol((Date.now() * Math.random()).toString(26))
});

/**
 *  @global
 *  @preserve
 *  @name Streamer
 */ Object.defineProperty(self, "Streamer", {
  value: Object.freeze(Streamer)
});
},{"../audiostream":1,"../videostream":46,"/bundle/utils":4,"buffer":10,"readable-stream":41}],4:[function(require,module,exports){
var Buffer = require("buffer").Buffer, onNextTick = function() {
  function dsp() {
    var i = 0, q = cbs;
    cbs = [];
    while (i < q.length) q[i++]();
  }
  var cbs = [];
  return function(cb) {
    1 === cbs.push(cb) && queueMicrotask(dsp);
  };
}();

Object.defineProperty(window, "vsNT", {
  value: onNextTick
});

var utils = {
  debuglog: function(name) {
    if (d > 8) {
      var logger = MegaLogger.getLogger(name);
      return logger.debug.bind(logger);
    }
    return function() {};
  },
  nextTick: function() {
    var cb = arguments[0];
    if (arguments.length > 1) {
      arguments[0] = null;
      onNextTick(Function.prototype.bind.apply(cb, arguments));
    } else onNextTick(cb);
  },
  inherit: window.inherits || function(target, source) {
    target.prototype = Object.create(source && source.prototype || source);
    Object.defineProperty(target.prototype, "constructor", {
      value: target,
      enumerable: !1
    });
  },
  deprecate: function(cb, msg) {
    var warned = !1;
    return function() {
      if (!warned) {
        warned = !0;
        console.warn(msg);
      }
      return cb.apply(this, arguments);
    };
  },
  isU8: function(obj) {
    return obj instanceof Uint8Array || Buffer.isBuffer(obj);
  }
};

module.exports = utils;
},{"buffer":10}],5:[function(require,module,exports){
"use strict";

var inherits = require("/bundle/utils").inherit, Buffer = require("buffer").Buffer, stream = require("readable-stream"), EventEmitter = require("eventemitter3").EventEmitter, EBMLDecoder = require("ebml/lib/ebml/decoder");

module.exports = EBMLRemuxer;

var DEBUG = 0 | localStorage.vsd, DEBUG_INFO = DEBUG || window.d, DEBUG_ALL = DEBUG > 3, DEBUG_TRACE = DEBUG > 2, DEBUG_VERBOSE = DEBUG > 1;

if (DEBUG_TRACE) {
  var tmp = function() {
    this.$etup();
  };
  createStream(tmp, EBMLDecoder);
  EBMLDecoder = tmp;
}

function EBMLRemuxer(file) {
  var self = this;
  this.$etup();
  this._file = file;
  this._tracks = [];
  this._seekTime = -1;
  this._hasVideo = !1;
  this._hasAudio = !1;
  this._seekTable = !1;
  this._seekTimeFixup = -1;
  this._initSegment = !1;
  this._createReader(0, "segment", function(segment) {
    this.destroy();
    self.setInitSegment(segment);
  });
}

createStream(EBMLRemuxer, EventEmitter);

EBMLRemuxer.prototype.emitInitSegment = function(segment) {
  var tracks = segment.Tracks;
  DEBUG_INFO && console.log("initSegment", segment, [ this ]);
  if (!tracks) return this.destroy(new Error("Unsupported media format."));
  for (var getCodec = function(codec) {
    var c = String(codec).substr(2).toLowerCase();
    "av1" === c && (c = "av01.0.00M.08");
    return c;
  }, i = tracks.length; i--; ) {
    var track = tracks[i], codec = String(track.CodecID).replace(/\W/g, ""), type = track.TrackType, mime = function(codec, type) {
      switch (codec) {
       case "A_VORBIS":
       case "A_OPUS":
       case "V_VP8":
       case "V_VP9":
       case "V_AV1":
        return (1 === type ? "video" : "audio") + '/webm; codecs="' + getCodec(codec) + '"';
      }
    }(codec, type);
    DEBUG_INFO && console.debug("Track%s, %s, %s", track.TrackNumber, codec, mime, track);
    if (mime) {
      if (this._hasVideo || 1 !== type) {
        if (this._hasAudio || 2 !== type) continue;
        if (!MediaSource.isTypeSupported(mime)) {
          DEBUG_INFO && console.debug("Unsupported audio track.", mime);
          continue;
        }
        this._hasAudio = codec;
      } else this._hasVideo = codec;
      track.mime = mime;
    }
  }
  if (this._hasVideo) {
    mime = 'video/webm; codecs="' + getCodec(this._hasVideo);
    this._hasAudio && (mime += "," + getCodec(this._hasAudio));
    this._tracks.push({
      mime: mime + '"'
    });
  } else this._hasAudio && this._tracks.push({
    mime: 'audio/webm; codecs="' + getCodec(this._hasAudio) + '"'
  });
  if (!this._tracks.length) return this.destroy(new Error("no playable tracks"));
  if (segment.Cues) {
    this._shrink(segment, {
      Cues: "CuePoint"
    });
    for (var c = segment.Cues, y = segment.playtime, t = this._seekTable = [], j = c.length; j--; ) {
      var p = c[j], x = p.CueTrackPositions, z = Math.round(p.CueTime * segment.timescale * 1e3) / 1e3;
      t.push([ z, y, x.CueClusterPosition + segment.offset ]);
      y = z;
    }
  }
  var data = this._tracks.map(function(track) {
    return {
      mime: track.mime,
      init: segment.data
    };
  });
  this._initSegment = segment;
  this.emit("ready", data);
};

EBMLRemuxer.prototype._shrink = function(segment, props) {
  for (var k in props) segment[k] && (segment[k] = segment[k][props[k]]) && (Array.isArray(segment[k]) || (segment[k] = [ segment[k] ]));
};

EBMLRemuxer.prototype._createReader = function(offset, target, event, cb) {
  var reader = new EBMLReader(this._file, offset);
  if ("string" === typeof target) {
    cb = event;
    event = target;
    target = this;
  }
  reader.on(event, function() {
    cb.apply(reader, arguments);
  });
  reader.on("error", function(err) {
    target.destroy(err);
  });
  return reader;
};

EBMLRemuxer.prototype.setInitSegment = function(segment) {
  var self = this, info = segment.Info;
  if (info) {
    segment.timescale = info.TimecodeScale / 1e9;
    segment.playtime = info.Duration * segment.timescale;
  }
  this._shrink(segment, {
    Tracks: "TrackEntry",
    SeekHead: "Seek",
    Tags: "Tag"
  });
  if (!segment.Cues && segment.SeekHead) {
    for (var cuesOffset = -1, i = segment.SeekHead.length; i--; ) {
      var seekHead = segment.SeekHead[i];
      if (475249515 === seekHead.SeekID.readInt32BE()) {
        cuesOffset = seekHead.SeekPosition + segment.offset;
        break;
      }
    }
    if (cuesOffset > 0) {
      this._createReader(cuesOffset, "cues", function(chunk) {
        segment.Cues = chunk.Cues;
        self.emitInitSegment(segment);
        this.destroy();
      });
      return;
    }
  }
  this.emitInitSegment(segment);
};

EBMLRemuxer.prototype._findCluster = function(time) {
  var offset = 0, t = this._seekTable;
  this._seekTime = time = Math.round(1e3 * time) / 1e3;
  for (var i = 0; i < t.length; ++i) {
    var x = t[i][0];
    if (time >= x && time <= t[i][1]) {
      time = x;
      offset = t[i + 1] ? t[i + 1][2] : t[i][2];
      break;
    }
  }
  this._seekTimeFixup = time;
  return offset || this._initSegment.data.length;
};

EBMLRemuxer.prototype.seek = function(time) {
  var self = this, offset = self._findCluster(time);
  return self._tracks.map(function(track, i) {
    track.outStream && track.outStream.destroy();
    return track.outStream = new MediaSegment(self, offset);
  });
};

function EBMLReader(file, offset) {
  this.$etup();
  this._file = file;
  this._conGroup = 0;
  this._cluster = null;
  this._ebmlOffset = 0;
  this._lastBlock = null;
  this._clusterCount = 0;
  this._segmentOffset = 0;
  this._timecodes = [ 0, 0 ];
  this._clusterOffset = -1;
  this._byteOffset = offset;
  this._trackDefaultDuration = 0;
  this._segment = Object.create(null);
  try {
    this.$buffer = new Buffer(33554432);
  } catch (ex) {
    vsNT(this.emit.bind(this, "error", ex));
    return this;
  }
  this.$head = 0;
  this._decoder = new EBMLDecoder();
  this._fileStream = file.createReadStream({
    start: offset
  });
  this._fileStream.pipe(this);
  var self = this;
  this._decoder.on("data", function(chunk) {
    self._onData(chunk[0], chunk[1]);
  });
  this.on("finish", function() {
    self._onFinish();
  });
}

createStream(EBMLReader, stream.Writable, function() {
  if (this._fileStream) {
    this._fileStream.destroy();
    this._fileStream = null;
  }
  if (this._decoder) {
    this._decoder.end();
    this._decoder.destroy();
    this._decoder = null;
  }
  this.$buffer = null;
  this._cluster = null;
  while (this._conGroup-- > 0) console.groupEnd();
});

EBMLReader.prototype._getValue = function(chunk) {
  var data = chunk.data;
  if ("b" === chunk.type) return data;
  if ("s" === chunk.type) return data.toString("ascii");
  if ("8" === chunk.type) return data.toString("utf-8");
  if ("f" === chunk.type) return chunk.dataSize < 8 ? data.readFloatBE() : data.readDoubleBE();
  for (var value = 0, i = 0; i < chunk.dataSize; i++) value |= data[i] << 8 * (chunk.dataSize - i - 1);
  return value;
};

EBMLReader.prototype._emitCluster = function(duration) {
  this.emit("cluster", this._cluster, this._timecodes[1 & ~this._clusterCount], duration);
  this._cluster = null;
};

EBMLReader.prototype._onFinish = function() {
  var v = -1, s = this._clusterOffset;
  if (s > 0) {
    var b = this._lastBlock, dur = b.data.readUInt32BE(0) / 1e6 | 0;
    this._addTimeCode(this._timecodes[1 & this._clusterCount] + dur);
    v = -dur;
    this._cluster = this._read(s, b.end);
  }
  null !== this._cluster && this._emitCluster(v);
  this.emit("cluster", null);
  this.destroy();
};

lazy(EBMLReader.prototype, "_clearDefaultDuration", function() {
  return !localStorage.vsncdd && void 0 !== window.chrome || localStorage.vscdd;
});

EBMLReader.prototype._onData = function(state, data) {
  if (DEBUG_VERBOSE && "SimpleBlock" !== data.name) {
    if ("start" === state) {
      this._conGroup++;
      console.group(data.name);
    }
    console.log("state=%s, data=%s", state, data.name, "tag" === state && [ this._getValue(data) ], data);
    if ("end" === state) {
      this._conGroup--;
      console.groupEnd();
    }
  }
  if ("start" === state) {
    if (!this._byteOffset) if ("EBML" === data.name) this._ebmlOffset = data.start; else if ("Segment" === data.name) this._segmentOffset = -1; else if (this._segmentOffset < 0) this._segmentOffset = data.start; else if ("Cluster" === data.name) {
      var segment = this._segment;
      this._segment = !1;
      delete segment.$;
      segment.offset = this._segmentOffset;
      segment.data = this._read(this._ebmlOffset, data.start);
      var dd = this._trackDefaultDuration;
      if (dd && this._clearDefaultDuration) {
        DEBUG_INFO && console.debug("Cleaning DefaultDuration...\n" + hexdump(segment.data, dd.start).slice(0, 4).join("\n"));
        var size = dd.dataSize;
        if (size > 4) console.warn("Unexpected default duration...", dd); else {
          segment.data.writeUInt32BE(629573760 + size, dd.start);
          while (size-- > 0) segment.data.writeUInt8(32, 4 + dd.start + size);
        }
      }
      var x = segment;
      if (x.Segment) {
        console.warn("left over segment", x.Segment);
        Object.assign(x, x.Segment);
        delete x.Segment;
      }
      this.emit("segment", segment);
      return;
    }
    if ("Cues" === data.name && null !== this._cluster) return this._onFinish();
    (tmp = Object.create(null)).$ = this._segment;
    this._segment[data.name] ? Array.isArray(this._segment[data.name]) ? this._segment[data.name].push(tmp) : this._segment[data.name] = [ this._segment[data.name], tmp ] : this._segment[data.name] = tmp;
    this._segment = tmp;
  } else if ("end" === state) {
    var tmp, name = data.name.toLowerCase(), C = "cluster" === name, E = C && -1 === data.end;
    this._segment = (tmp = this._segment).$;
    delete tmp.$;
    if (data.end - data.start > 0 || E) {
      if (this.listenerCount(name)) {
        var chunk = !E && this._read(data.start, data.end);
        if (C) if (E) {
          var s = this._clusterOffset;
          s >= 0 && (this._cluster = this._read(s, data.start));
          this._clusterOffset = data.start;
        } else this._cluster = chunk; else {
          if ("cues" === name) {
            (tmp = this._segment).data = chunk;
            chunk = tmp;
          }
          this.emit(name, chunk);
        }
      }
    } else console.warn("Empty master element...", data);
  } else {
    "SimpleBlock" === data.name || "Block" === data.name ? this._lastBlock = data : this._segment[data.name] = this._getValue(data);
    "Timecode" === data.name ? this._addTimeCode(this._getValue(data)) : "DefaultDuration" === data.name && (this._trackDefaultDuration = data);
  }
};

EBMLReader.prototype._addTimeCode = function(v) {
  var h = 1 & ++this._clusterCount;
  this._timecodes[h] = v;
  null !== this._cluster && this._emitCluster(this._timecodes[h] - this._timecodes[1 & ~h]);
};

EBMLReader.prototype._read = function(start, end) {
  var length = end - start, buffer = new Buffer(length), offset = start % this.$buffer.length, left = this.$buffer.length - offset;
  if (length > this.$buffer.length) this.destroy(new Error("ebml:read buffer overflow.")); else if (length > left) {
    this.$buffer.copy(buffer, 0, offset, this.$buffer.length);
    this.$buffer.copy(buffer, left, 0, length - left);
  } else this.$buffer.copy(buffer, 0, offset, offset + length);
  return buffer;
};

EBMLReader.prototype._write = function(chunk, enc, cb) {
  if (chunk.length > this.$buffer.length) return this.destroy(new Error("ebml:write buffer overflow."));
  var left = this.$buffer.length - this.$head;
  if (chunk.length > left) {
    chunk.copy(this.$buffer, this.$head, 0, left);
    chunk.copy(this.$buffer, 0, left, chunk.length);
    this.$head = chunk.length - left;
  } else {
    chunk.copy(this.$buffer, this.$head);
    this.$head += chunk.length;
  }
  try {
    this._decoder.write(chunk);
    cb();
  } catch (ex) {
    this.destroy(ex);
  }
};

function MediaSegment(muxer, offset) {
  var self = this;
  this.$etup();
  var s = muxer._initSegment;
  this.segment = s;
  this.playtime = s.playtime;
  this.timescale = s.timescale;
  this.seektime = muxer._seekTime;
  this._reader = null;
  this._async(function() {
    self._reader = muxer._createReader(offset, self, "cluster", function(cluster) {
      if (!self.destroyed) if (cluster) self.append.apply(self, arguments); else {
        DEBUG_INFO && console.debug(self + " EOS", null === cluster);
        self.push(null);
        self.destroy();
      }
    });
  });
}

createStream(MediaSegment, stream.PassThrough, function(err) {
  if (this._reader) {
    this._reader.destroy(err);
    this._reader = null;
  }
  this.end();
});

MediaSegment.prototype.hexdump = function(data) {
  var h = hexdump(data);
  console.log(h.slice(0, 12).join("\n") + "\n........\n" + h.slice(h.length - 4).join("\n"));
};

MediaSegment.prototype.append = function(cluster, timecode, duration) {
  if (duration < 0) {
    this.playtime || (this.playtime = (timecode + -duration) * this.timescale);
    duration = this.playtime / this.timescale - timecode;
    DEBUG_INFO && console.debug(this + " Last cluster, duration:", duration);
  }
  var timecodeOffset = -1, cs = cluster.readUInt32BE(4);
  if (16777216 === cs) timecodeOffset = 12; else {
    if (33554431 === cs || !this.segment.playtime) {
      DEBUG_INFO && console.warn("non-seekable cluster, 0x%s", cluster.toString("hex", 0, 32));
      this.push(this.segment.data);
    }
    timecodeOffset = 12 - Math.floor(Math.log2(cs >>> 24)) | 0;
  }
  if (timecodeOffset > 0) {
    if ((cs = cluster.readUInt16BE(timecodeOffset)) >> 8 === 191) {
      DEBUG_INFO && console.debug(this + " mkv timecode fixup (0x%s)", cluster.toString("hex", 0, timecodeOffset + 9));
      cs = cluster.readUInt16BE(timecodeOffset += 6);
    }
    if (cs >> 8 === 231 && (255 & cs) > 127) {
      cluster.timecode = timecode * this.timescale;
      cluster.duration = duration * this.timescale;
      if (-1 !== this.seektime) {
        cluster.seektime = this.seektime;
        this.seektime = -1;
      }
      var len = -65409 & cs, offset = timecodeOffset + 2;
      while (len-- > 0) cluster.writeUInt8(0, offset++);
    } else DEBUG_INFO && console.warn("Unexpected timecode offset...");
  } else if (DEBUG_INFO) {
    console.warn("Unexpected cluster data size...");
    this.hexdump(cluster);
  }
  this.push(cluster);
};

function createStream(dest, source, destroy) {
  inherits(dest, source);
  dest.prototype.$etup = function() {
    this.$iid = (Math.random() * Date.now() | 0).toString(16).slice(-6);
    this.destroyed = !1;
    source.call(this);
    if (DEBUG_VERBOSE) {
      var _emit = this.emit;
      this.emit = function(event) {
        "data" === event && !DEBUG_ALL || console.warn(this + ".emit(%s)", event, arguments, [ this ]);
        return _emit.apply(this, arguments);
      };
    }
  };
  dest.prototype._async = function(cb) {
    var self = this;
    queueMicrotask(function() {
      self.destroyed || cb.call(self);
    });
  };
  destroy = destroy && tryCatch(destroy);
  dest.prototype.destroy = function(err) {
    DEBUG_INFO && console[err ? "error" : "debug"](this + ".destroy", this.destroyed, [ this ], err);
    if (!this.destroyed) {
      this.destroyed = !0;
      destroy && destroy.call(this, err);
      err && this.emit("error", err);
      this.emit("close");
    }
  };
  dest.prototype.toString = function() {
    return this.constructor.name + "[$" + this.$iid + "]";
  };
}

function hexdump(buffer, offset, length) {
  offset = offset || 0;
  length = length || buffer.length;
  for (var out = [], row = "", i = 0; i < length; i += 16) {
    row = ("0000000" + offset.toString(16).toUpperCase()).slice(-8) + ":  ";
    for (var n = Math.min(16, length - offset), string = "", j = 0; j < 16; ++j) {
      !j || j % 4 || (row += " ");
      if (j < n) {
        var value = buffer.readUInt8(offset);
        string += value > 31 && value < 127 ? String.fromCharCode(value) : ".";
        row += ("0" + value.toString(16).toUpperCase()).slice(-2);
        offset++;
      } else {
        row += "  ";
        string += " ";
      }
    }
    out.push(row + "  " + string);
  }
  return out;
}
},{"/bundle/utils":4,"buffer":10,"ebml/lib/ebml/decoder":11,"eventemitter3":15,"readable-stream":41}],6:[function(require,module,exports){
var bs = require("binary-search"), EventEmitter = require("eventemitter3").EventEmitter, inherits = require("/bundle/utils").inherit, mp4 = require("mp4-stream"), Box = require("mp4-box-encoding"), RangeSliceStream = require("range-slice-stream"), Buffer = require("buffer").Buffer, locale = require("./bundle/locale"), FIND_MOOV_SEEK_SIZE = 4096, SILENT_PLAYBACK = parseInt(localStorage.vsna);

module.exports = MP4Remuxer;

function MP4Remuxer(file, opts) {
  EventEmitter.call(this);
  this._tracks = [];
  this._file = file;
  this._decoder = null;
  this._videoOnly = opts && opts.videoOnly || SILENT_PLAYBACK;
  this._bogusAudioTracks = opts && opts.bat || Object.create(null);
  vsNT(this._findMoov.bind(this, 0));
}

inherits(MP4Remuxer, EventEmitter);

MP4Remuxer.prototype._parseMoov = function() {
  var moov = this._moov, sidx = this._sidx;
  if (moov) {
    this._moov = this._sidx = !1;
    this._decoder && this._decoder.destroy();
    try {
      if (sidx) for (var i = moov.traks.length; i--; ) {
        var trak = moov.traks[i];
        if (trak.tkhd.trackId === sidx.referenceId) {
          trak.sidx = sidx;
          break;
        }
      }
      this._processMoov(moov);
    } catch (err) {
      this.emit("error", err);
    }
  }
};

MP4Remuxer.prototype._findMoov = function(offset) {
  var self = this, file = this._file, boxes = {
    moov: 1,
    sidx: 1
  }, lastbox = "sidx";
  if (!(d > 11)) {
    lastbox = "moov";
    delete boxes.sidx;
  }
  if (file.filesize >= 0 && offset >= file.filesize) return self._moov ? self._parseMoov() : self.emit("error", RangeError("Offset out of bound."));
  var fileStream = file.createReadStream({
    start: offset
  });
  self._decoder = mp4.decode();
  fileStream.pipe(self._decoder);
  var toSkip = 0, boxHandler = function(headers) {
    function destroy() {
      fileStream.destroy();
      self._decoder.removeListener("box", boxHandler);
      self._decoder.destroy();
    }
    function findNextBox() {
      if (self["_" + lastbox]) {
        destroy();
        self._parseMoov();
      } else if (headers.length < FIND_MOOV_SEEK_SIZE) {
        toSkip += headers.length;
        self._decoder.ignore();
      } else {
        destroy();
        self._findMoov(offset + (toSkip += headers.length));
      }
    }
    d && console.debug("box", headers.type, headers.length, headers, offset);
    boxes[headers.type] ? self._decoder.decode(function(data) {
      self["_" + headers.type] = data;
      findNextBox();
    }) : findNextBox();
  };
  self._decoder.on("box", boxHandler);
};

function RunLengthIndex(entries, countName) {
  this._entries = entries;
  this._countName = countName || "count";
  this._index = 0;
  this._offset = 0;
  this.value = this._entries[0] || !1;
}

RunLengthIndex.prototype.inc = function() {
  this._offset++;
  if (this._offset >= this._entries[this._index][this._countName]) {
    this._index++;
    this._offset = 0;
  }
  this.value = this._entries[this._index] || !1;
};

MP4Remuxer.prototype._processTracks = function(traks) {
  function validateAudioTrack(trk) {
    if (!trk) return !1;
    var mime = trk.mime;
    if (!MediaSource.isTypeSupported(mime)) {
      if ("mp3" !== trk.codec || !MediaSource.isTypeSupported(mime = "audio/mpeg")) {
        self._hasUnsupportedAudio = trk.codec;
        return !1;
      }
      trk.mime = mime;
    }
    if (self._hasVideo && hevc[self._hasVideo.type]) {
      mime = self._hasVideo.mime.replace(/"$/, ", " + trk.codec + '"');
      if ("mp4a.a9" === trk.codec || !MediaSource.isTypeSupported(mime)) {
        d && console.warn("[hevc] unsupported audio track.", mime);
        self._hasUnsupportedAudio = self._hasVideo.type + ":" + trk.codec;
        return !1;
      }
    }
    return trk;
  }
  for (var mime, codec, self = this, audio = [], hevc = Object.assign(Object.create(null), {
    hvc1: 1,
    hev1: 1
  }), mp3a = Object.assign(Object.create(null), {
    "mp4a.6b": 1,
    "mp4a.69": 1
  }), vide = Object.assign(Object.create(null), {
    avc1: 1,
    av01: 1,
    vp09: 1
  }, hevc), swap = Object.assign(Object.create(null), {
    fLaC: "flac",
    Opus: "opus",
    ".mp3": "mp3"
  }), i = 0; i < traks.length; i++) {
    var trak = traks[i], mdia = trak.mdia || !1, stsd = trak.mdia.minf.stbl.stsd.entries[0], lang = Object(mdia.mdhd).language, type = Object(mdia.hdlr).handlerType;
    if ("vide" === type && vide[stsd.type]) {
      codec = stsd.type;
      stsd.avcC ? codec += "." + stsd.avcC.mimeCodec : stsd.av1C ? codec = stsd.av1C.mimeCodec || codec : stsd.vpcC ? codec = stsd.vpcC.mimeCodec || codec : stsd.hvcC && (codec += stsd.hvcC.mimeCodec);
      mime = 'video/mp4; codecs="' + codec + '"';
      d && console.debug("Track%d: %s %s", i, locale.decodeMP4LangCode(lang), mime);
      self._hasVideo || (self._hasVideo = {
        type: stsd.type,
        codec: codec,
        mime: mime,
        trak: trak,
        lang: lang,
        idx: i
      });
    } else if ("soun" === type && !self._videoOnly && !self._bogusAudioTracks[i]) {
      if ("mp4a" === (codec = stsd.type)) {
        codec = "mp4a";
        stsd.esds && stsd.esds.mimeCodec && (codec += "." + stsd.esds.mimeCodec);
        mp3a[codec] && (codec = "mp3");
      }
      mime = 'audio/mp4; codecs="' + (swap[codec] || codec) + '"';
      d && console.debug("Track%d: %s %s", i, locale.decodeMP4LangCode(lang), mime);
      audio.push({
        type: stsd.type,
        codec: codec,
        mime: mime,
        trak: trak,
        lang: lang,
        idx: i
      });
    }
  }
  if (audio.length < 2) self._hasAudio = validateAudioTrack(audio[0]); else {
    for (var eng, def, und, j = 0; j < audio.length; ++j) {
      var trk = validateAudioTrack(audio[j]);
      if (trk) {
        var lng = locale.decodeMP4LangCode(trk.lang);
        eng || "eng" !== lng || (eng = trk);
        !def && locale.bcp47match(lng) && (def = trk);
        und = und || trk;
      }
    }
    self._hasAudio = def || eng || und || !1;
  }
};

MP4Remuxer.prototype._processMoov = function(moov) {
  var traks = moov.traks || !1;
  if (moov.otherBoxes) for (var b = moov.otherBoxes.length; b--; ) if (moov.otherBoxes[b] instanceof Error) {
    this.emit("error", moov.otherBoxes[b]);
    return;
  }
  this._tracks = [];
  this._hasVideo = !1;
  this._hasAudio = !1;
  this._processTracks(traks);
  d && console.debug("video%s:%s, audio%s:%s", this._hasVideo.idx, this._hasVideo.codec, 0 | this._hasAudio.idx, this._hasAudio.codec || "N/A");
  for (var i = 0; i < traks.length; i++) {
    var mime, trak = traks[i], stbl = trak.mdia.minf.stbl, stco = stbl.stco || stbl.co64;
    d && console.debug("handler=%s, type=%s, trak:", trak.mdia.hdlr.handlerType, stbl.stsd.entries[0].type, trak);
    if (this._hasVideo && this._hasVideo.trak === trak) {
      mime = this._hasVideo.mime;
      this._hasVideo = this._hasVideo.codec;
    } else {
      if (!this._hasAudio || this._hasAudio.trak !== trak) continue;
      mime = this._hasAudio.mime;
      this._chosenAudioTrack = this._hasAudio.idx;
      this._hasAudio = this._hasAudio.codec;
    }
    var currChunkEntry, samples = [], sample = 0, sampleInChunk = 0, chunk = 0, offsetInChunk = 0, sampleToChunkIndex = 0, dts = 0, decodingTimeEntry = new RunLengthIndex(stbl.stts.entries), presentationOffsetEntry = null;
    stbl.ctts && (presentationOffsetEntry = new RunLengthIndex(stbl.ctts.entries));
    var syncSampleIndex = 0;
    if (decodingTimeEntry.value) {
      while (1) {
        currChunkEntry = stbl.stsc.entries[sampleToChunkIndex];
        var size = stbl.stsz.sample_size || stbl.stsz.entries[sample], duration = decodingTimeEntry.value && decodingTimeEntry.value.duration || 0, sync = !0;
        stbl.stss && (sync = stbl.stss.entries[syncSampleIndex] === sample + 1);
        samples.push({
          size: size,
          duration: duration,
          dts: dts,
          presentationOffset: presentationOffsetEntry && presentationOffsetEntry.value.compositionOffset || 0,
          sync: sync,
          offset: offsetInChunk + stco.entries[chunk]
        });
        if (++sample >= stbl.stsz.sample_count) break;
        offsetInChunk += size;
        if (++sampleInChunk >= currChunkEntry.samplesPerChunk) {
          offsetInChunk = sampleInChunk = 0;
          chunk++;
          var nextChunkEntry = stbl.stsc.entries[sampleToChunkIndex + 1];
          nextChunkEntry && chunk + 1 >= nextChunkEntry.firstChunk && sampleToChunkIndex++;
        }
        dts += duration;
        decodingTimeEntry.inc();
        presentationOffsetEntry && presentationOffsetEntry.inc();
        sync && syncSampleIndex++;
      }
      trak.mdia.mdhd.duration = 0;
      trak.tkhd.duration = 0;
      var defaultSampleDescriptionIndex = currChunkEntry && currChunkEntry.sampleDescriptionId || 0, trackMoov = {
        type: "moov",
        mvhd: moov.mvhd,
        traks: [ {
          tkhd: trak.tkhd,
          mdia: {
            mdhd: trak.mdia.mdhd,
            hdlr: trak.mdia.hdlr,
            elng: trak.mdia.elng,
            minf: {
              vmhd: trak.mdia.minf.vmhd,
              smhd: trak.mdia.minf.smhd,
              dinf: trak.mdia.minf.dinf,
              stbl: {
                stsd: stbl.stsd,
                stts: empty(),
                ctts: empty(),
                stsc: empty(),
                stsz: empty(),
                stco: empty(),
                stss: empty()
              }
            }
          }
        } ],
        mvex: {
          mehd: {
            fragmentDuration: moov.mvhd.duration
          },
          trexs: [ {
            trackId: trak.tkhd.trackId,
            defaultSampleDescriptionIndex: defaultSampleDescriptionIndex,
            defaultSampleDuration: 0,
            defaultSampleSize: 0,
            defaultSampleFlags: 0
          } ]
        }
      };
      this._tracks.push({
        fragmentSequence: 1,
        trackId: trak.tkhd.trackId,
        timeScale: trak.mdia.mdhd.timeScale,
        samples: samples,
        currSample: null,
        currTime: null,
        moov: trackMoov,
        mime: mime
      });
    } else console.warn("No 'stts' entries for trak %s...", i, trak);
  }
  if (0 !== this._tracks.length) {
    this._ftyp = {
      type: "ftyp",
      brand: "iso5",
      brandVersion: moov.mvhd.duration = 0,
      compatibleBrands: [ "iso5" ]
    };
    var ftypBuf = Box.encode(this._ftyp), data = this._tracks.map(function(track) {
      var moovBuf = Box.encode(track.moov);
      return {
        mime: track.mime,
        init: Buffer.concat([ ftypBuf, moovBuf ])
      };
    });
    this.emit("ready", data);
  } else this.emit("error", new Error("no playable tracks"));
};

function empty() {
  return {
    version: 0,
    flags: 0,
    entries: []
  };
}

MP4Remuxer.prototype._writeFragment = function(fragment, i) {
  function wrap(cb) {
    return function(err) {
      err ? self.emit("error", err) : outStream.destroyed || inStream.destroyed ? d > 1 && console.debug("writeFragment stream destroyed", outStream.destroyed, inStream.destroyed) : cb();
    };
  }
  var self = this, track = self._tracks[i], inStream = track.inStream, outStream = track.outStream, parser = wrap(function() {
    if (!(fragment = self._generateFragment(i))) return outStream.finalize();
    writeFragment();
  }), boxer = wrap(function() {
    var slicedStream = inStream.slice(fragment.ranges), mediaDataStream = outStream.mediaData(fragment.length, parser);
    slicedStream.pipe(mediaDataStream);
  }), writeFragment = function() {
    outStream.destroyed || outStream.box(fragment.moof, boxer);
  };
  writeFragment();
};

MP4Remuxer.prototype.seek = function(time) {
  var self = this;
  if (!self._tracks) throw new Error("Not ready yet; wait for 'ready' event");
  if (self._fileStream) {
    self._fileStream.destroy();
    self._fileStream = null;
  }
  var highWaterMark = 0, startOffset = Math.pow(2, 53);
  self._tracks.forEach(function(track, i) {
    track.fragment = self._generateFragment(i, time);
    if (track.fragment) {
      var rangeStart = track.fragment.ranges[0].start;
      startOffset = Math.min(startOffset, rangeStart);
      highWaterMark = highWaterMark ? Math.abs(highWaterMark - rangeStart) : rangeStart;
    }
  });
  if (d) {
    console.debug("MP4Remuxer: Measured highWaterMark to need %s bytes.", highWaterMark);
    highWaterMark > 1e7 && console.warn("^ excessive highWaterMark detected...");
  }
  highWaterMark = Math.min((highWaterMark + 16777216 & -16777216) >>> 0, Math.pow(2, 26) * self._tracks.length);
  return self._tracks.map(function(track, i) {
    track.outStream && track.outStream.destroy();
    if (track.inStream) {
      track.inStream.destroy();
      track.inStream = null;
    }
    track.outStream = mp4.encode();
    if (track.fragment) {
      d && console.debug("MP4Remuxer.seek(%s)", time, track, startOffset);
      track.inStream = new RangeSliceStream(startOffset, {
        highWaterMark: highWaterMark
      });
      self._fileStream || (self._fileStream = self._file.createReadStream({
        start: startOffset
      }));
      self._fileStream.pipe(track.inStream);
      self._writeFragment(track.fragment, i);
    } else track.outStream.finalize();
    return track.outStream;
  });
};

MP4Remuxer.prototype._findSampleBefore = function(trackId, time) {
  var track = this._tracks[trackId], scaledTime = Math.floor(track.timeScale * time), sample = bs(track.samples, scaledTime, function(sample, t) {
    return sample.dts + sample.presentationOffset - t;
  });
  -1 === sample ? sample = 0 : sample < 0 && (sample = -sample - 2);
  if (sample < 1) return 0;
  var sampleIdx = sample;
  while (!track.samples[sample].sync) if (--sample < 0) return sampleIdx;
  return sample;
};

var MIN_FRAGMENT_DURATION = 1;

MP4Remuxer.prototype._generateFragment = function(track, time) {
  var currTrack = this._tracks[track], firstSample = void 0 !== time ? this._findSampleBefore(track, time) : currTrack.currSample;
  if (firstSample >= currTrack.samples.length) return null;
  for (var startDts = currTrack.samples[firstSample].dts, totalLen = 0, ranges = [], currSample = firstSample; currSample < currTrack.samples.length; currSample++) {
    var sample = currTrack.samples[currSample];
    if (sample.sync && sample.dts - startDts >= currTrack.timeScale * MIN_FRAGMENT_DURATION) break;
    totalLen += sample.size;
    var currRange = ranges.length - 1;
    currRange < 0 || ranges[currRange].end !== sample.offset ? ranges.push({
      start: sample.offset,
      end: sample.offset + sample.size
    }) : ranges[currRange].end += sample.size;
  }
  return {
    moof: this._generateMoof(track, firstSample, currTrack.currSample = currSample),
    ranges: ranges,
    length: totalLen
  };
};

MP4Remuxer.prototype._generateMoof = function(track, firstSample, lastSample) {
  for (var currTrack = this._tracks[track], entries = [], trunVersion = 0, j = firstSample; j < lastSample; j++) {
    var currSample = currTrack.samples[j];
    currSample.presentationOffset < 0 && (trunVersion = 1);
    entries.push({
      sampleDuration: currSample.duration,
      sampleSize: currSample.size,
      sampleFlags: currSample.sync ? 33554432 : 16842752,
      sampleCompositionTimeOffset: currSample.presentationOffset
    });
  }
  var moof = {
    type: "moof",
    mfhd: {
      sequenceNumber: currTrack.fragmentSequence++
    },
    trafs: [ {
      tfhd: {
        flags: 131072,
        trackId: currTrack.trackId
      },
      tfdt: {
        baseMediaDecodeTime: currTrack.samples[firstSample].dts
      },
      trun: {
        flags: 3841,
        dataOffset: 8,
        entries: entries,
        version: trunVersion
      }
    } ]
  };
  moof.trafs[0].trun.dataOffset += Box.encodingLength(moof);
  return moof;
};

var UINT32_MAX = Math.pow(2, 32);

Box.boxes.fullBoxes.co64 = !0;

Box.boxes.co64 = Box.boxes.co64 || {};

Box.boxes.co64.decode = function(buf, offset) {
  for (var num = (buf = buf.slice(offset)).readUInt32BE(0), entries = new Array(num), i = 0; i < num; i++) {
    var pos = 8 * i + 4, hi = buf.readUInt32BE(pos), lo = buf.readUInt32BE(4 + pos);
    entries[i] = hi * UINT32_MAX + lo;
  }
  return {
    entries: entries
  };
};

Box.boxes.av1C = {};

Box.boxes.av1C.encode = function _(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(box.buffer.length);
  box.buffer.copy(buf);
  _.bytes = box.buffer.length;
};

Box.boxes.av1C.decode = function(buf, offset, end) {
  function readUint8() {
    return buf.readUInt8(p++);
  }
  var p = 0, r = Object.create(null);
  buf = buf.slice(offset, end);
  var tmp = readUint8();
  this.version = 127 & tmp;
  if (tmp >> 7 & !1) console.warn("Invalid av1C marker."); else if (1 !== this.version) console.warn("Unsupported av1C version %d.", this.version); else {
    tmp = readUint8();
    r.seq_profile = tmp >> 5 & 7;
    r.seq_level_idx_0 = 31 & tmp;
    tmp = readUint8();
    r.seq_tier_0 = tmp >> 7 & 1;
    r.high_bitdepth = tmp >> 6 & 1;
    r.twelve_bit = tmp >> 5 & 1;
    r.monochrome = tmp >> 4 & 1;
    r.chroma_subsampling_x = tmp >> 3 & 1;
    r.chroma_subsampling_y = tmp >> 2 & 1;
    r.chroma_sample_position = 3 & tmp;
    tmp = readUint8();
    r.reserved = tmp >> 5 & 7;
    r.buffer = Buffer.from(buf);
    (tmp = r.high_bitdepth) < 10 && (tmp = 8);
    r.mimeCodec = [ "av01", r.seq_profile, ("0" + r.seq_level_idx_0).slice(-2) + (r.seq_tier_0 ? "H" : "M"), ("0" + tmp).slice(-2) ].join(".");
  }
  return r;
};

Box.boxes.av1C.encodingLength = function(box) {
  return box.buffer.length;
};

Box.boxes.av01 = Box.boxes.VisualSampleEntry;

Box.boxes.vpcC = {};

Box.boxes.vpcC.encode = function _(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(box.buffer.length);
  box.buffer.copy(buf);
  _.bytes = box.buffer.length;
};

Box.boxes.vpcC.decode = function(buf, offset, end) {
  function readUint8() {
    return buf.readUInt8(p++);
  }
  var p = 0, r = Object.create(null);
  buf = buf.slice(offset, end);
  var tmp = readUint8();
  this.version = 127 & tmp;
  if (1 !== this.version) console.warn("Unsupported/deprecated vpcC version %d.", this.version); else {
    p += 3;
    r.profile = readUint8();
    r.level = readUint8();
    tmp = readUint8();
    r.bitDepth = tmp >> 4;
    r.chromaSubsampling = tmp >> 1 & 7;
    r.videoFullRangeFlag = 1 & tmp;
    r.buffer = Buffer.from(buf);
    r.mimeCodec = [ "vp09", ("0" + r.profile).slice(-2), ("0" + r.level).slice(-2), ("0" + r.bitDepth).slice(-2) ].join(".");
  }
  return r;
};

Box.boxes.vpcC.encodingLength = function(box) {
  return box.buffer.length;
};

Box.boxes.vp09 = Box.boxes.VisualSampleEntry;

Box.boxes.hvcC = {};

Box.boxes.hvcC.encode = function _(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(box.buffer.length);
  box.buffer.copy(buf);
  _.bytes = box.buffer.length;
};

Box.boxes.hvcC.decode = function(buf, offset, end) {
  function readUint8() {
    return buf.readUInt8(p++);
  }
  function readUint16() {
    var v = buf.readUInt16BE(p);
    p += 2;
    return v;
  }
  var p = 0, r = Object.create(null);
  buf = buf.slice(offset, end);
  var tmp = readUint8();
  this.version = 255 & tmp;
  r.configurationVersion = this.version;
  tmp = readUint8();
  r.profile_space = tmp >> 6;
  r.tier_flag = (32 & tmp) >> 5;
  r.profile_idc = 31 & tmp;
  r.profile_compatibility_indications = function() {
    var v = buf.readUInt32BE(p);
    p += 4;
    return v;
  }();
  r.constraint_indicator_flags = function() {
    for (var out = new Uint8Array(6), i = 0; i < 6; i++) out[i] = readUint8();
    return out;
  }();
  r.level_idc = readUint8();
  r.min_spatial_segmentation_idc = 4095 & readUint16();
  r.parallelismType = 3 & readUint8();
  r.chromaFormat = 3 & readUint8();
  r.bitDepthLumaMinus8 = 7 & readUint8();
  r.bitDepthChromaMinus8 = 7 & readUint8();
  r.avgFrameRate = readUint16();
  tmp = readUint8();
  r.constantFrameRate = tmp >> 6;
  r.numTemporalLayers = (13 & tmp) >> 3;
  r.temporalIdNested = (4 & tmp) >> 2;
  r.lengthSizeMinusOne = 3 & tmp;
  r.buffer = Buffer.from(buf);
  var mime = ".";
  r.profile_space && (mime += String.fromCharCode(64 + r.profile_space));
  mime += r.profile_idc + ".";
  var j = tmp = 0, cpl = r.profile_compatibility_indications;
  while (1) {
    tmp = 1 & cpl;
    if (++j > 30) break;
    tmp <<= 1;
    cpl >>= 1;
  }
  mime += tmp.toString(16) + "." + (r.tier_flag ? "H" : "L") + r.level_idc;
  tmp = "";
  cpl = r.constraint_indicator_flags;
  for (j = 5; j >= 0; j--) (cpl[j] || tmp) && (tmp = "." + ("0" + Number(cpl[j]).toString(16)).slice(-2) + tmp);
  r.mimeCodec = mime + tmp;
  return r;
};

Box.boxes.hvcC.encodingLength = function(box) {
  return box.buffer.length;
};

Box.boxes.hev1 = Box.boxes.VisualSampleEntry;

Box.boxes.hvc1 = Box.boxes.VisualSampleEntry;

Box.boxes.fullBoxes.sidx = !0;

Box.boxes.sidx = {};

Box.boxes.sidx.decode = function(buf, offset) {
  function readUInt16() {
    var v = buf.readUInt16BE(p);
    p += 2;
    return v;
  }
  function readUInt32() {
    var v = buf.readUInt32BE(p);
    p += 4;
    return v;
  }
  function readUInt64() {
    var hi = readUInt32(), lo = readUInt32();
    return hi * UINT32_MAX + lo;
  }
  var time, r = Object.create(null), p = offset + 4;
  r.referenceId = readUInt32();
  r.timescale = readUInt32();
  if (0 === this.version) {
    r.earliestPresentationTime = readUInt32();
    r.firstOffset = readUInt32();
  } else {
    r.earliestPresentationTime = readUInt64();
    r.firstOffset = readUInt64();
  }
  readUInt16();
  r.count = readUInt16();
  r.entries = new Array(r.count);
  time = r.earliestPresentationTime;
  offset = this.length + r.firstOffset;
  for (var i = 0; i < r.count; i++) {
    var e = r.entries[i] = Object.create(null), t = readUInt32();
    e.type = t >>> 31 & 1;
    e.size = 2147483647 & t;
    e.duration = readUInt32();
    t = readUInt32();
    e.sap = t >>> 31 & 1;
    e.sapType = t >>> 28 & 7;
    e.sapDelta = 268435455 & t;
    e.byteOffset = [ offset, offset + e.size - 1 ];
    e.timeOffset = [ time, time / r.timescale, e.duration / r.timescale ];
    offset += e.size;
    time += e.duration;
  }
  return r;
};

Box.boxes.AudioSampleEntry.decode = function(buf, offset, end) {
  var length = end - offset, box = {
    dataReferenceIndex: (buf = buf.slice(offset, end)).readUInt16BE(6),
    channelCount: buf.readUInt16BE(16),
    sampleSize: buf.readUInt16BE(18),
    sampleRate: buf.readUInt32BE(24),
    children: []
  }, ptr = 28;
  while (length - ptr >= 8) {
    var child = Box.decode(buf, ptr, length);
    if (!child.length) break;
    box.children.push(child);
    ptr += (box[child.type] = child).length;
  }
  return box;
};

Box.boxes.stsz.decode = function(buf, offset) {
  var size = (buf = buf.slice(offset)).readUInt32BE(0), num = buf.readUInt32BE(4), entries = [];
  if (0 === size) {
    entries = new Array(num);
    for (var i = 0; i < num; i++) entries[i] = buf.readUInt32BE(4 * i + 8);
  }
  return {
    sample_size: size,
    sample_count: num,
    entries: entries
  };
};
},{"./bundle/locale":2,"/bundle/utils":4,"binary-search":9,"buffer":10,"eventemitter3":15,"mp4-box-encoding":20,"mp4-stream":23,"range-slice-stream":28}],7:[function(require,module,exports){
var AudioContext = window.AudioContext || window.webkitAudioContext, OfflineAudioContext = window.OfflineAudioContext || window.webkitOfflineAudioContext, BaseAudioContext = window.BaseAudioContext || OfflineAudioContext && Object.getPrototypeOf(OfflineAudioContext);

module.exports = "function" === typeof BaseAudioContext && BaseAudioContext.prototype ? BaseAudioContext : AudioContext;
},{}],8:[function(require,module,exports){
"use strict";

exports.byteLength = byteLength;

exports.toByteArray = toByteArray;

exports.fromByteArray = fromByteArray;

for (var lookup = [], revLookup = [], Arr = "undefined" !== typeof Uint8Array ? Uint8Array : Array, code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i];
  revLookup[code.charCodeAt(i)] = i;
}

revLookup["-".charCodeAt(0)] = 62;

revLookup["_".charCodeAt(0)] = 63;

function getLens(b64) {
  var len = b64.length;
  if (len % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4");
  var validLen = b64.indexOf("=");
  -1 === validLen && (validLen = len);
  return [ validLen, validLen === len ? 0 : 4 - validLen % 4 ];
}

function byteLength(b64) {
  var lens = getLens(b64), placeHoldersLen = lens[1];
  return 3 * (lens[0] + placeHoldersLen) / 4 - placeHoldersLen;
}

function _byteLength(b64, validLen, placeHoldersLen) {
  return 3 * (validLen + placeHoldersLen) / 4 - placeHoldersLen;
}

function toByteArray(b64) {
  for (var tmp, lens = getLens(b64), validLen = lens[0], placeHoldersLen = lens[1], arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)), curByte = 0, len = placeHoldersLen > 0 ? validLen - 4 : validLen, i = 0; i < len; i += 4) {
    tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
    arr[curByte++] = tmp >> 16 & 255;
    arr[curByte++] = tmp >> 8 & 255;
    arr[curByte++] = 255 & tmp;
  }
  if (2 === placeHoldersLen) {
    tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
    arr[curByte++] = 255 & tmp;
  }
  if (1 === placeHoldersLen) {
    tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
    arr[curByte++] = tmp >> 8 & 255;
    arr[curByte++] = 255 & tmp;
  }
  return arr;
}

function tripletToBase64(num) {
  return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[63 & num];
}

function encodeChunk(uint8, start, end) {
  for (var output = [], i = start; i < end; i += 3) output.push(tripletToBase64((uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (255 & uint8[i + 2])));
  return output.join("");
}

function fromByteArray(uint8) {
  for (var tmp, len = uint8.length, extraBytes = len % 3, parts = [], i = 0, len2 = len - extraBytes; i < len2; i += 16383) parts.push(encodeChunk(uint8, i, i + 16383 > len2 ? len2 : i + 16383));
  1 === extraBytes ? parts.push(lookup[(tmp = uint8[len - 1]) >> 2] + lookup[tmp << 4 & 63] + "==") : 2 === extraBytes && parts.push(lookup[(tmp = (uint8[len - 2] << 8) + uint8[len - 1]) >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=");
  return parts.join("");
}
},{}],9:[function(require,module,exports){
module.exports = function(haystack, needle, comparator, low, high) {
  var mid, cmp;
  if (void 0 === low) low = 0; else if ((low |= 0) < 0 || low >= haystack.length) throw new RangeError("invalid lower bound");
  if (void 0 === high) high = haystack.length - 1; else if ((high |= 0) < low || high >= haystack.length) throw new RangeError("invalid upper bound");
  while (low <= high) if ((cmp = +comparator(haystack[mid = low + (high - low >>> 1)], needle, mid, haystack)) < 0) low = mid + 1; else {
    if (!(cmp > 0)) return mid;
    high = mid - 1;
  }
  return ~low;
};
},{}],10:[function(require,module,exports){
var Buffer = function(a, b, c) {
  return "number" == typeof a ? allocUnsafe(a) : from(a, b, c);
}, base64 = require("base64-js"), ieee754 = require("ieee754");

/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */ exports.Buffer = Buffer;

exports.SlowBuffer = SlowBuffer;

exports.INSPECT_MAX_BYTES = 50;

var K_MAX_LENGTH = 2147483647;

exports.kMaxLength = K_MAX_LENGTH;

Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();

Buffer.TYPED_ARRAY_SUPPORT || "undefined" === typeof console || "function" !== typeof console.error || console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");

function typedArraySupport() {
  try {
    var arr = new Uint8Array(1);
    arr.__proto__ = {
      __proto__: Uint8Array.prototype,
      foo: function() {
        return 42;
      }
    };
    return 42 === arr.foo();
  } catch (e) {
    return !1;
  }
}

Object.defineProperty(Buffer.prototype, "parent", {
  enumerable: !0,
  get: function() {
    if (Buffer.isBuffer(this)) return this.buffer;
  }
});

Object.defineProperty(Buffer.prototype, "offset", {
  enumerable: !0,
  get: function() {
    if (Buffer.isBuffer(this)) return this.byteOffset;
  }
});

function createBuffer(length) {
  if (length > K_MAX_LENGTH) throw new RangeError('The value "' + length + '" is invalid for option "size"');
  var buf = new Uint8Array(length);
  Object.setPrototypeOf(buf, Buffer.prototype);
  return buf;
}

function Buffer(arg, encodingOrOffset, length) {
  if ("number" !== typeof arg) return from(arg, encodingOrOffset, length);
  if ("string" === typeof encodingOrOffset) throw new TypeError('The "string" argument must be of type string. Received type number');
  return allocUnsafe(arg);
}

Buffer.poolSize = 8192;

function from(value, encodingOrOffset, length) {
  if ("string" === typeof value) return fromString(value, encodingOrOffset);
  if (ArrayBuffer.isView(value)) return fromArrayView(value);
  if (null == value) throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
  if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) return fromArrayBuffer(value, encodingOrOffset, length);
  if ("number" === typeof value) throw new TypeError('The "value" argument must not be of type number. Received type number');
  var valueOf = value.valueOf && value.valueOf();
  if (null != valueOf && valueOf !== value) return Buffer.from(valueOf, encodingOrOffset, length);
  var b = fromObject(value);
  if (b) return b;
  if ("undefined" !== typeof Symbol && null != Symbol.toPrimitive && "function" === typeof value[Symbol.toPrimitive]) return Buffer.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
  throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
}

Buffer.from = function(value, encodingOrOffset, length) {
  return from(value, encodingOrOffset, length);
};

Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);

Object.setPrototypeOf(Buffer, Uint8Array);

function alloc(size, fill, encoding) {
  return size <= 0 || void 0 === fill ? createBuffer(size) : "string" === typeof encoding ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
}

Buffer.alloc = function(size, fill, encoding) {
  return alloc(size, fill, encoding);
};

function allocUnsafe(size) {
  return createBuffer(size < 0 ? 0 : 0 | size);
}

Buffer.allocUnsafe = function(size) {
  return allocUnsafe(size);
};

Buffer.allocUnsafeSlow = function(size) {
  return allocUnsafe(size);
};

function fromString(string, encoding) {
  "string" === typeof encoding && "" !== encoding || (encoding = "utf8");
  if (!Buffer.isEncoding(encoding)) throw new TypeError("Unknown encoding: " + encoding);
  var length = 0 | byteLength(string, encoding), buf = createBuffer(length), actual = buf.write(string, encoding);
  actual !== length && (buf = buf.slice(0, actual));
  return buf;
}

function fromArrayLike(array) {
  for (var length = array.length < 0 ? 0 : 0 | array.length, buf = createBuffer(length), i = 0; i < length; i += 1) buf[i] = 255 & array[i];
  return buf;
}

function fromArrayBuffer(array, byteOffset, length) {
  if (byteOffset < 0 || array.byteLength < byteOffset) throw new RangeError('"offset" is outside of buffer bounds');
  if (array.byteLength < byteOffset + (length || 0)) throw new RangeError('"length" is outside of buffer bounds');
  var buf = void 0 === byteOffset && void 0 === length ? new Uint8Array(array) : void 0 === length ? new Uint8Array(array, byteOffset) : new Uint8Array(array, byteOffset, length);
  Object.setPrototypeOf(buf, Buffer.prototype);
  return buf;
}

function fromObject(obj) {
  if (Buffer.isBuffer(obj)) {
    var len = 0 | obj.length, buf = createBuffer(len);
    if (0 === buf.length) return buf;
    obj.copy(buf, 0, 0, len);
    return buf;
  }
  return void 0 !== obj.length ? "number" !== typeof obj.length || numberIsNaN(obj.length) ? createBuffer(0) : fromArrayLike(obj) : "Buffer" === obj.type && Array.isArray(obj.data) ? fromArrayLike(obj.data) : void 0;
}

function SlowBuffer(length) {
  +length != length && (length = 0);
  return Buffer.alloc(+length);
}

Buffer.isBuffer = function(b) {
  return null != b && !0 === b._isBuffer && b !== Buffer.prototype;
};

Buffer.compare = function(a, b) {
  isInstance(a, Uint8Array) && (a = Buffer.from(a, a.offset, a.byteLength));
  isInstance(b, Uint8Array) && (b = Buffer.from(b, b.offset, b.byteLength));
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
  if (a === b) return 0;
  for (var x = a.length, y = b.length, i = 0, len = Math.min(x, y); i < len; ++i) if (a[i] !== b[i]) {
    x = a[i];
    y = b[i];
    break;
  }
  return x < y ? -1 : y < x ? 1 : 0;
};

Buffer.isEncoding = function(encoding) {
  switch (String(encoding).toLowerCase()) {
   case "hex":
   case "utf8":
   case "utf-8":
   case "ascii":
   case "latin1":
   case "binary":
   case "base64":
   case "ucs2":
   case "ucs-2":
   case "utf16le":
   case "utf-16le":
    return !0;

   default:
    return !1;
  }
};

Buffer.concat = function(list, length) {
  if (!Array.isArray(list)) throw new TypeError('"list" argument must be an Array of Buffers');
  if (0 === list.length) return Buffer.alloc(0);
  if (void 0 === length) for (i = length = 0; i < list.length; ++i) length += list[i].length;
  for (var buffer = Buffer.allocUnsafe(length), pos = 0, i = 0; i < list.length; ++i) {
    var buf = list[i];
    if (isInstance(buf, Uint8Array)) {
      if (pos + buf.length > buffer.length) {
        Buffer.isBuffer(buf) || (buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength));
        buf.copy(buffer, pos);
      } else Uint8Array.prototype.set.call(buffer, buf, pos);
      pos += buf.length;
    } else {
      if (!Buffer.isBuffer(buf)) throw new TypeError('"list" argument must be an Array of Buffers');
      buf.copy(buffer, pos);
      pos += buf.length;
    }
  }
  return buffer;
};

function byteLength(string, encoding) {
  if (Buffer.isBuffer(string)) return string.length;
  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) return string.byteLength;
  if ("string" !== typeof string) throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string);
  var len = string.length, mustMatch = arguments.length > 2 && !0 === arguments[2];
  if (!mustMatch && 0 === len) return 0;
  for (var loweredCase = !1; ;) switch (encoding) {
   case "ascii":
   case "latin1":
   case "binary":
    return len;

   case "utf8":
   case "utf-8":
    return utf8ToBytes(string).length;

   case "ucs2":
   case "ucs-2":
   case "utf16le":
   case "utf-16le":
    return 2 * len;

   case "hex":
    return len >>> 1;

   case "base64":
    return base64ToBytes(string).length;

   default:
    if (loweredCase) return mustMatch ? -1 : utf8ToBytes(string).length;
    encoding = ("" + encoding).toLowerCase();
    loweredCase = !0;
  }
}

Buffer.byteLength = byteLength;

function slowToString(encoding, start, end) {
  var loweredCase = !1;
  (void 0 === start || start < 0) && (start = 0);
  if (start > this.length) return "";
  (void 0 === end || end > this.length) && (end = this.length);
  if (end <= 0) return "";
  if ((end >>>= 0) <= (start >>>= 0)) return "";
  encoding = encoding || "utf8";
  while (1) switch (encoding) {
   case "hex":
    return hexSlice(this, start, end);

   case "utf8":
   case "utf-8":
    return utf8Slice(this, start, end);

   case "ascii":
    return asciiSlice(this, start, end);

   case "latin1":
   case "binary":
    return latin1Slice(this, start, end);

   case "base64":
    return base64Slice(this, start, end);

   case "ucs2":
   case "ucs-2":
   case "utf16le":
   case "utf-16le":
    return utf16leSlice(this, start, end);

   default:
    if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
    encoding = (encoding + "").toLowerCase();
    loweredCase = !0;
  }
}

Buffer.prototype._isBuffer = !0;

function swap(b, n, m) {
  var i = b[n];
  b[n] = b[m];
  b[m] = i;
}

Buffer.prototype.swap16 = function() {
  var len = this.length;
  if (len % 2 !== 0) throw new RangeError("Buffer size must be a multiple of 16-bits");
  for (var i = 0; i < len; i += 2) swap(this, i, i + 1);
  return this;
};

Buffer.prototype.swap32 = function() {
  var len = this.length;
  if (len % 4 !== 0) throw new RangeError("Buffer size must be a multiple of 32-bits");
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3);
    swap(this, i + 1, i + 2);
  }
  return this;
};

Buffer.prototype.swap64 = function() {
  var len = this.length;
  if (len % 8 !== 0) throw new RangeError("Buffer size must be a multiple of 64-bits");
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7);
    swap(this, i + 1, i + 6);
    swap(this, i + 2, i + 5);
    swap(this, i + 3, i + 4);
  }
  return this;
};

Buffer.prototype.toString = function() {
  var length = this.length;
  return 0 === length ? "" : 0 === arguments.length ? utf8Slice(this, 0, length) : slowToString.apply(this, arguments);
};

Buffer.prototype.toLocaleString = Buffer.prototype.toString;

function hexWrite(buf, string, offset, length) {
  offset = Number(offset) || 0;
  var remaining = buf.length - offset;
  (!length || (length = Number(length)) > remaining) && (length = remaining);
  var strLen = string.length;
  length > strLen / 2 && (length = strLen / 2);
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(2 * i, 2), 16);
    if (numberIsNaN(parsed)) return i;
    buf[offset + i] = parsed;
  }
  return i;
}

function utf8Write(buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}

function asciiWrite(buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length);
}

function latin1Write(buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length);
}

function base64Write(buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length);
}

function ucs2Write(buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}

Buffer.prototype.write = function(string, offset, length, encoding) {
  if (void 0 === offset) {
    encoding = "utf8";
    length = this.length;
    offset = 0;
  } else if (void 0 === length && "string" === typeof offset) {
    encoding = offset;
    length = this.length;
    offset = 0;
  } else {
    if (!isFinite(offset)) throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
    offset >>>= 0;
    if (isFinite(length)) {
      length >>>= 0;
      void 0 === encoding && (encoding = "utf8");
    } else {
      encoding = length;
      length = void 0;
    }
  }
  var remaining = this.length - offset;
  (void 0 === length || length > remaining) && (length = remaining);
  if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) throw new RangeError("Attempt to write outside buffer bounds");
  encoding = encoding || "utf8";
  for (var loweredCase = !1; ;) switch (encoding) {
   case "hex":
    return hexWrite(this, string, offset, length);

   case "utf8":
   case "utf-8":
    return utf8Write(this, string, offset, length);

   case "ascii":
    return asciiWrite(this, string, offset, length);

   case "latin1":
   case "binary":
    return latin1Write(this, string, offset, length);

   case "base64":
    return base64Write(this, string, offset, length);

   case "ucs2":
   case "ucs-2":
   case "utf16le":
   case "utf-16le":
    return ucs2Write(this, string, offset, length);

   default:
    if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
    encoding = ("" + encoding).toLowerCase();
    loweredCase = !0;
  }
};

Buffer.prototype.toJSON = function() {
  return {
    type: "Buffer",
    data: Array.prototype.slice.call(this._arr || this, 0)
  };
};

function base64Slice(buf, start, end) {
  return base64.fromByteArray(0 === start && end === buf.length ? buf : buf.slice(start, end));
}

function utf8Slice(buf, start, end) {
  end = Math.min(buf.length, end);
  var res = [], i = start;
  while (i < end) {
    var secondByte, thirdByte, fourthByte, tempCodePoint, firstByte = buf[i], codePoint = null, bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
    if (i + bytesPerSequence <= end) switch (bytesPerSequence) {
     case 1:
      firstByte < 128 && (codePoint = firstByte);
      break;

     case 2:
      128 === (192 & (secondByte = buf[i + 1])) && (tempCodePoint = (31 & firstByte) << 6 | 63 & secondByte) > 127 && (codePoint = tempCodePoint);
      break;

     case 3:
      thirdByte = buf[i + 2];
      128 === (192 & (secondByte = buf[i + 1])) && 128 === (192 & thirdByte) && (tempCodePoint = (15 & firstByte) << 12 | (63 & secondByte) << 6 | 63 & thirdByte) > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343) && (codePoint = tempCodePoint);
      break;

     case 4:
      thirdByte = buf[i + 2];
      fourthByte = buf[i + 3];
      128 === (192 & (secondByte = buf[i + 1])) && 128 === (192 & thirdByte) && 128 === (192 & fourthByte) && (tempCodePoint = (15 & firstByte) << 18 | (63 & secondByte) << 12 | (63 & thirdByte) << 6 | 63 & fourthByte) > 65535 && tempCodePoint < 1114112 && (codePoint = tempCodePoint);
    }
    if (null === codePoint) {
      codePoint = 65533;
      bytesPerSequence = 1;
    } else if (codePoint > 65535) {
      res.push((codePoint -= 65536) >>> 10 & 1023 | 55296);
      codePoint = 56320 | 1023 & codePoint;
    }
    res.push(codePoint);
    i += bytesPerSequence;
  }
  return decodeCodePointsArray(res);
}

var _, MAX_ARGUMENTS_LENGTH = 4096;

function decodeCodePointsArray(codePoints) {
  var len = codePoints.length;
  if (len <= MAX_ARGUMENTS_LENGTH) return String.fromCharCode.apply(String, codePoints);
  var res = "", i = 0;
  while (i < len) res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
  return res;
}

function asciiSlice(buf, start, end) {
  var ret = "";
  end = Math.min(buf.length, end);
  for (var i = start; i < end; ++i) ret += String.fromCharCode(127 & buf[i]);
  return ret;
}

function latin1Slice(buf, start, end) {
  var ret = "";
  end = Math.min(buf.length, end);
  for (var i = start; i < end; ++i) ret += String.fromCharCode(buf[i]);
  return ret;
}

function hexSlice(buf, start, end) {
  var len = buf.length;
  (!start || start < 0) && (start = 0);
  (!end || end < 0 || end > len) && (end = len);
  for (var out = "", i = start; i < end; ++i) out += toHex(buf[i]);
  return out;
}

function utf16leSlice(buf, start, end) {
  for (var bytes = buf.slice(start, end), res = "", i = 0; i < bytes.length; i += 2) res += String.fromCharCode(bytes[i] + 256 * bytes[i + 1]);
  return res;
}

Buffer.prototype.slice = function(start, end) {
  var len = this.length;
  (start = ~~start) < 0 ? (start += len) < 0 && (start = 0) : start > len && (start = len);
  (end = void 0 === end ? len : ~~end) < 0 ? (end += len) < 0 && (end = 0) : end > len && (end = len);
  end < start && (end = start);
  var newBuf = this.subarray(start, end);
  Object.setPrototypeOf(newBuf, Buffer.prototype);
  return newBuf;
};

Buffer.prototype.readUIntLE = function(offset, byteLength) {
  byteLength >>>= 0;
  var val = this[offset >>>= 0], mul = 1, i = 0;
  while (++i < byteLength && (mul *= 256)) val += this[offset + i] * mul;
  return val;
};

Buffer.prototype.readUIntBE = function(offset, byteLength) {
  byteLength >>>= 0;
  var val = this[(offset >>>= 0) + --byteLength], mul = 1;
  while (byteLength > 0 && (mul *= 256)) val += this[offset + --byteLength] * mul;
  return val;
};

Buffer.prototype.readUInt8 = function(offset) {
  return this[offset >>>= 0];
};

Buffer.prototype.readUInt16LE = function(offset) {
  return this[offset >>>= 0] | this[offset + 1] << 8;
};

Buffer.prototype.readUInt16BE = function(offset) {
  return this[offset >>>= 0] << 8 | this[offset + 1];
};

Buffer.prototype.readUInt32LE = function(offset) {
  return (this[offset >>>= 0] | this[offset + 1] << 8 | this[offset + 2] << 16) + 16777216 * this[offset + 3];
};

Buffer.prototype.readUInt32BE = function(offset) {
  return 16777216 * this[offset >>>= 0] + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};

Buffer.prototype.readIntLE = function(offset, byteLength) {
  byteLength >>>= 0;
  var val = this[offset >>>= 0], mul = 1, i = 0;
  while (++i < byteLength && (mul *= 256)) val += this[offset + i] * mul;
  val >= (mul *= 128) && (val -= Math.pow(2, 8 * byteLength));
  return val;
};

Buffer.prototype.readIntBE = function(offset, byteLength) {
  var i = byteLength >>>= 0, mul = 1, val = this[(offset >>>= 0) + --i];
  while (i > 0 && (mul *= 256)) val += this[offset + --i] * mul;
  val >= (mul *= 128) && (val -= Math.pow(2, 8 * byteLength));
  return val;
};

Buffer.prototype.readInt8 = function(offset) {
  return 128 & this[offset >>>= 0] ? -1 * (255 - this[offset] + 1) : this[offset];
};

Buffer.prototype.readInt16LE = function(offset) {
  var val = this[offset >>>= 0] | this[offset + 1] << 8;
  return 32768 & val ? 4294901760 | val : val;
};

Buffer.prototype.readInt16BE = function(offset) {
  var val = this[1 + (offset >>>= 0)] | this[offset] << 8;
  return 32768 & val ? 4294901760 | val : val;
};

Buffer.prototype.readInt32LE = function(offset) {
  return this[offset >>>= 0] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};

Buffer.prototype.readInt32BE = function(offset) {
  return this[offset >>>= 0] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};

Buffer.prototype.readFloatLE = function(offset) {
  return ieee754.read(this, offset >>>= 0, !0, 23, 4);
};

Buffer.prototype.readFloatBE = function(offset) {
  return ieee754.read(this, offset >>>= 0, !1, 23, 4);
};

Buffer.prototype.readDoubleLE = function(offset) {
  return ieee754.read(this, offset >>>= 0, !0, 52, 8);
};

Buffer.prototype.readDoubleBE = function(offset) {
  return ieee754.read(this, offset >>>= 0, !1, 52, 8);
};

Buffer.prototype.writeUIntLE = function(value, offset, byteLength) {
  byteLength >>>= 0;
  var mul = 1, i = 0;
  this[offset >>>= 0] = 255 & (value = +value);
  while (++i < byteLength && (mul *= 256)) this[offset + i] = value / mul & 255;
  return offset + byteLength;
};

Buffer.prototype.writeUIntBE = function(value, offset, byteLength) {
  var i = (byteLength >>>= 0) - 1, mul = 1;
  this[(offset >>>= 0) + i] = 255 & (value = +value);
  while (--i >= 0 && (mul *= 256)) this[offset + i] = value / mul & 255;
  return offset + byteLength;
};

Buffer.prototype.writeUInt8 = function(value, offset) {
  this[offset >>>= 0] = 255 & (value = +value);
  return offset + 1;
};

Buffer.prototype.writeUInt16LE = function(value, offset) {
  this[offset >>>= 0] = 255 & (value = +value);
  this[offset + 1] = value >>> 8;
  return offset + 2;
};

Buffer.prototype.writeUInt16BE = function(value, offset) {
  this[offset >>>= 0] = (value = +value) >>> 8;
  this[offset + 1] = 255 & value;
  return offset + 2;
};

Buffer.prototype.writeUInt32LE = function(value, offset) {
  this[3 + (offset >>>= 0)] = (value = +value) >>> 24;
  this[offset + 2] = value >>> 16;
  this[offset + 1] = value >>> 8;
  this[offset] = 255 & value;
  return offset + 4;
};

Buffer.prototype.writeUInt32BE = function(value, offset) {
  this[offset >>>= 0] = (value = +value) >>> 24;
  this[offset + 1] = value >>> 16;
  this[offset + 2] = value >>> 8;
  this[offset + 3] = 255 & value;
  return offset + 4;
};

Buffer.prototype.writeIntLE = function(value, offset, byteLength) {
  var i = 0, mul = 1, sub = 0;
  this[offset >>>= 0] = 255 & (value = +value);
  while (++i < byteLength && (mul *= 256)) {
    value < 0 && 0 === sub && 0 !== this[offset + i - 1] && (sub = 1);
    this[offset + i] = (value / mul >> 0) - sub & 255;
  }
  return offset + byteLength;
};

Buffer.prototype.writeIntBE = function(value, offset, byteLength) {
  var i = byteLength - 1, mul = 1, sub = 0;
  this[(offset >>>= 0) + i] = 255 & (value = +value);
  while (--i >= 0 && (mul *= 256)) {
    value < 0 && 0 === sub && 0 !== this[offset + i + 1] && (sub = 1);
    this[offset + i] = (value / mul >> 0) - sub & 255;
  }
  return offset + byteLength;
};

Buffer.prototype.writeInt8 = function(value, offset) {
  (value = +value) < 0 && (value = 255 + value + 1);
  this[offset >>>= 0] = 255 & value;
  return offset + 1;
};

Buffer.prototype.writeInt16LE = function(value, offset) {
  this[offset >>>= 0] = 255 & (value = +value);
  this[offset + 1] = value >>> 8;
  return offset + 2;
};

Buffer.prototype.writeInt16BE = function(value, offset) {
  this[offset >>>= 0] = (value = +value) >>> 8;
  this[offset + 1] = 255 & value;
  return offset + 2;
};

Buffer.prototype.writeInt32LE = function(value, offset) {
  this[offset >>>= 0] = 255 & (value = +value);
  this[offset + 1] = value >>> 8;
  this[offset + 2] = value >>> 16;
  this[offset + 3] = value >>> 24;
  return offset + 4;
};

Buffer.prototype.writeInt32BE = function(value, offset) {
  (value = +value) < 0 && (value = 4294967295 + value + 1);
  this[offset >>>= 0] = value >>> 24;
  this[offset + 1] = value >>> 16;
  this[offset + 2] = value >>> 8;
  this[offset + 3] = 255 & value;
  return offset + 4;
};

function writeFloat(buf, value, offset, littleEndian, noAssert) {
  ieee754.write(buf, value = +value, offset >>>= 0, littleEndian, 23, 4);
  return offset + 4;
}

Buffer.prototype.writeFloatLE = function(value, offset, noAssert) {
  return writeFloat(this, value, offset, !0, noAssert);
};

Buffer.prototype.writeFloatBE = function(value, offset, noAssert) {
  return writeFloat(this, value, offset, !1, noAssert);
};

function writeDouble(buf, value, offset, littleEndian, noAssert) {
  ieee754.write(buf, value = +value, offset >>>= 0, littleEndian, 52, 8);
  return offset + 8;
}

Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) {
  return writeDouble(this, value, offset, !0, noAssert);
};

Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) {
  return writeDouble(this, value, offset, !1, noAssert);
};

Buffer.prototype.copy = function(target, targetStart, start, end) {
  if (!Buffer.isBuffer(target)) throw new TypeError("argument should be a Buffer");
  start = start || 0;
  end || 0 === end || (end = this.length);
  targetStart >= target.length && (targetStart = target.length);
  end > 0 && end < start && (end = start);
  if (end === start) return 0;
  if (0 === target.length || 0 === this.length) return 0;
  if ((targetStart = targetStart || 0) < 0) throw new RangeError("targetStart out of bounds");
  if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
  if (end < 0) throw new RangeError("sourceEnd out of bounds");
  end > this.length && (end = this.length);
  target.length - targetStart < end - start && (end = target.length - targetStart + start);
  var len = end - start;
  this === target ? this.copyWithin(targetStart, start, end) : Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
  return len;
};

Buffer.prototype.fill = function(val, start, end, encoding) {
  if ("string" === typeof val) {
    if ("string" === typeof start) {
      encoding = start;
      start = 0;
      end = this.length;
    } else if ("string" === typeof end) {
      encoding = end;
      end = this.length;
    }
    if (void 0 !== encoding && "string" !== typeof encoding) throw new TypeError("encoding must be a string");
    if ("string" === typeof encoding && !Buffer.isEncoding(encoding)) throw new TypeError("Unknown encoding: " + encoding);
    if (1 === val.length) {
      var code = val.charCodeAt(0);
      ("utf8" === encoding && code < 128 || "latin1" === encoding) && (val = code);
    }
  } else "number" === typeof val && (val &= 255);
  if (start < 0 || this.length < start || this.length < end) throw new RangeError("Out of range index");
  if (end <= start) return this;
  start >>>= 0;
  end = void 0 === end ? this.length : end >>> 0;
  var i;
  if ("number" === typeof (val = val || 0)) for (i = start; i < end; ++i) this[i] = val; else {
    var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding), len = bytes.length;
    if (0 === len) throw new TypeError('The value "' + val + '" is invalid for argument "value"');
    for (i = 0; i < end - start; ++i) this[i + start] = bytes[i % len];
  }
  return this;
};

var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;

function base64clean(str) {
  if ((str = (str = str.split("=")[0]).trim().replace(INVALID_BASE64_RE, "")).length < 2) return "";
  while (str.length % 4 !== 0) str += "=";
  return str;
}

function toHex(n) {
  return n < 16 ? "0" + n.toString(16) : n.toString(16);
}

function utf8ToBytes(string, units) {
  units = units || Infinity;
  for (var codePoint, length = string.length, leadSurrogate = null, bytes = [], i = 0; i < length; ++i) {
    if ((codePoint = string.charCodeAt(i)) > 55295 && codePoint < 57344) {
      if (!leadSurrogate) {
        if (codePoint > 56319) {
          (units -= 3) > -1 && bytes.push(239, 191, 189);
          continue;
        }
        if (i + 1 === length) {
          (units -= 3) > -1 && bytes.push(239, 191, 189);
          continue;
        }
        leadSurrogate = codePoint;
        continue;
      }
      if (codePoint < 56320) {
        (units -= 3) > -1 && bytes.push(239, 191, 189);
        leadSurrogate = codePoint;
        continue;
      }
      codePoint = 65536 + (leadSurrogate - 55296 << 10 | codePoint - 56320);
    } else leadSurrogate && (units -= 3) > -1 && bytes.push(239, 191, 189);
    leadSurrogate = null;
    if (codePoint < 128) {
      if (--units < 0) break;
      bytes.push(codePoint);
    } else if (codePoint < 2048) {
      if ((units -= 2) < 0) break;
      bytes.push(codePoint >> 6 | 192, 63 & codePoint | 128);
    } else if (codePoint < 65536) {
      if ((units -= 3) < 0) break;
      bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, 63 & codePoint | 128);
    } else {
      if (!(codePoint < 1114112)) throw new Error("Invalid code point");
      if ((units -= 4) < 0) break;
      bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, 63 & codePoint | 128);
    }
  }
  return bytes;
}

function asciiToBytes(str) {
  for (var byteArray = [], i = 0; i < str.length; ++i) byteArray.push(255 & str.charCodeAt(i));
  return byteArray;
}

function utf16leToBytes(str, units) {
  for (var c, hi, byteArray = [], i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break;
    hi = (c = str.charCodeAt(i)) >> 8;
    byteArray.push(c % 256);
    byteArray.push(hi);
  }
  return byteArray;
}

function base64ToBytes(str) {
  return base64.toByteArray(base64clean(str));
}

function blitBuffer(src, dst, offset, length) {
  for (var i = 0; i < length; ++i) {
    if (i + offset >= dst.length || i >= src.length) break;
    dst[i + offset] = src[i];
  }
  return i;
}

function isInstance(obj, type) {
  return obj instanceof type || null != obj && null != obj.constructor && null != obj.constructor.name && obj.constructor.name === type.name;
}

function numberIsNaN(obj) {
  return obj !== obj;
}

function fromArrayView(a) {
  return isInstance(a, Uint8Array) ? fromArrayBuffer((a = new Uint8Array(a)).buffer, a.byteOffset, a.byteLength) : fromArrayLike(a);
}
},{"base64-js":8,"ieee754":16}],11:[function(require,module,exports){
var Buffer = require("buffer").Buffer, Transform = require("readable-stream").Transform, tools = require("./tools.js"), schema = require("./schema.js"), debug = "ebml:decoder", STATE_TAG = 1, STATE_SIZE = 2, STATE_CONTENT = 3;

function EbmlDecoder(options) {
  (options = options || {}).readableObjectMode = !0;
  Transform.call(this, options);
  this._buffer = null;
  this._tag_stack = [];
  this._state = STATE_TAG;
  this._cursor = 0;
  this._total = 0;
  this._schema = schema;
}

require("/bundle/utils").inherit(EbmlDecoder, Transform);

EbmlDecoder.prototype._transform = function(chunk, enc, done) {
  this._buffer = null === this._buffer ? chunk : Buffer.concat([ this._buffer, chunk ]);
  while (this._cursor < this._buffer.length) {
    if (this._state === STATE_TAG && !this.readTag()) break;
    if (this._state === STATE_SIZE && !this.readSize()) break;
    if (this._state === STATE_CONTENT && !this.readContent()) break;
  }
  done();
};

EbmlDecoder.prototype.getSchemaInfo = function(tagStr) {
  return this._schema[tagStr] || {
    type: "unknown",
    name: "unknown"
  };
};

EbmlDecoder.prototype.readTag = function() {
  if (this._cursor >= this._buffer.length) return !1;
  var start = this._total, tag = tools.readVint(this._buffer, this._cursor);
  if (null == tag) return !1;
  var tagStr = this._buffer.toString("hex", this._cursor, this._cursor + tag.length);
  this._cursor += tag.length;
  this._total += tag.length;
  this._state = STATE_SIZE;
  var tagObj = {
    tag: tag.value,
    tagStr: tagStr,
    type: this.getSchemaInfo(tagStr).type,
    name: this.getSchemaInfo(tagStr).name,
    start: start,
    end: start + tag.length
  };
  this._tag_stack.push(tagObj);
  return !0;
};

EbmlDecoder.prototype.readSize = function() {
  var tagObj = this._tag_stack[this._tag_stack.length - 1];
  if (this._cursor >= this._buffer.length) return !1;
  var size = tools.readVint(this._buffer, this._cursor);
  if (null == size) return !1;
  this._cursor += size.length;
  this._total += size.length;
  this._state = STATE_CONTENT;
  tagObj.dataSize = size.value;
  -1 === size.value ? tagObj.end = -1 : tagObj.end += size.value + size.length;
  return !0;
};

EbmlDecoder.prototype.readContent = function() {
  var tagObj = this._tag_stack[this._tag_stack.length - 1];
  if ("m" === tagObj.type) {
    this.push([ "start", tagObj ]);
    this._state = STATE_TAG;
    return !0;
  }
  if (this._buffer.length < this._cursor + tagObj.dataSize) return !1;
  var data = this._buffer.subarray(this._cursor, this._cursor + tagObj.dataSize);
  this._total += tagObj.dataSize;
  this._state = STATE_TAG;
  this._buffer = this._buffer.subarray(this._cursor + tagObj.dataSize);
  this._cursor = 0;
  this._tag_stack.pop();
  tagObj.data = data;
  this.push([ "tag", tagObj ]);
  while (this._tag_stack.length > 0) {
    var topEle = this._tag_stack[this._tag_stack.length - 1];
    if (this._total < topEle.end) break;
    this.push([ "end", topEle ]);
    this._tag_stack.pop();
  }
  return !0;
};

module.exports = EbmlDecoder;
},{"./schema.js":12,"./tools.js":13,"/bundle/utils":4,"buffer":10,"readable-stream":41}],12:[function(require,module,exports){
var schema={80:{name:"ChapterDisplay",level:"4",type:"m",multiple:"1",minver:"1",webm:"1"},83:{name:"TrackType",level:"3",type:"u",mandatory:"1",minver:"1",range:"1-254"},85:{name:"ChapString",level:"5",type:"8",mandatory:"1",minver:"1",webm:"1"},86:{name:"CodecID",level:"3",type:"s",mandatory:"1",minver:"1"},88:{name:"FlagDefault",level:"3",type:"u",mandatory:"1",minver:"1",default:"1",range:"0-1"},89:{name:"ChapterTrackNumber",level:"5",type:"u",mandatory:"1",multiple:"1",minver:"1",webm:"0",range:"not 0"},91:{name:"ChapterTimeStart",level:"4",type:"u",mandatory:"1",minver:"1",webm:"1"},92:{name:"ChapterTimeEnd",level:"4",type:"u",minver:"1",webm:"0"},96:{name:"CueRefTime",level:"5",type:"u",mandatory:"1",minver:"2",webm:"0"},97:{name:"CueRefCluster",level:"5",type:"u",mandatory:"1",webm:"0"},98:{name:"ChapterFlagHidden",level:"4",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0",range:"0-1"},4254:{name:"ContentCompAlgo",level:"6",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0",br:["","","",""],del:["1 - bzlib,","2 - lzo1x"]},4255:{name:"ContentCompSettings",level:"6",type:"b",minver:"1",webm:"0"},4282:{name:"DocType",level:"1",type:"s",mandatory:"1",default:"matroska",minver:"1"},4285:{name:"DocTypeReadVersion",level:"1",type:"u",mandatory:"1",default:"1",minver:"1"},4286:{name:"EBMLVersion",level:"1",type:"u",mandatory:"1",default:"1",minver:"1"},4287:{name:"DocTypeVersion",level:"1",type:"u",mandatory:"1",default:"1",minver:"1"},4444:{name:"SegmentFamily",level:"2",type:"b",multiple:"1",minver:"1",webm:"0",bytesize:"16"},4461:{name:"DateUTC",level:"2",type:"d",minver:"1"},4484:{name:"TagDefault",level:"4",type:"u",mandatory:"1",minver:"1",webm:"0",default:"1",range:"0-1"},4485:{name:"TagBinary",level:"4",type:"b",minver:"1",webm:"0"},4487:{name:"TagString",level:"4",type:"8",minver:"1",webm:"0"},4489:{name:"Duration",level:"2",type:"f",minver:"1",range:"> 0"},4598:{name:"ChapterFlagEnabled",level:"4",type:"u",mandatory:"1",minver:"1",webm:"0",default:"1",range:"0-1"},4660:{name:"FileMimeType",level:"3",type:"s",mandatory:"1",minver:"1",webm:"0"},4661:{name:"FileUsedStartTime",level:"3",type:"u",divx:"1"},4662:{name:"FileUsedEndTime",level:"3",type:"u",divx:"1"},4675:{name:"FileReferral",level:"3",type:"b",webm:"0"},5031:{name:"ContentEncodingOrder",level:"5",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0"},5032:{name:"ContentEncodingScope",level:"5",type:"u",mandatory:"1",minver:"1",webm:"0",default:"1",range:"not 0",br:["","",""]},5033:{name:"ContentEncodingType",level:"5",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0",br:["",""]},5034:{name:"ContentCompression",level:"5",type:"m",minver:"1",webm:"0"},5035:{name:"ContentEncryption",level:"5",type:"m",minver:"1",webm:"0"},5378:{name:"CueBlockNumber",level:"4",type:"u",minver:"1",default:"1",range:"not 0"},5654:{name:"ChapterStringUID",level:"4",type:"8",mandatory:"0",minver:"3",webm:"1"},5741:{name:"WritingApp",level:"2",type:"8",mandatory:"1",minver:"1"},5854:{name:"SilentTracks",level:"2",type:"m",minver:"1",webm:"0"},6240:{name:"ContentEncoding",level:"4",type:"m",mandatory:"1",multiple:"1",minver:"1",webm:"0"},6264:{name:"BitDepth",level:"4",type:"u",minver:"1",range:"not 0"},6532:{name:"SignedElement",level:"3",type:"b",multiple:"1",webm:"0"},6624:{name:"TrackTranslate",level:"3",type:"m",multiple:"1",minver:"1",webm:"0"},6911:{name:"ChapProcessCommand",level:"5",type:"m",multiple:"1",minver:"1",webm:"0"},6922:{name:"ChapProcessTime",level:"6",type:"u",mandatory:"1",minver:"1",webm:"0"},6924:{name:"ChapterTranslate",level:"2",type:"m",multiple:"1",minver:"1",webm:"0"},6933:{name:"ChapProcessData",level:"6",type:"b",mandatory:"1",minver:"1",webm:"0"},6944:{name:"ChapProcess",level:"4",type:"m",multiple:"1",minver:"1",webm:"0"},6955:{name:"ChapProcessCodecID",level:"5",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0"},7373:{name:"Tag",level:"2",type:"m",mandatory:"1",multiple:"1",minver:"1",webm:"0"},7384:{name:"SegmentFilename",level:"2",type:"8",minver:"1",webm:"0"},7446:{name:"AttachmentLink",level:"3",type:"u",minver:"1",webm:"0",range:"not 0"},258688:{name:"CodecName",level:"3",type:"8",minver:"1"},18538067:{name:"Segment",level:"0",type:"m",mandatory:"1",multiple:"1",minver:"1"},"447a":{name:"TagLanguage",level:"4",type:"s",mandatory:"1",minver:"1",webm:"0",default:"und"},"45a3":{name:"TagName",level:"4",type:"8",mandatory:"1",minver:"1",webm:"0"},"67c8":{name:"SimpleTag",level:"3",recursive:"1",type:"m",mandatory:"1",multiple:"1",minver:"1",webm:"0"},"63c6":{name:"TagAttachmentUID",level:"4",type:"u",multiple:"1",minver:"1",webm:"0",default:"0"},"63c4":{name:"TagChapterUID",level:"4",type:"u",multiple:"1",minver:"1",webm:"0",default:"0"},"63c9":{name:"TagEditionUID",level:"4",type:"u",multiple:"1",minver:"1",webm:"0",default:"0"},"63c5":{name:"TagTrackUID",level:"4",type:"u",multiple:"1",minver:"1",webm:"0",default:"0"},"63ca":{name:"TargetType",level:"4",type:"s",minver:"1",webm:"0",strong:"informational"},"68ca":{name:"TargetTypeValue",level:"4",type:"u",minver:"1",webm:"0",default:"50"},"63c0":{name:"Targets",level:"3",type:"m",mandatory:"1",minver:"1",webm:"0"},"1254c367":{name:"Tags",level:"1",type:"m",multiple:"1",minver:"1",webm:"0"},"450d":{name:"ChapProcessPrivate",level:"5",type:"b",minver:"1",webm:"0"},"437e":{name:"ChapCountry",level:"5",type:"s",multiple:"1",minver:"1",webm:"0"},"437c":{name:"ChapLanguage",level:"5",type:"s",mandatory:"1",multiple:"1",minver:"1",webm:"1",default:"eng"},"8f":{name:"ChapterTrack",level:"4",type:"m",minver:"1",webm:"0"},"63c3":{name:"ChapterPhysicalEquiv",level:"4",type:"u",minver:"1",webm:"0"},"6ebc":{name:"ChapterSegmentEditionUID",level:"4",type:"u",minver:"1",webm:"0",range:"not 0"},"6e67":{name:"ChapterSegmentUID",level:"4",type:"b",minver:"1",webm:"0",range:">0",bytesize:"16"},"73c4":{name:"ChapterUID",level:"4",type:"u",mandatory:"1",minver:"1",webm:"1",range:"not 0"},b6:{name:"ChapterAtom",level:"3",recursive:"1",type:"m",mandatory:"1",multiple:"1",minver:"1",webm:"1"},"45dd":{name:"EditionFlagOrdered",level:"3",type:"u",minver:"1",webm:"0",default:"0",range:"0-1"},"45db":{name:"EditionFlagDefault",level:"3",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0",range:"0-1"},"45bd":{name:"EditionFlagHidden",level:"3",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0",range:"0-1"},"45bc":{name:"EditionUID",level:"3",type:"u",minver:"1",webm:"0",range:"not 0"},"45b9":{name:"EditionEntry",level:"2",type:"m",mandatory:"1",multiple:"1",minver:"1",webm:"1"},"1043a770":{name:"Chapters",level:"1",type:"m",minver:"1",webm:"1"},"46ae":{name:"FileUID",level:"3",type:"u",mandatory:"1",minver:"1",webm:"0",range:"not 0"},"465c":{name:"FileData",level:"3",type:"b",mandatory:"1",minver:"1",webm:"0"},"466e":{name:"FileName",level:"3",type:"8",mandatory:"1",minver:"1",webm:"0"},"467e":{name:"FileDescription",level:"3",type:"8",minver:"1",webm:"0"},"61a7":{name:"AttachedFile",level:"2",type:"m",mandatory:"1",multiple:"1",minver:"1",webm:"0"},"1941a469":{name:"Attachments",level:"1",type:"m",minver:"1",webm:"0"},eb:{name:"CueRefCodecState",level:"5",type:"u",webm:"0",default:"0"},"535f":{name:"CueRefNumber",level:"5",type:"u",webm:"0",default:"1",range:"not 0"},db:{name:"CueReference",level:"4",type:"m",multiple:"1",minver:"2",webm:"0"},ea:{name:"CueCodecState",level:"4",type:"u",minver:"2",webm:"0",default:"0"},b2:{name:"CueDuration",level:"4",type:"u",mandatory:"0",minver:"4",webm:"0"},f0:{name:"CueRelativePosition",level:"4",type:"u",mandatory:"0",minver:"4",webm:"0"},f1:{name:"CueClusterPosition",level:"4",type:"u",mandatory:"1",minver:"1"},f7:{name:"CueTrack",level:"4",type:"u",mandatory:"1",minver:"1",range:"not 0"},b7:{name:"CueTrackPositions",level:"3",type:"m",mandatory:"1",multiple:"1",minver:"1"},b3:{name:"CueTime",level:"3",type:"u",mandatory:"1",minver:"1"},bb:{name:"CuePoint",level:"2",type:"m",mandatory:"1",multiple:"1",minver:"1"},"1c53bb6b":{name:"Cues",level:"1",type:"m",minver:"1"},"47e6":{name:"ContentSigHashAlgo",level:"6",type:"u",minver:"1",webm:"0",default:"0",br:["",""]},"47e5":{name:"ContentSigAlgo",level:"6",type:"u",minver:"1",webm:"0",default:"0",br:""},"47e4":{name:"ContentSigKeyID",level:"6",type:"b",minver:"1",webm:"0"},"47e3":{name:"ContentSignature",level:"6",type:"b",minver:"1",webm:"0"},"47e2":{name:"ContentEncKeyID",level:"6",type:"b",minver:"1",webm:"0"},"47e1":{name:"ContentEncAlgo",level:"6",type:"u",minver:"1",webm:"0",default:"0",br:""},"6d80":{name:"ContentEncodings",level:"3",type:"m",minver:"1",webm:"0"},c4:{name:"TrickMasterTrackSegmentUID",level:"3",type:"b",divx:"1",bytesize:"16"},c7:{name:"TrickMasterTrackUID",level:"3",type:"u",divx:"1"},c6:{name:"TrickTrackFlag",level:"3",type:"u",divx:"1",default:"0"},c1:{name:"TrickTrackSegmentUID",level:"3",type:"b",divx:"1",bytesize:"16"},c0:{name:"TrickTrackUID",level:"3",type:"u",divx:"1"},ed:{name:"TrackJoinUID",level:"5",type:"u",mandatory:"1",multiple:"1",minver:"3",webm:"0",range:"not 0"},e9:{name:"TrackJoinBlocks",level:"4",type:"m",minver:"3",webm:"0"},e6:{name:"TrackPlaneType",level:"6",type:"u",mandatory:"1",minver:"3",webm:"0"},e5:{name:"TrackPlaneUID",level:"6",type:"u",mandatory:"1",minver:"3",webm:"0",range:"not 0"},e4:{name:"TrackPlane",level:"5",type:"m",mandatory:"1",multiple:"1",minver:"3",webm:"0"},e3:{name:"TrackCombinePlanes",level:"4",type:"m",minver:"3",webm:"0"},e2:{name:"TrackOperation",level:"3",type:"m",minver:"3",webm:"0"},"7d7b":{name:"ChannelPositions",level:"4",type:"b",webm:"0"},"9f":{name:"Channels",level:"4",type:"u",mandatory:"1",minver:"1",default:"1",range:"not 0"},"78b5":{name:"OutputSamplingFrequency",level:"4",type:"f",minver:"1",default:"Sampling Frequency",range:"> 0"},b5:{name:"SamplingFrequency",level:"4",type:"f",mandatory:"1",minver:"1",default:"8000.0",range:"> 0"},e1:{name:"Audio",level:"3",type:"m",minver:"1"},"2383e3":{name:"FrameRate",level:"4",type:"f",range:"> 0",strong:"Informational"},"2fb523":{name:"GammaValue",level:"4",type:"f",webm:"0",range:"> 0"},"2eb524":{name:"ColourSpace",level:"4",type:"b",minver:"1",webm:"0",bytesize:"4"},"54b3":{name:"AspectRatioType",level:"4",type:"u",minver:"1",default:"0"},"54b2":{name:"DisplayUnit",level:"4",type:"u",minver:"1",default:"0"},"54ba":{name:"DisplayHeight",level:"4",type:"u",minver:"1",default:"PixelHeight",range:"not 0"},"54b0":{name:"DisplayWidth",level:"4",type:"u",minver:"1",default:"PixelWidth",range:"not 0"},"54dd":{name:"PixelCropRight",level:"4",type:"u",minver:"1",default:"0"},"54cc":{name:"PixelCropLeft",level:"4",type:"u",minver:"1",default:"0"},"54bb":{name:"PixelCropTop",level:"4",type:"u",minver:"1",default:"0"},"54aa":{name:"PixelCropBottom",level:"4",type:"u",minver:"1",default:"0"},ba:{name:"PixelHeight",level:"4",type:"u",mandatory:"1",minver:"1",range:"not 0"},b0:{name:"PixelWidth",level:"4",type:"u",mandatory:"1",minver:"1",range:"not 0"},"53b9":{name:"OldStereoMode",level:"4",type:"u",maxver:"0",webm:"0",divx:"0"},"53c0":{name:"AlphaMode",level:"4",type:"u",minver:"3",webm:"1",default:"0"},"53b8":{name:"StereoMode",level:"4",type:"u",minver:"3",webm:"1",default:"0"},"9a":{name:"FlagInterlaced",level:"4",type:"u",mandatory:"1",minver:"2",webm:"1",default:"0",range:"0-1"},e0:{name:"Video",level:"3",type:"m",minver:"1"},"66a5":{name:"TrackTranslateTrackID",level:"4",type:"b",mandatory:"1",minver:"1",webm:"0"},"66bf":{name:"TrackTranslateCodec",level:"4",type:"u",mandatory:"1",minver:"1",webm:"0"},"66fc":{name:"TrackTranslateEditionUID",level:"4",type:"u",multiple:"1",minver:"1",webm:"0"},"56bb":{name:"SeekPreRoll",level:"3",type:"u",mandatory:"1",multiple:"0",default:"0",minver:"4",webm:"1"},"56aa":{name:"CodecDelay",level:"3",type:"u",multiple:"0",default:"0",minver:"4",webm:"1"},"6fab":{name:"TrackOverlay",level:"3",type:"u",multiple:"1",minver:"1",webm:"0"},aa:{name:"CodecDecodeAll",level:"3",type:"u",mandatory:"1",minver:"2",webm:"0",default:"1",range:"0-1"},"26b240":{name:"CodecDownloadURL",level:"3",type:"s",multiple:"1",webm:"0"},"3b4040":{name:"CodecInfoURL",level:"3",type:"s",multiple:"1",webm:"0"},"3a9697":{name:"CodecSettings",level:"3",type:"8",webm:"0"},"63a2":{name:"CodecPrivate",level:"3",type:"b",minver:"1"},"22b59c":{name:"Language",level:"3",type:"s",minver:"1",default:"eng"},"536e":{name:"Name",level:"3",type:"8",minver:"1"},"55ee":{name:"MaxBlockAdditionID",level:"3",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0"},"537f":{name:"TrackOffset",level:"3",type:"i",webm:"0",default:"0"},"23314f":{name:"TrackTimecodeScale",level:"3",type:"f",mandatory:"1",minver:"1",maxver:"3",webm:"0",default:"1.0",range:"> 0"},"234e7a":{name:"DefaultDecodedFieldDuration",level:"3",type:"u",minver:"4",range:"not 0"},"23e383":{name:"DefaultDuration",level:"3",type:"u",minver:"1",range:"not 0"},"6df8":{name:"MaxCache",level:"3",type:"u",minver:"1",webm:"0"},"6de7":{name:"MinCache",level:"3",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0"},"9c":{name:"FlagLacing",level:"3",type:"u",mandatory:"1",minver:"1",default:"1",range:"0-1"},"55aa":{name:"FlagForced",level:"3",type:"u",mandatory:"1",minver:"1",default:"0",range:"0-1"},b9:{name:"FlagEnabled",level:"3",type:"u",mandatory:"1",minver:"2",webm:"1",default:"1",range:"0-1"},"73c5":{name:"TrackUID",level:"3",type:"u",mandatory:"1",minver:"1",range:"not 0"},d7:{name:"TrackNumber",level:"3",type:"u",mandatory:"1",minver:"1",range:"not 0"},ae:{name:"TrackEntry",level:"2",type:"m",mandatory:"1",multiple:"1",minver:"1"},"1654ae6b":{name:"Tracks",level:"1",type:"m",multiple:"1",minver:"1"},af:{name:"EncryptedBlock",level:"2",type:"b",multiple:"1",webm:"0"},ca:{name:"ReferenceTimeCode",level:"4",type:"u",multiple:"0",mandatory:"1",minver:"0",webm:"0",divx:"1"},c9:{name:"ReferenceOffset",level:"4",type:"u",multiple:"0",mandatory:"1",minver:"0",webm:"0",divx:"1"},c8:{name:"ReferenceFrame",level:"3",type:"m",multiple:"0",minver:"0",webm:"0",divx:"1"},cf:{name:"SliceDuration",level:"5",type:"u",default:"0"},ce:{name:"Delay",level:"5",type:"u",default:"0"},cb:{name:"BlockAdditionID",level:"5",type:"u",default:"0"},cd:{name:"FrameNumber",level:"5",type:"u",default:"0"},cc:{name:"LaceNumber",level:"5",type:"u",minver:"1",default:"0",divx:"0"},e8:{name:"TimeSlice",level:"4",type:"m",multiple:"1",minver:"1",divx:"0"},"8e":{name:"Slices",level:"3",type:"m",minver:"1",divx:"0"},"75a2":{name:"DiscardPadding",level:"3",type:"i",minver:"4",webm:"1"},a4:{name:"CodecState",level:"3",type:"b",minver:"2",webm:"0"},fd:{name:"ReferenceVirtual",level:"3",type:"i",webm:"0"},fb:{name:"ReferenceBlock",level:"3",type:"i",multiple:"1",minver:"1"},fa:{name:"ReferencePriority",level:"3",type:"u",mandatory:"1",minver:"1",webm:"0",default:"0"},"9b":{name:"BlockDuration",level:"3",type:"u",minver:"1",default:"TrackDuration"},a5:{name:"BlockAdditional",level:"5",type:"b",mandatory:"1",minver:"1",webm:"0"},ee:{name:"BlockAddID",level:"5",type:"u",mandatory:"1",minver:"1",webm:"0",default:"1",range:"not 0"},a6:{name:"BlockMore",level:"4",type:"m",mandatory:"1",multiple:"1",minver:"1",webm:"0"},"75a1":{name:"BlockAdditions",level:"3",type:"m",minver:"1",webm:"0"},a2:{name:"BlockVirtual",level:"3",type:"b",webm:"0"},a1:{name:"Block",level:"3",type:"b",mandatory:"1",minver:"1"},a0:{name:"BlockGroup",level:"2",type:"m",multiple:"1",minver:"1"},a3:{name:"SimpleBlock",level:"2",type:"b",multiple:"1",minver:"2",webm:"1",divx:"1"},ab:{name:"PrevSize",level:"2",type:"u",minver:"1"},a7:{name:"Position",level:"2",type:"u",minver:"1",webm:"0"},"58d7":{name:"SilentTrackNumber",level:"3",type:"u",multiple:"1",minver:"1",webm:"0"},e7:{name:"Timecode",level:"2",type:"u",mandatory:"1",minver:"1"},"1f43b675":{name:"Cluster",level:"1",type:"m",multiple:"1",minver:"1"},"4d80":{name:"MuxingApp",level:"2",type:"8",mandatory:"1",minver:"1"},"7ba9":{name:"Title",level:"2",type:"8",minver:"1",webm:"0"},"2ad7b2":{name:"TimecodeScaleDenominator",level:"2",type:"u",mandatory:"1",minver:"4",default:"1000000000"},"2ad7b1":{name:"TimecodeScale",level:"2",type:"u",mandatory:"1",minver:"1",default:"1000000"},"69a5":{name:"ChapterTranslateID",level:"3",type:"b",mandatory:"1",minver:"1",webm:"0"},"69bf":{name:"ChapterTranslateCodec",level:"3",type:"u",mandatory:"1",minver:"1",webm:"0"},"69fc":{name:"ChapterTranslateEditionUID",level:"3",type:"u",multiple:"1",minver:"1",webm:"0"},"3e83bb":{name:"NextFilename",level:"2",type:"8",minver:"1",webm:"0"},"3eb923":{name:"NextUID",level:"2",type:"b",minver:"1",webm:"0",bytesize:"16"},"3c83ab":{name:"PrevFilename",level:"2",type:"8",minver:"1",webm:"0"},"3cb923":{name:"PrevUID",level:"2",type:"b",minver:"1",webm:"0",bytesize:"16"},"73a4":{name:"SegmentUID",level:"2",type:"b",minver:"1",webm:"0",range:"not 0",bytesize:"16"},"1549a966":{name:"Info",level:"1",type:"m",mandatory:"1",multiple:"1",minver:"1"},"53ac":{name:"SeekPosition",level:"3",type:"u",mandatory:"1",minver:"1"},"53ab":{name:"SeekID",level:"3",type:"b",mandatory:"1",minver:"1"},"4dbb":{name:"Seek",level:"2",type:"m",mandatory:"1",multiple:"1",minver:"1"},"114d9b74":{name:"SeekHead",level:"1",type:"m",multiple:"1",minver:"1"},"7e7b":{name:"SignatureElementList",level:"2",type:"m",multiple:"1",webm:"0",i:"Cluster|Block|BlockAdditional"},"7e5b":{name:"SignatureElements",level:"1",type:"m",webm:"0"},"7eb5":{name:"Signature",level:"1",type:"b",webm:"0"},"7ea5":{name:"SignaturePublicKey",level:"1",type:"b",webm:"0"},"7e9a":{name:"SignatureHash",level:"1",type:"u",webm:"0"},"7e8a":{name:"SignatureAlgo",level:"1",type:"u",webm:"0"},"1b538667":{name:"SignatureSlot",level:"-1",type:"m",multiple:"1",webm:"0"},bf:{name:"CRC-32",level:"-1",type:"b",minver:"1",webm:"0"},ec:{name:"Void",level:"-1",type:"b",minver:"1"},"42f3":{name:"EBMLMaxSizeLength",level:"1",type:"u",mandatory:"1",default:"8",minver:"1"},"42f2":{name:"EBMLMaxIDLength",level:"1",type:"u",mandatory:"1",default:"4",minver:"1"},"42f7":{name:"EBMLReadVersion",level:"1",type:"u",mandatory:"1",default:"1",minver:"1"},"1a45dfa3":{name:"EBML",level:"0",type:"m",mandatory:"1",multiple:"1",minver:"1"}};module.exports=schema;
},{}],13:[function(require,module,exports){
var Buffer = require("buffer").Buffer, tools = {
  readVint: function(buffer, start) {
    start = start || 0;
    var length = 8 - Math.floor(Math.log2(buffer[start]));
    if (length > 8) throw new Error("Unrepresentable length: " + length + " " + buffer.toString("hex", start, start + length));
    if (start + length > buffer.length) return null;
    for (var value = buffer[start] & (1 << 8 - length) - 1, i = 1; i < length; i++) {
      if (7 === i && value >= Math.pow(2, 45) && buffer[start + 7] > 0) return {
        length: length,
        value: -1
      };
      value *= Math.pow(2, 8);
      value += buffer[start + i];
    }
    return {
      length: length,
      value: value
    };
  },
  writeVint: function(value) {
    if (value < 0 || value > Math.pow(2, 53)) throw new Error("Unrepresentable value: " + value);
    for (var length = 1; length <= 8; length++) if (value < Math.pow(2, 7 * length) - 1) break;
    for (var buffer = new Buffer(length), i = 1; i <= length; i++) {
      value -= buffer[length - i] = 255 & value;
      value /= Math.pow(2, 8);
    }
    buffer[0] = buffer[0] | 1 << 8 - length;
    return buffer;
  }
};

module.exports = tools;
},{"buffer":10}],14:[function(require,module,exports){
var once = require("once"), noop = function() {}, eos = function(stream, opts, callback) {
  if ("function" === typeof opts) return eos(stream, null, opts);
  opts = opts || {};
  callback = once(callback || noop);
  function onlegacyfinish() {
    stream.writable || onfinish();
  }
  function onend() {
    readable = !1;
    writable || callback.call(stream);
  }
  function onexit(exitCode) {
    callback.call(stream, exitCode ? new Error("exited with error code: " + exitCode) : null);
  }
  function onerror(err) {
    callback.call(stream, err);
  }
  function onclose() {
    vsNT(onclosenexttick);
  }
  function onrequest() {
    stream.req.on("finish", onfinish);
  }
  function onfinish() {
    writable = !1;
    readable || callback.call(stream);
  }
  function onclosenexttick() {
    if (!cancelled) return (!readable || rs && rs.ended) && (!writable || ws && ws.ended && !ws.destroyed) ? void 0 : callback.call(stream, new Error("premature close"));
  }
  var ws = stream._writableState, rs = stream._readableState, readable = opts.readable || !1 !== opts.readable && stream.readable, writable = opts.writable || !1 !== opts.writable && stream.writable, cancelled = !1;
  if (writable && !ws) {
    stream.on("end", onlegacyfinish);
    stream.on("close", onlegacyfinish);
  }
  stream.on("end", onend);
  stream.on("finish", onfinish);
  !1 !== opts.error && stream.on("error", onerror);
  stream.on("close", onclose);
  return function() {
    cancelled = !0;
    stream.removeListener("complete", onfinish);
    stream.removeListener("abort", onclose);
    stream.removeListener("request", onrequest);
    stream.req && stream.req.removeListener("finish", onfinish);
    stream.removeListener("end", onlegacyfinish);
    stream.removeListener("close", onlegacyfinish);
    stream.removeListener("finish", onfinish);
    stream.removeListener("exit", onexit);
    stream.removeListener("end", onend);
    stream.removeListener("error", onerror);
    stream.removeListener("close", onclose);
  };
};

module.exports = eos;
},{"once":25}],15:[function(require,module,exports){
"use strict";

var has = Object.prototype.hasOwnProperty, prefix = "~";

function Events() {}

if (Object.create) {
  Events.prototype = Object.create(null);
  new Events().__proto__ || (prefix = !1);
}

function EE(fn, context, once) {
  this.fn = fn;
  this.context = context;
  this.once = once || !1;
}

function addListener(emitter, event, fn, context, once, pp) {
  if ("function" !== typeof fn) throw new TypeError("The listener must be a function");
  var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
  emitter._events[evt] ? emitter._events[evt].fn ? emitter._events[evt] = pp ? [ listener, emitter._events[evt] ] : [ emitter._events[evt], listener ] : emitter._events[evt][pp ? "unshift" : "push"](listener) : (emitter._events[evt] = listener, 
  emitter._eventsCount++);
  return emitter;
}

function clearEvent(emitter, evt) {
  0 === --emitter._eventsCount ? emitter._events = new Events() : delete emitter._events[evt];
}

function EventEmitter() {
  this._events = new Events();
  this._eventsCount = 0;
}

EventEmitter.prototype.eventNames = function() {
  var events, name, names = [];
  if (0 === this._eventsCount) return names;
  for (name in events = this._events) has.call(events, name) && names.push(prefix ? name.slice(1) : name);
  return Object.getOwnPropertySymbols ? names.concat(Object.getOwnPropertySymbols(events)) : names;
};

EventEmitter.prototype.listeners = function(event) {
  var handlers = this._events[prefix ? prefix + event : event];
  if (!handlers) return [];
  if (handlers.fn) return [ handlers.fn ];
  for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) ee[i] = handlers[i].fn;
  return ee;
};

EventEmitter.prototype.listenerCount = function(event) {
  var listeners = this._events[prefix ? prefix + event : event];
  return listeners ? listeners.fn ? 1 : listeners.length : 0;
};

EventEmitter.prototype.emit = function(event, a1, a2, a3, a4, a5) {
  var evt = prefix ? prefix + event : event;
  if (!this._events[evt]) return !1;
  var args, listeners = this._events[evt], len = arguments.length;
  if (listeners.fn) {
    listeners.once && this.removeListener(event, listeners.fn, void 0, !0);
    switch (len) {
     case 1:
      return listeners.fn.call(listeners.context), !0;

     case 2:
      return listeners.fn.call(listeners.context, a1), !0;

     case 3:
      return listeners.fn.call(listeners.context, a1, a2), !0;

     case 4:
      return listeners.fn.call(listeners.context, a1, a2, a3), !0;

     case 5:
      return listeners.fn.call(listeners.context, a1, a2, a3, a4), !0;

     case 6:
      return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), !0;
    }
    for (i = 1, args = new Array(len - 1); i < len; i++) args[i - 1] = arguments[i];
    listeners.fn.apply(listeners.context, args);
  } else for (var j, length = listeners.length, i = 0; i < length; i++) {
    listeners[i].once && this.removeListener(event, listeners[i].fn, void 0, !0);
    switch (len) {
     case 1:
      listeners[i].fn.call(listeners[i].context);
      break;

     case 2:
      listeners[i].fn.call(listeners[i].context, a1);
      break;

     case 3:
      listeners[i].fn.call(listeners[i].context, a1, a2);
      break;

     case 4:
      listeners[i].fn.call(listeners[i].context, a1, a2, a3);
      break;

     default:
      if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) args[j - 1] = arguments[j];
      listeners[i].fn.apply(listeners[i].context, args);
    }
  }
  return !0;
};

EventEmitter.prototype.on = function(event, fn, context, pp) {
  return addListener(this, event, fn, context, !1, pp);
};

EventEmitter.prototype.once = function(event, fn, context) {
  return addListener(this, event, fn, context, !0);
};

EventEmitter.prototype.removeListener = function(event, fn, context, once) {
  var evt = prefix ? prefix + event : event;
  if (!this._events[evt]) return this;
  if (!fn) {
    clearEvent(this, evt);
    return this;
  }
  var listeners = this._events[evt];
  if (listeners.fn) listeners.fn !== fn || once && !listeners.once || context && listeners.context !== context || clearEvent(this, evt); else {
    for (var i = 0, events = [], length = listeners.length; i < length; i++) (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) && events.push(listeners[i]);
    events.length ? this._events[evt] = 1 === events.length ? events[0] : events : clearEvent(this, evt);
  }
  return this;
};

EventEmitter.prototype.removeAllListeners = function(event) {
  var evt;
  if (event) this._events[evt = prefix ? prefix + event : event] && clearEvent(this, evt); else {
    this._events = new Events();
    this._eventsCount = 0;
  }
  return this;
};

EventEmitter.prototype.off = EventEmitter.prototype.removeListener;

EventEmitter.prototype.addListener = EventEmitter.prototype.on;

EventEmitter.prefixed = prefix;

EventEmitter.EventEmitter = EventEmitter;

"undefined" !== typeof module && (module.exports = EventEmitter);
},{}],16:[function(require,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
  var e, m, eLen = 8 * nBytes - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? nBytes - 1 : 0, d = isLE ? -1 : 1, s = buffer[offset + i];
  i += d;
  e = s & (1 << -nBits) - 1;
  s >>= -nBits;
  nBits += eLen;
  for (;nBits > 0; e = 256 * e + buffer[offset + i], i += d, nBits -= 8) ;
  m = e & (1 << -nBits) - 1;
  e >>= -nBits;
  nBits += mLen;
  for (;nBits > 0; m = 256 * m + buffer[offset + i], i += d, nBits -= 8) ;
  if (0 === e) e = 1 - eBias; else {
    if (e === eMax) return m ? NaN : Infinity * (s ? -1 : 1);
    m += Math.pow(2, mLen);
    e -= eBias;
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};

exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c, eLen = 8 * nBytes - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = 23 === mLen ? Math.pow(2, -24) - Math.pow(2, -77) : 0, i = isLE ? 0 : nBytes - 1, d = isLE ? 1 : -1, s = value < 0 || 0 === value && 1 / value < 0 ? 1 : 0;
  value = Math.abs(value);
  if (isNaN(value) || Infinity === value) {
    m = isNaN(value) ? 1 : 0;
    e = eMax;
  } else {
    e = Math.floor(Math.log(value) / Math.LN2);
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--;
      c *= 2;
    }
    if ((value += e + eBias >= 1 ? rt / c : rt * Math.pow(2, 1 - eBias)) * c >= 2) {
      e++;
      c /= 2;
    }
    if (e + eBias >= eMax) {
      m = 0;
      e = eMax;
    } else if (e + eBias >= 1) {
      m = (value * c - 1) * Math.pow(2, mLen);
      e += eBias;
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
      e = 0;
    }
  }
  for (;mLen >= 8; buffer[offset + i] = 255 & m, i += d, m /= 256, mLen -= 8) ;
  e = e << mLen | m;
  eLen += mLen;
  for (;eLen > 0; buffer[offset + i] = 255 & e, i += d, e /= 256, eLen -= 8) ;
  buffer[offset + i - d] |= 128 * s;
};
},{}],17:[function(require,module,exports){
module.exports = MediaElementWrapper;

var inherits = require("/bundle/utils").inherit, stream = require("readable-stream"), toArrayBuffer = require("to-arraybuffer"), MediaSource = "undefined" !== typeof window && window.MediaSource, DEFAULT_BUFFER_DURATION = 60;

function MediaElementWrapper(elem, opts) {
  var self = this;
  if (!(self instanceof MediaElementWrapper)) return new MediaElementWrapper(elem, opts);
  if (!MediaSource) throw new Error("web browser lacks MediaSource support");
  self._debug = (opts = opts || {}).debug;
  self._bufferDuration = opts.bufferDuration || DEFAULT_BUFFER_DURATION;
  self._elem = elem;
  self._mediaSource = new MediaSource();
  self._streams = [];
  self.detailedError = null;
  self._errorHandler = function() {
    self._elem.removeEventListener("error", self._errorHandler);
    self._streams.slice().forEach(function(stream) {
      stream.destroy(self._elem.error);
    });
  };
  self._elem.addEventListener("error", self._errorHandler);
  self._elem.src = window.URL.createObjectURL(self._mediaSource);
}

MediaElementWrapper.prototype.createWriteStream = function(obj) {
  return new MediaSourceStream(this, obj);
};

MediaElementWrapper.prototype.error = function(err) {
  this.detailedError || (this.detailedError = err);
  this._dumpDebugData();
  try {
    this._mediaSource.endOfStream("decode");
  } catch (err) {}
  try {
    window.URL.revokeObjectURL(this._elem.src);
  } catch (err) {}
};

MediaElementWrapper.prototype._dumpDebugData = function() {
  if (this._debug) {
    this._debug = !1;
    this._streams.forEach(function(stream, i) {
      downloadBuffers(stream._debugBuffers, "mediasource-stream-" + i);
    });
  }
};

inherits(MediaSourceStream, stream.Writable);

function MediaSourceStream(wrapper, obj) {
  var self = this;
  stream.Writable.call(self);
  self._wrapper = wrapper;
  self._elem = wrapper._elem;
  self._mediaSource = wrapper._mediaSource;
  self._allStreams = wrapper._streams;
  self._allStreams.push(self);
  self._bufferDuration = wrapper._bufferDuration;
  self._sourceBuffer = null;
  self._debugBuffers = [];
  self._openHandler = function() {
    self._onSourceOpen();
  };
  self._flowHandler = function() {
    self._flow();
  };
  self._errorHandler = function(err) {
    self.destroyed || self.emit("error", err);
  };
  if ("string" === typeof obj) {
    self._type = obj;
    "open" === self._mediaSource.readyState ? self._createSourceBuffer() : self._mediaSource.addEventListener("sourceopen", self._openHandler);
  } else if (null === obj._sourceBuffer) {
    obj.destroy();
    self._type = obj._type;
    self._mediaSource.addEventListener("sourceopen", self._openHandler);
  } else {
    if (!obj._sourceBuffer) throw new Error("The argument to MediaElementWrapper.createWriteStream must be a string or a previous stream returned from that function");
    obj.destroy();
    self._type = obj._type;
    self._sourceBuffer = obj._sourceBuffer;
    self._debugBuffers = obj._debugBuffers;
    self._sourceBuffer.addEventListener("updateend", self._flowHandler);
    self._sourceBuffer.addEventListener("error", self._errorHandler);
  }
  self._elem.addEventListener("timeupdate", self._flowHandler);
  self.on("error", function(err) {
    self._wrapper.error(err);
  });
  self.on("finish", function() {
    if (!self.destroyed) {
      self._finished = !0;
      if (self._allStreams.every(function(other) {
        return other._finished;
      })) {
        self._wrapper._dumpDebugData();
        try {
          self._mediaSource.endOfStream();
        } catch (err) {}
      }
    }
  });
}

MediaSourceStream.prototype._onSourceOpen = function() {
  if (!this.destroyed) {
    this._mediaSource.removeEventListener("sourceopen", this._openHandler);
    this._createSourceBuffer();
  }
};

MediaSourceStream.prototype.destroy = function(err) {
  if (!this.destroyed) {
    this.destroyed = !0;
    this._allStreams.splice(this._allStreams.indexOf(this), 1);
    this._mediaSource.removeEventListener("sourceopen", this._openHandler);
    this._elem.removeEventListener("timeupdate", this._flowHandler);
    if (this._sourceBuffer) {
      this._sourceBuffer.removeEventListener("updateend", this._flowHandler);
      this._sourceBuffer.removeEventListener("error", this._errorHandler);
      "open" === this._mediaSource.readyState && this._sourceBuffer.abort();
    }
    err && this.emit("error", err);
    this.emit("close");
  }
};

MediaSourceStream.prototype._createSourceBuffer = function() {
  if (!this.destroyed) if (MediaSource.isTypeSupported(this._type)) {
    this._sourceBuffer = this._mediaSource.addSourceBuffer(this._type);
    this._sourceBuffer.addEventListener("updateend", this._flowHandler);
    this._sourceBuffer.addEventListener("error", this._errorHandler);
    if (this._cb) {
      var cb = this._cb;
      this._cb = null;
      cb();
    }
  } else onIdle(this.destroy.bind(this, new Error("The provided type is not supported")));
};

MediaSourceStream.prototype._write = function(chunk, encoding, cb) {
  var self = this;
  if (!self.destroyed) if (self._sourceBuffer) {
    if (self._sourceBuffer.updating) return cb(new Error("Cannot append buffer while source buffer updating"));
    var arr = toArrayBuffer(chunk);
    self._wrapper._debug && self._debugBuffers.push(arr);
    try {
      self._sourceBuffer.appendBuffer(arr);
    } catch (err) {
      self.destroy(err);
      return;
    }
    self._cb = cb;
  } else self._cb = function(err) {
    if (err) return cb(err);
    self._write(chunk, encoding, cb);
  };
};

MediaSourceStream.prototype._flow = function() {
  if (!this.destroyed && this._sourceBuffer && !this._sourceBuffer.updating && !("open" === this._mediaSource.readyState && this._getBufferDuration() > this._bufferDuration) && this._cb) {
    var cb = this._cb;
    this._cb = null;
    cb();
  }
};

var EPSILON = 0;

MediaSourceStream.prototype._getBufferDuration = function() {
  for (var buffered = this._sourceBuffer.buffered, currentTime = this._elem.currentTime, bufferEnd = -1, i = 0; i < buffered.length; i++) {
    var start = buffered.start(i), end = buffered.end(i) + EPSILON;
    if (start > currentTime) break;
    (bufferEnd >= 0 || currentTime <= end) && (bufferEnd = end);
  }
  var bufferedTime = bufferEnd - currentTime;
  bufferedTime < 0 && (bufferedTime = 0);
  return bufferedTime;
};

function downloadBuffers(bufs, name) {
  var a = document.createElement("a");
  a.href = window.URL.createObjectURL(new window.Blob(bufs));
  a.download = name;
  a.click();
}
},{"/bundle/utils":4,"readable-stream":41,"to-arraybuffer":43}],18:[function(require,module,exports){
var Buffer = require("buffer").Buffer, Box = require("./index"), Descriptor = require("./descriptor"), uint64be = require("uint64be"), TIME_OFFSET = 20828448e5;

exports.fullBoxes = {};

var fullBoxes = [ "mvhd", "tkhd", "mdhd", "vmhd", "smhd", "stsd", "esds", "stsz", "stco", "co64", "stss", "stts", "ctts", "stsc", "dref", "elst", "hdlr", "mehd", "trex", "mfhd", "tfhd", "tfdt", "trun" ];

fullBoxes.forEach(function(type) {
  exports.fullBoxes[type] = !0;
});

exports.ftyp = {};

exports.ftyp.encode = function(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.ftyp.encodingLength(box));
  var brands = box.compatibleBrands || [];
  buf.write(box.brand, 0, 4, "ascii");
  buf.writeUInt32BE(box.brandVersion, 4);
  for (var i = 0; i < brands.length; i++) buf.write(brands[i], 8 + 4 * i, 4, "ascii");
  exports.ftyp.encode.bytes = 8 + 4 * brands.length;
  return buf;
};

exports.ftyp.decode = function(buf, offset) {
  for (var brand = (buf = buf.slice(offset)).toString("ascii", 0, 4), version = buf.readUInt32BE(4), compatibleBrands = [], i = 8; i < buf.length; i += 4) compatibleBrands.push(buf.toString("ascii", i, i + 4));
  return {
    brand: brand,
    brandVersion: version,
    compatibleBrands: compatibleBrands
  };
};

exports.ftyp.encodingLength = function(box) {
  return 8 + 4 * (box.compatibleBrands || []).length;
};

exports.mvhd = {};

exports.mvhd.encode = function(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(96);
  writeDate(box.ctime || new Date(), buf, 0);
  writeDate(box.mtime || new Date(), buf, 4);
  buf.writeUInt32BE(box.timeScale || 0, 8);
  buf.writeUInt32BE(box.duration || 0, 12);
  writeFixed32(box.preferredRate || 0, buf, 16);
  writeFixed16(box.preferredVolume || 0, buf, 20);
  writeReserved(buf, 22, 32);
  writeMatrix(box.matrix, buf, 32);
  buf.writeUInt32BE(box.previewTime || 0, 68);
  buf.writeUInt32BE(box.previewDuration || 0, 72);
  buf.writeUInt32BE(box.posterTime || 0, 76);
  buf.writeUInt32BE(box.selectionTime || 0, 80);
  buf.writeUInt32BE(box.selectionDuration || 0, 84);
  buf.writeUInt32BE(box.currentTime || 0, 88);
  buf.writeUInt32BE(box.nextTrackId || 0, 92);
  exports.mvhd.encode.bytes = 96;
  return buf;
};

exports.mvhd.decode = function(buf, offset) {
  return {
    ctime: readDate(buf = buf.slice(offset), 0),
    mtime: readDate(buf, 4),
    timeScale: buf.readUInt32BE(8),
    duration: buf.readUInt32BE(12),
    preferredRate: readFixed32(buf, 16),
    preferredVolume: readFixed16(buf, 20),
    matrix: readMatrix(buf.slice(32, 68)),
    previewTime: buf.readUInt32BE(68),
    previewDuration: buf.readUInt32BE(72),
    posterTime: buf.readUInt32BE(76),
    selectionTime: buf.readUInt32BE(80),
    selectionDuration: buf.readUInt32BE(84),
    currentTime: buf.readUInt32BE(88),
    nextTrackId: buf.readUInt32BE(92)
  };
};

exports.mvhd.encodingLength = function(box) {
  return 96;
};

exports.tkhd = {};

exports.tkhd.encode = function(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(80);
  writeDate(box.ctime || new Date(), buf, 0);
  writeDate(box.mtime || new Date(), buf, 4);
  buf.writeUInt32BE(box.trackId || 0, 8);
  writeReserved(buf, 12, 16);
  buf.writeUInt32BE(box.duration || 0, 16);
  writeReserved(buf, 20, 28);
  buf.writeUInt16BE(box.layer || 0, 28);
  buf.writeUInt16BE(box.alternateGroup || 0, 30);
  buf.writeUInt16BE(box.volume || 0, 32);
  writeMatrix(box.matrix, buf, 36);
  buf.writeUInt32BE(box.trackWidth || 0, 72);
  buf.writeUInt32BE(box.trackHeight || 0, 76);
  exports.tkhd.encode.bytes = 80;
  return buf;
};

exports.tkhd.decode = function(buf, offset) {
  return {
    ctime: readDate(buf = buf.slice(offset), 0),
    mtime: readDate(buf, 4),
    trackId: buf.readUInt32BE(8),
    duration: buf.readUInt32BE(16),
    layer: buf.readUInt16BE(28),
    alternateGroup: buf.readUInt16BE(30),
    volume: buf.readUInt16BE(32),
    matrix: readMatrix(buf.slice(36, 72)),
    trackWidth: buf.readUInt32BE(72),
    trackHeight: buf.readUInt32BE(76)
  };
};

exports.tkhd.encodingLength = function(box) {
  return 80;
};

exports.mdhd = {};

exports.mdhd.encode = function(box, buf, offset) {
  if (1 === box.version) {
    buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(32);
    writeDate64(box.ctime || new Date(), buf, 0);
    writeDate64(box.mtime || new Date(), buf, 8);
    buf.writeUInt32BE(box.timeScale || 0, 16);
    buf.writeUIntBE(box.duration || 0, 20, 6);
    buf.writeUInt16BE(box.language || 0, 28);
    buf.writeUInt16BE(box.quality || 0, 30);
    exports.mdhd.encode.bytes = 32;
    return buf;
  }
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(20);
  writeDate(box.ctime || new Date(), buf, 0);
  writeDate(box.mtime || new Date(), buf, 4);
  buf.writeUInt32BE(box.timeScale || 0, 8);
  buf.writeUInt32BE(box.duration || 0, 12);
  buf.writeUInt16BE(box.language || 0, 16);
  buf.writeUInt16BE(box.quality || 0, 18);
  exports.mdhd.encode.bytes = 20;
  return buf;
};

exports.mdhd.decode = function(buf, offset, end) {
  buf = buf.slice(offset);
  return end - offset !== 20 ? {
    ctime: readDate64(buf, 0),
    mtime: readDate64(buf, 8),
    timeScale: buf.readUInt32BE(16),
    duration: buf.readUIntBE(20, 6),
    language: buf.readUInt16BE(28),
    quality: buf.readUInt16BE(30)
  } : {
    ctime: readDate(buf, 0),
    mtime: readDate(buf, 4),
    timeScale: buf.readUInt32BE(8),
    duration: buf.readUInt32BE(12),
    language: buf.readUInt16BE(16),
    quality: buf.readUInt16BE(18)
  };
};

exports.mdhd.encodingLength = function(box) {
  return 1 === box.version ? 32 : 20;
};

exports.vmhd = {};

exports.vmhd.encode = function(box, buf, offset) {
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(8)).writeUInt16BE(box.graphicsMode || 0, 0);
  var opcolor = box.opcolor || [ 0, 0, 0 ];
  buf.writeUInt16BE(opcolor[0], 2);
  buf.writeUInt16BE(opcolor[1], 4);
  buf.writeUInt16BE(opcolor[2], 6);
  exports.vmhd.encode.bytes = 8;
  return buf;
};

exports.vmhd.decode = function(buf, offset) {
  return {
    graphicsMode: (buf = buf.slice(offset)).readUInt16BE(0),
    opcolor: [ buf.readUInt16BE(2), buf.readUInt16BE(4), buf.readUInt16BE(6) ]
  };
};

exports.vmhd.encodingLength = function(box) {
  return 8;
};

exports.smhd = {};

exports.smhd.encode = function(box, buf, offset) {
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(4)).writeUInt16BE(box.balance || 0, 0);
  writeReserved(buf, 2, 4);
  exports.smhd.encode.bytes = 4;
  return buf;
};

exports.smhd.decode = function(buf, offset) {
  return {
    balance: (buf = buf.slice(offset)).readUInt16BE(0)
  };
};

exports.smhd.encodingLength = function(box) {
  return 4;
};

exports.stsd = {};

exports.stsd.encode = function(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.stsd.encodingLength(box));
  var entries = box.entries || [];
  buf.writeUInt32BE(entries.length, 0);
  for (var ptr = 4, i = 0; i < entries.length; i++) {
    Box.encode(entries[i], buf, ptr);
    ptr += Box.encode.bytes;
  }
  exports.stsd.encode.bytes = ptr;
  return buf;
};

exports.stsd.decode = function(buf, offset, end) {
  for (var num = (buf = buf.slice(offset)).readUInt32BE(0), entries = new Array(num), ptr = 4, i = 0; i < num; i++) {
    var entry = Box.decode(buf, ptr, end);
    ptr += (entries[i] = entry).length;
  }
  return {
    entries: entries
  };
};

exports.stsd.encodingLength = function(box) {
  var totalSize = 4;
  if (!box.entries) return totalSize;
  for (var i = 0; i < box.entries.length; i++) totalSize += Box.encodingLength(box.entries[i]);
  return totalSize;
};

exports.avc1 = exports.VisualSampleEntry = {};

exports.VisualSampleEntry.encode = function(box, buf, offset) {
  writeReserved(buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.VisualSampleEntry.encodingLength(box)), 0, 6);
  buf.writeUInt16BE(box.dataReferenceIndex || 0, 6);
  writeReserved(buf, 8, 24);
  buf.writeUInt16BE(box.width || 0, 24);
  buf.writeUInt16BE(box.height || 0, 26);
  buf.writeUInt32BE(box.hResolution || 4718592, 28);
  buf.writeUInt32BE(box.vResolution || 4718592, 32);
  writeReserved(buf, 36, 40);
  buf.writeUInt16BE(box.frameCount || 1, 40);
  var compressorName = box.compressorName || "", nameLen = Math.min(compressorName.length, 31);
  buf.writeUInt8(nameLen, 42);
  buf.write(compressorName, 43, nameLen, "utf8");
  buf.writeUInt16BE(box.depth || 24, 74);
  buf.writeInt16BE(-1, 76);
  var ptr = 78;
  (box.children || []).forEach(function(child) {
    Box.encode(child, buf, ptr);
    ptr += Box.encode.bytes;
  });
  exports.VisualSampleEntry.encode.bytes = ptr;
};

exports.VisualSampleEntry.decode = function(buf, offset, end) {
  buf = buf.slice(offset);
  var length = end - offset, nameLen = Math.min(buf.readUInt8(42), 31), box = {
    dataReferenceIndex: buf.readUInt16BE(6),
    width: buf.readUInt16BE(24),
    height: buf.readUInt16BE(26),
    hResolution: buf.readUInt32BE(28),
    vResolution: buf.readUInt32BE(32),
    frameCount: buf.readUInt16BE(40),
    compressorName: buf.toString("utf8", 43, 43 + nameLen),
    depth: buf.readUInt16BE(74),
    children: []
  }, ptr = 78;
  while (length - ptr >= 8) {
    var child = Box.decode(buf, ptr, length);
    box.children.push(child);
    ptr += (box[child.type] = child).length;
  }
  return box;
};

exports.VisualSampleEntry.encodingLength = function(box) {
  var len = 78;
  (box.children || []).forEach(function(child) {
    len += Box.encodingLength(child);
  });
  return len;
};

exports.avcC = {};

exports.avcC.encode = function(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(box.buffer.length);
  box.buffer.copy(buf);
  exports.avcC.encode.bytes = box.buffer.length;
};

exports.avcC.decode = function(buf, offset, end) {
  return {
    mimeCodec: (buf = buf.slice(offset, end)).toString("hex", 1, 4),
    buffer: Buffer.from(buf)
  };
};

exports.avcC.encodingLength = function(box) {
  return box.buffer.length;
};

exports.mp4a = exports.AudioSampleEntry = {};

exports.AudioSampleEntry.encode = function(box, buf, offset) {
  writeReserved(buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.AudioSampleEntry.encodingLength(box)), 0, 6);
  buf.writeUInt16BE(box.dataReferenceIndex || 0, 6);
  writeReserved(buf, 8, 16);
  buf.writeUInt16BE(box.channelCount || 2, 16);
  buf.writeUInt16BE(box.sampleSize || 16, 18);
  writeReserved(buf, 20, 24);
  buf.writeUInt32BE(box.sampleRate || 0, 24);
  var ptr = 28;
  (box.children || []).forEach(function(child) {
    Box.encode(child, buf, ptr);
    ptr += Box.encode.bytes;
  });
  exports.AudioSampleEntry.encode.bytes = ptr;
};

exports.AudioSampleEntry.decode = function(buf, offset, end) {
  var length = end - offset, box = {
    dataReferenceIndex: (buf = buf.slice(offset, end)).readUInt16BE(6),
    channelCount: buf.readUInt16BE(16),
    sampleSize: buf.readUInt16BE(18),
    sampleRate: buf.readUInt32BE(24),
    children: []
  }, ptr = 28;
  while (length - ptr >= 8) {
    var child = Box.decode(buf, ptr, length);
    box.children.push(child);
    ptr += (box[child.type] = child).length;
  }
  return box;
};

exports.AudioSampleEntry.encodingLength = function(box) {
  var len = 28;
  (box.children || []).forEach(function(child) {
    len += Box.encodingLength(child);
  });
  return len;
};

exports.esds = {};

exports.esds.encode = function(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(box.buffer.length);
  box.buffer.copy(buf, 0);
  exports.esds.encode.bytes = box.buffer.length;
};

exports.esds.decode = function(buf, offset, end) {
  buf = buf.slice(offset, end);
  var desc = Descriptor.Descriptor.decode(buf, 0, buf.length), dcd = ("ESDescriptor" === desc.tagName ? desc : {}).DecoderConfigDescriptor || {}, oti = dcd.oti || 0, dsi = dcd.DecoderSpecificInfo, audioConfig = dsi ? (248 & dsi.buffer.readUInt8(0)) >> 3 : 0, mimeCodec = null;
  if (oti) {
    mimeCodec = oti.toString(16);
    audioConfig && (mimeCodec += "." + audioConfig);
  }
  return {
    mimeCodec: mimeCodec,
    buffer: Buffer.from(buf.slice(0))
  };
};

exports.esds.encodingLength = function(box) {
  return box.buffer.length;
};

exports.stsz = {};

exports.stsz.encode = function(box, buf, offset) {
  var entries = box.entries || [];
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.stsz.encodingLength(box))).writeUInt32BE(0, 0);
  buf.writeUInt32BE(entries.length, 4);
  for (var i = 0; i < entries.length; i++) buf.writeUInt32BE(entries[i], 4 * i + 8);
  exports.stsz.encode.bytes = 8 + 4 * entries.length;
  return buf;
};

exports.stsz.decode = function(buf, offset) {
  for (var size = (buf = buf.slice(offset)).readUInt32BE(0), num = buf.readUInt32BE(4), entries = new Array(num), i = 0; i < num; i++) entries[i] = 0 === size ? buf.readUInt32BE(4 * i + 8) : size;
  return {
    entries: entries
  };
};

exports.stsz.encodingLength = function(box) {
  return 8 + 4 * box.entries.length;
};

exports.stss = exports.stco = {};

exports.stco.encode = function(box, buf, offset) {
  var entries = box.entries || [];
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.stco.encodingLength(box))).writeUInt32BE(entries.length, 0);
  for (var i = 0; i < entries.length; i++) buf.writeUInt32BE(entries[i], 4 * i + 4);
  exports.stco.encode.bytes = 4 + 4 * entries.length;
  return buf;
};

exports.stco.decode = function(buf, offset) {
  for (var num = (buf = buf.slice(offset)).readUInt32BE(0), entries = new Array(num), i = 0; i < num; i++) entries[i] = buf.readUInt32BE(4 * i + 4);
  return {
    entries: entries
  };
};

exports.stco.encodingLength = function(box) {
  return 4 + 4 * box.entries.length;
};

exports.co64 = {};

exports.co64.encode = function(box, buf, offset) {
  var entries = box.entries || [];
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.co64.encodingLength(box))).writeUInt32BE(entries.length, 0);
  for (var i = 0; i < entries.length; i++) uint64be.encode(entries[i], buf, 8 * i + 4);
  exports.co64.encode.bytes = 4 + 8 * entries.length;
  return buf;
};

exports.co64.decode = function(buf, offset) {
  for (var num = (buf = buf.slice(offset)).readUInt32BE(0), entries = new Array(num), i = 0; i < num; i++) entries[i] = uint64be.decode(buf, 8 * i + 4);
  return {
    entries: entries
  };
};

exports.co64.encodingLength = function(box) {
  return 4 + 8 * box.entries.length;
};

exports.stts = {};

exports.stts.encode = function(box, buf, offset) {
  var entries = box.entries || [];
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.stts.encodingLength(box))).writeUInt32BE(entries.length, 0);
  for (var i = 0; i < entries.length; i++) {
    var ptr = 8 * i + 4;
    buf.writeUInt32BE(entries[i].count || 0, ptr);
    buf.writeUInt32BE(entries[i].duration || 0, 4 + ptr);
  }
  exports.stts.encode.bytes = 4 + 8 * box.entries.length;
  return buf;
};

exports.stts.decode = function(buf, offset) {
  for (var num = (buf = buf.slice(offset)).readUInt32BE(0), entries = new Array(num), i = 0; i < num; i++) {
    var ptr = 8 * i + 4;
    entries[i] = {
      count: buf.readUInt32BE(ptr),
      duration: buf.readUInt32BE(4 + ptr)
    };
  }
  return {
    entries: entries
  };
};

exports.stts.encodingLength = function(box) {
  return 4 + 8 * box.entries.length;
};

exports.ctts = {};

exports.ctts.encode = function(box, buf, offset) {
  var entries = box.entries || [];
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.ctts.encodingLength(box))).writeUInt32BE(entries.length, 0);
  for (var i = 0; i < entries.length; i++) {
    var ptr = 8 * i + 4;
    buf.writeUInt32BE(entries[i].count || 0, ptr);
    buf.writeUInt32BE(entries[i].compositionOffset || 0, 4 + ptr);
  }
  exports.ctts.encode.bytes = 4 + 8 * entries.length;
  return buf;
};

exports.ctts.decode = function(buf, offset) {
  for (var num = (buf = buf.slice(offset)).readUInt32BE(0), entries = new Array(num), i = 0; i < num; i++) {
    var ptr = 8 * i + 4;
    entries[i] = {
      count: buf.readUInt32BE(ptr),
      compositionOffset: buf.readInt32BE(4 + ptr)
    };
  }
  return {
    entries: entries
  };
};

exports.ctts.encodingLength = function(box) {
  return 4 + 8 * box.entries.length;
};

exports.stsc = {};

exports.stsc.encode = function(box, buf, offset) {
  var entries = box.entries || [];
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.stsc.encodingLength(box))).writeUInt32BE(entries.length, 0);
  for (var i = 0; i < entries.length; i++) {
    var ptr = 12 * i + 4;
    buf.writeUInt32BE(entries[i].firstChunk || 0, ptr);
    buf.writeUInt32BE(entries[i].samplesPerChunk || 0, 4 + ptr);
    buf.writeUInt32BE(entries[i].sampleDescriptionId || 0, 8 + ptr);
  }
  exports.stsc.encode.bytes = 4 + 12 * entries.length;
  return buf;
};

exports.stsc.decode = function(buf, offset) {
  for (var num = (buf = buf.slice(offset)).readUInt32BE(0), entries = new Array(num), i = 0; i < num; i++) {
    var ptr = 12 * i + 4;
    entries[i] = {
      firstChunk: buf.readUInt32BE(ptr),
      samplesPerChunk: buf.readUInt32BE(4 + ptr),
      sampleDescriptionId: buf.readUInt32BE(8 + ptr)
    };
  }
  return {
    entries: entries
  };
};

exports.stsc.encodingLength = function(box) {
  return 4 + 12 * box.entries.length;
};

exports.dref = {};

exports.dref.encode = function(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.dref.encodingLength(box));
  var entries = box.entries || [];
  buf.writeUInt32BE(entries.length, 0);
  for (var ptr = 4, i = 0; i < entries.length; i++) {
    var entry = entries[i];
    buf.writeUInt32BE((entry.buf ? entry.buf.length : 0) + 4 + 4, ptr);
    buf.write(entry.type, ptr += 4, 4, "ascii");
    ptr += 4;
    if (entry.buf) {
      entry.buf.copy(buf, ptr);
      ptr += entry.buf.length;
    }
  }
  exports.dref.encode.bytes = ptr;
  return buf;
};

exports.dref.decode = function(buf, offset) {
  for (var num = (buf = buf.slice(offset)).readUInt32BE(0), entries = new Array(num), ptr = 4, i = 0; i < num; i++) {
    var size = buf.readUInt32BE(ptr), type = buf.toString("ascii", ptr + 4, ptr + 8), tmp = buf.slice(ptr + 8, ptr + size);
    ptr += size;
    entries[i] = {
      type: type,
      buf: tmp
    };
  }
  return {
    entries: entries
  };
};

exports.dref.encodingLength = function(box) {
  var totalSize = 4;
  if (!box.entries) return totalSize;
  for (var i = 0; i < box.entries.length; i++) {
    var buf = box.entries[i].buf;
    totalSize += (buf ? buf.length : 0) + 4 + 4;
  }
  return totalSize;
};

exports.elst = {};

exports.elst.encode = function(box, buf, offset) {
  var entries = box.entries || [];
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.elst.encodingLength(box))).writeUInt32BE(entries.length, 0);
  for (var i = 0; i < entries.length; i++) {
    var ptr = 12 * i + 4;
    buf.writeUInt32BE(entries[i].trackDuration || 0, ptr);
    buf.writeUInt32BE(entries[i].mediaTime || 0, 4 + ptr);
    writeFixed32(entries[i].mediaRate || 0, buf, 8 + ptr);
  }
  exports.elst.encode.bytes = 4 + 12 * entries.length;
  return buf;
};

exports.elst.decode = function(buf, offset) {
  for (var num = (buf = buf.slice(offset)).readUInt32BE(0), entries = new Array(num), i = 0; i < num; i++) {
    var ptr = 12 * i + 4;
    entries[i] = {
      trackDuration: buf.readUInt32BE(ptr),
      mediaTime: buf.readInt32BE(4 + ptr),
      mediaRate: readFixed32(buf, 8 + ptr)
    };
  }
  return {
    entries: entries
  };
};

exports.elst.encodingLength = function(box) {
  return 4 + 12 * box.entries.length;
};

exports.hdlr = {};

exports.hdlr.encode = function(box, buf, offset) {
  buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(exports.hdlr.encodingLength(box));
  var len = 21 + (box.name || "").length;
  buf.fill(0, 0, len);
  buf.write(box.handlerType || "", 4, 4, "ascii");
  writeString(box.name || "", buf, 20);
  exports.hdlr.encode.bytes = len;
  return buf;
};

exports.hdlr.decode = function(buf, offset, end) {
  return {
    handlerType: (buf = buf.slice(offset)).toString("ascii", 4, 8),
    name: readString(buf, 20, end)
  };
};

exports.hdlr.encodingLength = function(box) {
  return 21 + (box.name || "").length;
};

exports.mehd = {};

exports.mehd.encode = function(box, buf, offset) {
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(4)).writeUInt32BE(box.fragmentDuration || 0, 0);
  exports.mehd.encode.bytes = 4;
  return buf;
};

exports.mehd.decode = function(buf, offset) {
  return {
    fragmentDuration: (buf = buf.slice(offset)).readUInt32BE(0)
  };
};

exports.mehd.encodingLength = function(box) {
  return 4;
};

exports.trex = {};

exports.trex.encode = function(box, buf, offset) {
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(20)).writeUInt32BE(box.trackId || 0, 0);
  buf.writeUInt32BE(box.defaultSampleDescriptionIndex || 0, 4);
  buf.writeUInt32BE(box.defaultSampleDuration || 0, 8);
  buf.writeUInt32BE(box.defaultSampleSize || 0, 12);
  buf.writeUInt32BE(box.defaultSampleFlags || 0, 16);
  exports.trex.encode.bytes = 20;
  return buf;
};

exports.trex.decode = function(buf, offset) {
  return {
    trackId: (buf = buf.slice(offset)).readUInt32BE(0),
    defaultSampleDescriptionIndex: buf.readUInt32BE(4),
    defaultSampleDuration: buf.readUInt32BE(8),
    defaultSampleSize: buf.readUInt32BE(12),
    defaultSampleFlags: buf.readUInt32BE(16)
  };
};

exports.trex.encodingLength = function(box) {
  return 20;
};

exports.mfhd = {};

exports.mfhd.encode = function(box, buf, offset) {
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(4)).writeUInt32BE(box.sequenceNumber || 0, 0);
  exports.mfhd.encode.bytes = 4;
  return buf;
};

exports.mfhd.decode = function(buf, offset) {
  return {
    sequenceNumber: buf.readUInt32BE(0)
  };
};

exports.mfhd.encodingLength = function(box) {
  return 4;
};

exports.tfhd = {};

exports.tfhd.encode = function(box, buf, offset) {
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(4)).writeUInt32BE(box.trackId, 0);
  exports.tfhd.encode.bytes = 4;
  return buf;
};

exports.tfhd.decode = function(buf, offset) {};

exports.tfhd.encodingLength = function(box) {
  return 4;
};

exports.tfdt = {};

exports.tfdt.encode = function(box, buf, offset) {
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(4)).writeUInt32BE(box.baseMediaDecodeTime || 0, 0);
  exports.tfdt.encode.bytes = 4;
  return buf;
};

exports.tfdt.decode = function(buf, offset) {};

exports.tfdt.encodingLength = function(box) {
  return 4;
};

exports.trun = {};

exports.trun.encode = function(box, buf, offset) {
  (buf = buf ? buf.slice(offset) : Buffer.allocUnsafe(8 + 16 * box.entries.length)).writeUInt32BE(box.entries.length, 0);
  buf.writeInt32BE(box.dataOffset, 4);
  for (var ptr = 8, i = 0; i < box.entries.length; i++) {
    var entry = box.entries[i];
    buf.writeUInt32BE(entry.sampleDuration, ptr);
    buf.writeUInt32BE(entry.sampleSize, ptr += 4);
    buf.writeUInt32BE(entry.sampleFlags, ptr += 4);
    ptr += 4;
    0 === (box.version || 0) ? buf.writeUInt32BE(entry.sampleCompositionTimeOffset, ptr) : buf.writeInt32BE(entry.sampleCompositionTimeOffset, ptr);
    ptr += 4;
  }
  exports.trun.encode.bytes = ptr;
};

exports.trun.decode = function(buf, offset) {};

exports.trun.encodingLength = function(box) {
  return 8 + 16 * box.entries.length;
};

exports.mdat = {};

exports.mdat.encode = function(box, buf, offset) {
  if (box.buffer) {
    box.buffer.copy(buf, offset);
    exports.mdat.encode.bytes = box.buffer.length;
  } else exports.mdat.encode.bytes = exports.mdat.encodingLength(box);
};

exports.mdat.decode = function(buf, start, end) {
  return {
    buffer: Buffer.from(buf.slice(start, end))
  };
};

exports.mdat.encodingLength = function(box) {
  return box.buffer ? box.buffer.length : box.contentLength;
};

function writeReserved(buf, offset, end) {
  for (var i = offset; i < end; i++) buf[i] = 0;
}

function writeDate(date, buf, offset) {
  buf.writeUInt32BE(Math.floor((date.getTime() + TIME_OFFSET) / 1e3), offset);
}

function writeDate64(date, buf, offset) {
  buf.writeUIntBE(Math.floor((date.getTime() + TIME_OFFSET) / 1e3), offset, 6);
}

function writeFixed32(num, buf, offset) {
  buf.writeUInt16BE(Math.floor(num) % 65536, offset);
  buf.writeUInt16BE(Math.floor(256 * num * 256) % 65536, offset + 2);
}

function writeFixed16(num, buf, offset) {
  buf[offset] = Math.floor(num) % 256;
  buf[offset + 1] = Math.floor(256 * num) % 256;
}

function writeMatrix(list, buf, offset) {
  list = list || [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  for (var i = 0; i < list.length; i++) writeFixed32(list[i], buf, offset + 4 * i);
}

function writeString(str, buf, offset) {
  var strBuffer = Buffer.from(str, "utf8");
  strBuffer.copy(buf, offset);
  buf[offset + strBuffer.length] = 0;
}

function readMatrix(buf) {
  for (var list = new Array(buf.length / 4), i = 0; i < list.length; i++) list[i] = readFixed32(buf, 4 * i);
  return list;
}

function readDate64(buf, offset) {
  return new Date(1e3 * buf.readUIntBE(offset, 6) - TIME_OFFSET);
}

function readDate(buf, offset) {
  return new Date(1e3 * buf.readUInt32BE(offset) - TIME_OFFSET);
}

function readFixed32(buf, offset) {
  return buf.readUInt16BE(offset) + buf.readUInt16BE(offset + 2) / 65536;
}

function readFixed16(buf, offset) {
  return buf[offset] + buf[offset + 1] / 256;
}

function readString(buf, offset, length) {
  for (var i = 0; i < length; i++) if (0 === buf[offset + i]) break;
  return buf.toString("utf8", offset, offset + i);
}
},{"./descriptor":19,"./index":20,"buffer":10,"uint64be":44}],19:[function(require,module,exports){
var Buffer = require("buffer").Buffer, tagToName = {
  3: "ESDescriptor",
  4: "DecoderConfigDescriptor",
  5: "DecoderSpecificInfo",
  6: "SLConfigDescriptor"
};

exports.Descriptor = {};

exports.Descriptor.decode = function(buf, start, end) {
  var lenByte, tag = buf.readUInt8(start), ptr = start + 1, len = 0;
  do {
    len = len << 7 | 127 & (lenByte = buf.readUInt8(ptr++));
  } while (128 & lenByte);
  var obj, tagName = tagToName[tag];
  (obj = exports[tagName] ? exports[tagName].decode(buf, ptr, end) : {
    buffer: Buffer.from(buf.slice(ptr, ptr + len))
  }).tag = tag;
  obj.tagName = tagName;
  obj.length = ptr - start + len;
  obj.contentsLen = len;
  return obj;
};

exports.DescriptorArray = {};

exports.DescriptorArray.decode = function(buf, start, end) {
  var ptr = start, obj = {};
  while (ptr + 2 <= end) {
    var descriptor = exports.Descriptor.decode(buf, ptr, end);
    ptr += descriptor.length;
    obj[tagToName[descriptor.tag] || "Descriptor" + descriptor.tag] = descriptor;
  }
  return obj;
};

exports.ESDescriptor = {};

exports.ESDescriptor.decode = function(buf, start, end) {
  var flags = buf.readUInt8(start + 2), ptr = start + 3;
  128 & flags && (ptr += 2);
  64 & flags && (ptr += buf.readUInt8(ptr) + 1);
  32 & flags && (ptr += 2);
  return exports.DescriptorArray.decode(buf, ptr, end);
};

exports.DecoderConfigDescriptor = {};

exports.DecoderConfigDescriptor.decode = function(buf, start, end) {
  var oti = buf.readUInt8(start), obj = exports.DescriptorArray.decode(buf, start + 13, end);
  obj.oti = oti;
  return obj;
};
},{"buffer":10}],20:[function(require,module,exports){
var Buffer = require("buffer").Buffer, uint64be = require("uint64be"), boxes = require("./boxes"), UINT32_MAX = 4294967295, Box = exports;

Box.boxes = boxes;

var containers = exports.containers = {
  moov: [ "mvhd", "meta", "traks", "mvex" ],
  trak: [ "tkhd", "tref", "trgr", "edts", "meta", "mdia", "udta" ],
  edts: [ "elst" ],
  mdia: [ "mdhd", "hdlr", "elng", "minf" ],
  minf: [ "vmhd", "smhd", "hmhd", "sthd", "nmhd", "dinf", "stbl" ],
  dinf: [ "dref" ],
  stbl: [ "stsd", "stts", "ctts", "cslg", "stsc", "stsz", "stz2", "stco", "co64", "stss", "stsh", "padb", "stdp", "sdtp", "sbgps", "sgpds", "subss", "saizs", "saios" ],
  mvex: [ "mehd", "trexs", "leva" ],
  moof: [ "mfhd", "meta", "trafs" ],
  traf: [ "tfhd", "tfdt", "trun", "sbgps", "sgpds", "subss", "saizs", "saios", "meta" ]
};

Box.encode = function(obj, buffer, offset) {
  Box.encodingLength(obj);
  offset = offset || 0;
  buffer = buffer || Buffer.allocUnsafe(obj.length);
  return Box._encode(obj, buffer, offset);
};

Box._encode = function(obj, buffer, offset) {
  var type = obj.type, len = obj.length;
  len > UINT32_MAX && (len = 1);
  buffer.writeUInt32BE(len, offset);
  buffer.write(obj.type, offset + 4, 4, "ascii");
  var ptr = offset + 8;
  if (1 === len) {
    uint64be.encode(obj.length, buffer, ptr);
    ptr += 8;
  }
  if (boxes.fullBoxes[type]) {
    buffer.writeUInt32BE(obj.flags || 0, ptr);
    buffer.writeUInt8(obj.version || 0, ptr);
    ptr += 4;
  }
  if (containers[type]) {
    containers[type].forEach(function(childType) {
      if (5 === childType.length) {
        var entry = obj[childType] || [];
        childType = childType.substr(0, 4);
        entry.forEach(function(child) {
          Box._encode(child, buffer, ptr);
          ptr += Box.encode.bytes;
        });
      } else if (obj[childType]) {
        Box._encode(obj[childType], buffer, ptr);
        ptr += Box.encode.bytes;
      }
    });
    obj.otherBoxes && obj.otherBoxes.forEach(function(child) {
      Box._encode(child, buffer, ptr);
      ptr += Box.encode.bytes;
    });
  } else if (boxes[type]) {
    var encode = boxes[type].encode;
    encode(obj, buffer, ptr);
    ptr += encode.bytes;
  } else {
    if (!obj.buffer) throw new Error("Either `type` must be set to a known type (not'" + type + "') or `buffer` must be set");
    obj.buffer.copy(buffer, ptr);
    ptr += obj.buffer.length;
  }
  Box.encode.bytes = ptr - offset;
  return buffer;
};

Box.readHeaders = function(buffer, start, end) {
  if ((end = end || buffer.length) - (start = start || 0) < 8) return 8;
  var version, flags, len = buffer.readUInt32BE(start), type = buffer.toString("ascii", start + 4, start + 8), ptr = start + 8;
  if (1 === len) {
    if (end - start < 16) return 16;
    len = uint64be.decode(buffer, ptr);
    ptr += 8;
  }
  d > 1 && console.warn("Box.readHeaders", [ buffer ], start, end, type, containers[type], boxes[type], boxes.fullBoxes[type]);
  "sidx" === type && (ptr -= 8);
  if (boxes.fullBoxes[type]) {
    version = buffer.readUInt8(ptr);
    flags = 16777215 & buffer.readUInt32BE(ptr);
    ptr += 4;
  }
  return {
    length: len,
    headersLen: ptr - start,
    contentLen: len - (ptr - start),
    type: type,
    version: version,
    flags: flags
  };
};

Box.decode = function(buffer, start, end) {
  var headers = Box.readHeaders(buffer, start = start || 0, end = end || buffer.length);
  return !headers || headers.length > end - start ? new Error("Unsupported media format, data too short...") : Box.decodeWithoutHeaders(headers, buffer, start + headers.headersLen, start + headers.length);
};

Box.decodeWithoutHeaders = function(headers, buffer, start, end) {
  start = start || 0;
  end = end || buffer.length;
  var type = headers.type, obj = Object.create(null);
  d > 1 && console.warn("Box.decode", type, obj);
  if (containers[type]) {
    obj.otherBoxes = [];
    var contents = containers[type], ptr = start;
    while (end - ptr >= 8) {
      var child = Box.decode(buffer, ptr, end);
      ptr += child.length;
      if (contents.indexOf(child.type) >= 0) obj[child.type] = child; else if (contents.indexOf(child.type + "s") >= 0) {
        var childType = child.type + "s";
        (obj[childType] = obj[childType] || []).push(child);
      } else obj.otherBoxes.push(child);
    }
  } else boxes[type] ? obj = boxes[type].decode.call(headers, buffer, start, end) : obj.buffer = Buffer.from(buffer.slice(start, end));
  obj.length = headers.length;
  obj.contentLen = headers.contentLen;
  obj.type = headers.type;
  obj.version = headers.version;
  obj.flags = headers.flags;
  return obj;
};

Box.encodingLength = function(obj) {
  var type = obj.type, len = 8;
  boxes.fullBoxes[type] && (len += 4);
  if (containers[type]) {
    containers[type].forEach(function(childType) {
      if (5 === childType.length) {
        var entry = obj[childType] || [];
        childType = childType.substr(0, 4);
        entry.forEach(function(child) {
          child.type = childType;
          len += Box.encodingLength(child);
        });
      } else if (obj[childType]) {
        var child = obj[childType];
        child.type = childType;
        len += Box.encodingLength(child);
      }
    });
    obj.otherBoxes && obj.otherBoxes.forEach(function(child) {
      len += Box.encodingLength(child);
    });
  } else if (boxes[type]) len += boxes[type].encodingLength(obj); else {
    if (!obj.buffer) throw new Error("Either `type` must be set to a known type (not'" + type + "') or `buffer` must be set");
    len += obj.buffer.length;
  }
  len > UINT32_MAX && (len += 8);
  return obj.length = len;
};
},{"./boxes":18,"buffer":10,"uint64be":44}],21:[function(require,module,exports){
var Buffer = require("buffer").Buffer, stream = require("readable-stream"), inherits = require("/bundle/utils").inherit, nextEvent = require("next-event"), Box = require("mp4-box-encoding"), EMPTY = Buffer.allocUnsafe(0);

module.exports = Decoder;

function Decoder() {
  if (!(this instanceof Decoder)) return new Decoder();
  stream.Writable.call(this);
  this.destroyed = !1;
  this._pending = 0;
  this._missing = 0;
  this._ignoreEmpty = !1;
  this._buf = null;
  this._str = null;
  this._cb = null;
  this._ondrain = null;
  this._writeBuffer = null;
  this._writeCb = null;
  this._ondrain = null;
  this._kick();
}

inherits(Decoder, stream.Writable);

Decoder.prototype.destroy = function(err) {
  if (!this.destroyed) {
    this.destroyed = !0;
    err && this.emit("error", err);
    this.emit("close");
  }
};

Decoder.prototype._write = function(data, enc, next) {
  if (!this.destroyed) {
    var drained = !this._str || !this._str._writableState.needDrain;
    while (data.length && !this.destroyed) {
      if (!this._missing && !this._ignoreEmpty) {
        this._writeBuffer = data;
        this._writeCb = next;
        return;
      }
      var consumed = data.length < this._missing ? data.length : this._missing;
      this._buf ? data.copy(this._buf, this._buf.length - this._missing) : this._str && (drained = this._str.write(consumed === data.length ? data : data.slice(0, consumed)));
      this._missing -= consumed;
      if (!this._missing) {
        var buf = this._buf, cb = this._cb, stream = this._str;
        this._buf = this._cb = this._str = this._ondrain = null;
        this._ignoreEmpty = !(drained = !0);
        stream && stream.end();
        cb && cb(buf);
      }
      data = consumed === data.length ? EMPTY : data.slice(consumed);
    }
    if (!this._pending || this._missing) drained ? next() : this._ondrain(next); else {
      this._writeBuffer = data;
      this._writeCb = next;
    }
  }
};

Decoder.prototype._buffer = function(size, cb) {
  this._missing = size;
  this._buf = Buffer.allocUnsafe(size);
  this._cb = cb;
};

Decoder.prototype._stream = function(size, cb) {
  var self = this;
  this._missing = size;
  this._str = new MediaData(this);
  this._ondrain = nextEvent(this._str, "drain");
  this._pending++;
  this._str.on("end", function() {
    self._pending--;
    self._kick();
  });
  this._cb = cb;
  return this._str;
};

Decoder.prototype._readBox = function() {
  var self = this;
  !function bufferHeaders(len, buf) {
    self._buffer(len, function(additionalBuf) {
      buf = buf ? Buffer.concat([ buf, additionalBuf ]) : additionalBuf;
      var headers = Box.readHeaders(buf);
      if ("number" === typeof headers) bufferHeaders(headers - buf.length, buf); else {
        self._pending++;
        self._headers = headers;
        self.emit("box", headers);
      }
    });
  }(8);
};

Decoder.prototype.stream = function() {
  if (!this._headers) throw new Error("this function can only be called once after 'box' is emitted");
  var headers = this._headers;
  this._headers = null;
  return this._stream(headers.contentLen, null);
};

Decoder.prototype.decode = function(cb) {
  var self = this;
  if (!self._headers) throw new Error("this function can only be called once after 'box' is emitted");
  var headers = self._headers;
  self._headers = null;
  self._buffer(headers.contentLen, function(buf) {
    var box = Box.decodeWithoutHeaders(headers, buf);
    cb(box);
    self._pending--;
    self._kick();
  });
};

Decoder.prototype.ignore = function() {
  var self = this;
  if (!self._headers) throw new Error("this function can only be called once after 'box' is emitted");
  var headers = self._headers;
  self._headers = null;
  this._missing = headers.contentLen;
  0 === this._missing && (this._ignoreEmpty = !0);
  this._cb = function() {
    self._pending--;
    self._kick();
  };
};

Decoder.prototype._kick = function() {
  if (!this._pending) {
    this._buf || this._str || this._readBox();
    if (this._writeBuffer) {
      var next = this._writeCb, buffer = this._writeBuffer;
      this._writeBuffer = null;
      this._writeCb = null;
      this._write(buffer, null, next);
    }
  }
};

function MediaData(parent) {
  this._parent = parent;
  this.destroyed = !1;
  stream.PassThrough.call(this);
}

inherits(MediaData, stream.PassThrough);

MediaData.prototype.destroy = function(err) {
  if (!this.destroyed) {
    this.destroyed = !0;
    this._parent.destroy(err);
    err && this.emit("error", err);
    this.emit("close");
  }
};
},{"/bundle/utils":4,"buffer":10,"mp4-box-encoding":20,"next-event":24,"readable-stream":41}],22:[function(require,module,exports){
var stream = require("readable-stream"), inherits = require("/bundle/utils").inherit, Box = require("mp4-box-encoding");

module.exports = Encoder;

var nextTick = require("/bundle/utils").nextTick, Buffer = require("buffer").Buffer;

function noop() {}

function Encoder() {
  if (!(this instanceof Encoder)) return new Encoder();
  stream.Readable.call(this);
  this.destroyed = !1;
  this._finalized = !1;
  this._reading = !1;
  this._stream = null;
  this._drain = null;
  this._want = !1;
  this._onreadable = function() {
    if (self._want) {
      self._want = !1;
      self._read();
    }
  };
  this._onend = function() {
    self._stream = null;
  };
  var self = this;
}

inherits(Encoder, stream.Readable);

Encoder.prototype.mediaData = Encoder.prototype.mdat = function(size, cb) {
  var stream = new MediaData(this);
  this.box({
    type: "mdat",
    contentLength: size,
    encodeBufferLen: 8,
    stream: stream
  }, cb);
  return stream;
};

Encoder.prototype.box = function(box, cb) {
  cb = cb || noop;
  if (this.destroyed) return cb(new Error("Encoder is destroyed"));
  var buf;
  box.encodeBufferLen && (buf = Buffer.allocUnsafe(box.encodeBufferLen));
  if (box.stream) {
    box.buffer = null;
    buf = Box.encode(box, buf);
    this.push(buf);
    this._stream = box.stream;
    this._stream.on("readable", this._onreadable);
    this._stream.on("end", this._onend);
    this._stream.on("end", cb);
    this._forward();
  } else {
    buf = Box.encode(box, buf);
    if (this.push(buf)) return nextTick(cb);
    this._drain = cb;
  }
};

Encoder.prototype.destroy = function(err) {
  if (!this.destroyed) {
    this.destroyed = !0;
    this._stream && this._stream.destroy && this._stream.destroy();
    this._stream = null;
    if (this._drain) {
      var cb = this._drain;
      this._drain = null;
      cb(err);
    }
    err && this.emit("error", err);
    this.emit("close");
  }
};

Encoder.prototype.finalize = function() {
  this._finalized = !0;
  this._stream || this._drain || this.push(null);
};

Encoder.prototype._forward = function() {
  if (this._stream) while (!this.destroyed) {
    var buf = this._stream.read();
    if (!buf) {
      this._want = !!this._stream;
      return;
    }
    if (!this.push(buf)) return;
  }
};

Encoder.prototype._read = function() {
  if (!this._reading && !this.destroyed) {
    this._reading = !0;
    this._stream && this._forward();
    if (this._drain) {
      var drain = this._drain;
      this._drain = null;
      drain();
    }
    this._reading = !1;
    this._finalized && this.push(null);
  }
};

function MediaData(parent) {
  this._parent = parent;
  this.destroyed = !1;
  stream.PassThrough.call(this);
}

inherits(MediaData, stream.PassThrough);

MediaData.prototype.destroy = function(err) {
  if (!this.destroyed) {
    this.destroyed = !0;
    this._parent.destroy(err);
    err && this.emit("error", err);
    this.emit("close");
  }
};
},{"/bundle/utils":4,"buffer":10,"mp4-box-encoding":20,"readable-stream":41}],23:[function(require,module,exports){
exports.decode = require("./decode");

exports.encode = require("./encode");
},{"./decode":21,"./encode":22}],24:[function(require,module,exports){
module.exports = nextEvent;

function nextEvent(emitter, name) {
  var next = null;
  emitter.on(name, function(data) {
    if (next) {
      var fn = next;
      next = null;
      fn(data);
    }
  });
  return function(once) {
    next = once;
  };
}
},{}],25:[function(require,module,exports){
var wrappy = require("wrappy");

module.exports = wrappy(once);

module.exports.strict = wrappy(onceStrict);

once.proto = once(function() {
  Object.defineProperty(Function.prototype, "once", {
    value: function() {
      return once(this);
    },
    configurable: !0
  });
  Object.defineProperty(Function.prototype, "onceStrict", {
    value: function() {
      return onceStrict(this);
    },
    configurable: !0
  });
});

function once(fn) {
  var f = function() {
    if (f.called) return f.value;
    f.called = !0;
    return f.value = fn.apply(this, arguments);
  };
  f.called = !1;
  return f;
}

function onceStrict(fn) {
  var f = function() {
    if (f.called) throw new Error(f.onceError);
    f.called = !0;
    return f.value = fn.apply(this, arguments);
  };
  f.onceError = (fn.name || "Function wrapped with `once`") + " shouldn't be called more than once";
  f.called = !1;
  return f;
}
},{"wrappy":45}],26:[function(require,module,exports){
"use strict";

var BaseAudioContext = require("base-audio-context"), OfflineAudioContext = window.OfflineAudioContext || window.webkitOfflineAudioContext;

if (OfflineAudioContext) {
  var silent = new Uint32Array([ 1179011410, 56, 1163280727, 544501094, 16, 65537, 44100, 88200, 1048578, 1635017060, 20, 0, 0, 0, 0, 0 ]).buffer, isPromiseBased = new OfflineAudioContext(1, 128, 44100).decodeAudioData(silent, function() {}, function() {});
  if (!isPromiseBased) {
    var decodeAudioData = BaseAudioContext.prototype.decodeAudioData;
    BaseAudioContext.prototype.decodeAudioData = function(audioData, successCallback, errorCallback) {
      var _this = this;
      return new Promise(function(resolve, reject) {
        return decodeAudioData.call(_this, audioData, resolve, reject.bind(null, Error("Legacy WebAudio API decoding error")));
      });
    };
    BaseAudioContext.prototype.decodeAudioData.original = decodeAudioData;
  }
}
},{"base-audio-context":7}],27:[function(require,module,exports){
var isFS, once = require("once"), eos = require("end-of-stream"), noop = function() {}, isFn = function(fn) {
  return "function" === typeof fn;
}, isRequest = function(stream) {
  return stream.setHeader && isFn(stream.abort);
}, destroyer = function(stream, reading, writing, callback) {
  callback = once(callback);
  var closed = !1;
  stream.on("close", function() {
    closed = !0;
  });
  eos(stream, {
    readable: reading,
    writable: writing
  }, function(err) {
    if (err) return callback(err);
    closed = !0;
    callback();
  });
  var destroyed = !1;
  return function(err) {
    if (!closed && !destroyed) {
      destroyed = !0;
      if (isRequest(stream)) return stream.abort();
      if (isFn(stream.destroy)) return stream.destroy();
      callback(err || new Error("stream was destroyed"));
    }
  };
}, call = function(fn) {
  fn();
}, pipe = function(from, to) {
  return from.pipe(to);
}, pump = function() {
  var i = arguments.length, streams = new Array(i);
  while (i--) streams[i] = arguments[i];
  var error, callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;
  Array.isArray(streams[0]) && (streams = streams[0]);
  if (streams.length < 2) throw new Error("pump requires two streams per minimum");
  var destroys = streams.map(function(stream, i) {
    var reading = i < streams.length - 1;
    return destroyer(stream, reading, i > 0, function(err) {
      error = error || err;
      err && destroys.forEach(call);
      if (!reading) {
        destroys.forEach(call);
        callback(error);
      }
    });
  });
  return streams.reduce(pipe);
};

module.exports = pump;
},{"end-of-stream":14,"once":25}],28:[function(require,module,exports){
"use strict";

var _require = require("readable-stream"), Writable = _require.Writable, PassThrough = _require.PassThrough, RangeSliceStream = function(_Writable) {
  function RangeSliceStream(offset, opts) {
    var _this;
    void 0 === opts && (opts = {});
    (_this = _Writable.call(this, opts) || this).satisfied = !0;
    _this._queue = [];
    _this._position = offset || 0;
    _this._cb = null;
    _this._buffer = null;
    return _this;
  }
  require("/bundle/utils").inherit(RangeSliceStream, _Writable);
  var _proto = RangeSliceStream.prototype;
  _proto._write = function(chunk, encoding, cb) {
    var drained = !0;
    while (1) {
      if (this.destroyed) return;
      if (0 === this._queue.length) {
        this.satisfied = !0;
        this.emit("satisfied");
        this._buffer = chunk;
        this._cb = cb;
        return;
      }
      this._buffer = null;
      var currRange = this._queue[0], writeStart = Math.max(currRange.start - this._position, 0), writeEnd = currRange.end - this._position;
      if (writeStart >= chunk.length) {
        this._position += chunk.length;
        return cb(null);
      }
      var toWrite = void 0;
      if (writeEnd > chunk.length) {
        this._position += chunk.length;
        toWrite = 0 === writeStart ? chunk : chunk.slice(writeStart);
        drained = currRange.stream.write(toWrite) && drained;
        break;
      }
      this._position += writeEnd;
      toWrite = 0 === writeStart && writeEnd === chunk.length ? chunk : chunk.slice(writeStart, writeEnd);
      drained = currRange.stream.write(toWrite) && drained;
      currRange.last && currRange.stream.end();
      chunk = chunk.slice(writeEnd);
      this._queue.shift();
    }
    drained ? cb(null) : currRange.stream.once("drain", cb.bind(null, null));
  };
  _proto.slice = function(ranges) {
    var _this2 = this;
    if (this.destroyed) return null;
    this.satisfied = !1;
    Array.isArray(ranges) || (ranges = [ ranges ]);
    var str = new PassThrough();
    ranges.forEach(function(range, i) {
      _this2._queue.push({
        start: range.start,
        end: range.end,
        stream: str,
        last: i === ranges.length - 1
      });
    });
    this._buffer && this._write(this._buffer, null, this._cb);
    return str;
  };
  return RangeSliceStream;
}(Writable);

module.exports = RangeSliceStream;
},{"/bundle/utils":4,"readable-stream":41}],29:[function(require,module,exports){
"use strict";

var codes = {};

function createErrorType(code, message, Base) {
  var NodeError = function(_Base) {
    function NodeError(arg1, arg2, arg3) {
      return _Base.call(this, function(arg1, arg2, arg3) {
        return "string" === typeof message ? message : message(arg1, arg2, arg3);
      }(arg1, arg2, arg3)) || this;
    }
    require("/bundle/utils").inherit(NodeError, _Base);
    return NodeError;
  }(Base = Base || Error);
  NodeError.prototype.name = Base.name;
  codes[NodeError.prototype.code = code] = NodeError;
}

function oneOf(expected, thing) {
  if (Array.isArray(expected)) {
    var len = expected.length;
    expected = expected.map(function(i) {
      return String(i);
    });
    return len > 2 ? "one of " + thing + " " + expected.slice(0, len - 1).join(", ") + ", or " + expected[len - 1] : 2 === len ? "one of " + thing + " " + expected[0] + " or " + expected[1] : "of " + thing + " " + expected[0];
  }
  return "of " + thing + " " + String(expected);
}

function startsWith(str, search, pos) {
  return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
}

function endsWith(str, search, this_len) {
  (void 0 === this_len || this_len > str.length) && (this_len = str.length);
  return str.substring(this_len - search.length, this_len) === search;
}

function includes(str, search, start) {
  "number" !== typeof start && (start = 0);
  return !(start + search.length > str.length) && -1 !== str.indexOf(search, start);
}

createErrorType("ERR_INVALID_OPT_VALUE", function(name, value) {
  return 'The value "' + value + '" is invalid for option "' + name + '"';
}, TypeError);

createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) {
  var determiner;
  if ("string" === typeof expected && startsWith(expected, "not ")) {
    determiner = "must not be";
    expected = expected.replace(/^not /, "");
  } else determiner = "must be";
  return (endsWith(name, " argument") ? "The " + name + " " + determiner + " " + oneOf(expected, "type") : 'The "' + name + '" ' + (includes(name, ".") ? "property" : "argument") + " " + determiner + " " + oneOf(expected, "type")) + ". Received type " + typeof actual;
}, TypeError);

createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF");

createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name) {
  return "The " + name + " method is not implemented";
});

createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close");

createErrorType("ERR_STREAM_DESTROYED", function(name) {
  return "Cannot call " + name + " after a stream was destroyed";
});

createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times");

createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable");

createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end");

createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError);

createErrorType("ERR_UNKNOWN_ENCODING", function(arg) {
  return "Unknown encoding: " + arg;
}, TypeError);

createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event");

module.exports.codes = codes;
},{"/bundle/utils":4}],30:[function(require,module,exports){
"use strict";

var objectKeys = Object.keys;

module.exports = Duplex;

var Readable = require("./_stream_readable"), Writable = require("./_stream_writable");

require("/bundle/utils").inherit(Duplex, Readable);

for (var keys = objectKeys(Writable.prototype), v = 0; v < keys.length; v++) {
  var method = keys[v];
  Duplex.prototype[method] || (Duplex.prototype[method] = Writable.prototype[method]);
}

function Duplex(options) {
  if (!(this instanceof Duplex)) return new Duplex(options);
  Readable.call(this, options);
  Writable.call(this, options);
  this.allowHalfOpen = !0;
  if (options) {
    !1 === options.readable && (this.readable = !1);
    !1 === options.writable && (this.writable = !1);
    if (!1 === options.allowHalfOpen) {
      this.allowHalfOpen = !1;
      this.once("end", onend);
    }
  }
}

Object.defineProperty(Duplex.prototype, "writableHighWaterMark", {
  enumerable: !1,
  get: function() {
    return this._writableState.highWaterMark;
  }
});

Object.defineProperty(Duplex.prototype, "writableBuffer", {
  enumerable: !1,
  get: function() {
    return this._writableState && this._writableState.getBuffer();
  }
});

Object.defineProperty(Duplex.prototype, "writableLength", {
  enumerable: !1,
  get: function() {
    return this._writableState.length;
  }
});

function onend() {
  this._writableState.ended || vsNT(onEndNT.bind(null, this));
}

function onEndNT(self) {
  self.end();
}

Object.defineProperty(Duplex.prototype, "destroyed", {
  enumerable: !1,
  get: function() {
    return void 0 !== this._readableState && void 0 !== this._writableState && this._readableState.destroyed && this._writableState.destroyed;
  },
  set: function(value) {
    if (void 0 !== this._readableState && void 0 !== this._writableState) {
      this._readableState.destroyed = value;
      this._writableState.destroyed = value;
    }
  }
});
},{"./_stream_readable":32,"./_stream_writable":34,"/bundle/utils":4}],31:[function(require,module,exports){
"use strict";

module.exports = PassThrough;

var Transform = require("./_stream_transform");

require("/bundle/utils").inherit(PassThrough, Transform);

function PassThrough(options) {
  if (!(this instanceof PassThrough)) return new PassThrough(options);
  Transform.call(this, options);
}

PassThrough.prototype._transform = function(chunk, encoding, cb) {
  cb(null, chunk);
};
},{"./_stream_transform":33,"/bundle/utils":4}],32:[function(require,module,exports){
"use strict";

var Duplex;

(module.exports = Readable).ReadableState = ReadableState;

var StringDecoder, createReadableStreamAsyncIterator, from, EE = require("eventemitter3").EventEmitter, EElistenerCount = function(emitter, type) {
  return emitter.listeners(type).length;
}, Stream = require("./internal/streams/stream"), _isUint8Array = require("/bundle/utils").isU8, Buffer = require("buffer").Buffer, debug = require("/bundle/utils").debuglog("stream"), BufferList = require("./internal/streams/buffer_list"), destroyImpl = require("./internal/streams/destroy"), _require = require("./internal/streams/state"), getHighWaterMark = _require.getHighWaterMark, _require$codes = require("../errors").codes, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;

require("/bundle/utils").inherit(Readable, Stream);

var errorOrDestroy = destroyImpl.errorOrDestroy, kProxyEvents = [ "error", "close", "destroy", "pause", "resume" ];

function prependListener(emitter, event, fn) {
  if ("function" === typeof emitter.prependListener) return emitter.prependListener(event, fn);
  emitter._events && emitter._events[event] ? Array.isArray(emitter._events[event]) ? emitter._events[event].unshift(fn) : emitter._events[event] = [ fn, emitter._events[event] ] : emitter.on(event, fn);
}

function ReadableState(options, stream, isDuplex) {
  Duplex = Duplex || require("./_stream_duplex");
  "boolean" !== typeof isDuplex && (isDuplex = stream instanceof Duplex);
  this.objectMode = !!(options = options || {}).objectMode;
  isDuplex && (this.objectMode = this.objectMode || !!options.readableObjectMode);
  this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex);
  this.buffer = new BufferList();
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = !1;
  this.endEmitted = !1;
  this.reading = !1;
  this.sync = !0;
  this.needReadable = !1;
  this.emittedReadable = !1;
  this.readableListening = !1;
  this.resumeScheduled = !1;
  this.paused = !0;
  this.emitClose = !1 !== options.emitClose;
  this.autoDestroy = !!options.autoDestroy;
  this.destroyed = !1;
  this.defaultEncoding = options.defaultEncoding || "utf8";
  this.awaitDrain = 0;
  this.readingMore = !1;
  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    StringDecoder = StringDecoder || require("string_decoder/").StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}

function Readable(options) {
  Duplex = Duplex || require("./_stream_duplex");
  if (!(this instanceof Readable)) return new Readable(options);
  this._readableState = new ReadableState(options, this, this instanceof Duplex);
  this.readable = !0;
  if (options) {
    "function" === typeof options.read && (this._read = options.read);
    "function" === typeof options.destroy && (this._destroy = options.destroy);
  }
  Stream.call(this);
}

Object.defineProperty(Readable.prototype, "destroyed", {
  enumerable: !1,
  get: function() {
    return void 0 !== this._readableState && this._readableState.destroyed;
  },
  set: function(value) {
    this._readableState && (this._readableState.destroyed = value);
  }
});

Readable.prototype.destroy = destroyImpl.destroy;

Readable.prototype._undestroy = destroyImpl.undestroy;

Readable.prototype._destroy = function(err, cb) {
  cb(err);
};

Readable.prototype.push = function(chunk, encoding) {
  var skipChunkCheck, state = this._readableState;
  if (state.objectMode) skipChunkCheck = !0; else if ("string" === typeof chunk) {
    if ((encoding = encoding || state.defaultEncoding) !== state.encoding) {
      chunk = Buffer.from(chunk, encoding);
      encoding = "";
    }
    skipChunkCheck = !0;
  }
  return readableAddChunk(this, chunk, encoding, !1, skipChunkCheck);
};

Readable.prototype.unshift = function(chunk) {
  return readableAddChunk(this, chunk, null, !0, !1);
};

function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  var er, state = stream._readableState;
  if (null === chunk) {
    state.reading = !1;
    onEofChunk(stream, state);
  } else {
    skipChunkCheck || (er = 0);
    if (er) errorOrDestroy(stream, er); else if (state.objectMode || chunk && chunk.length > 0) {
      "string" === typeof chunk || state.objectMode || Object.getPrototypeOf(chunk) === Buffer.prototype || (chunk = Buffer.from(chunk));
      if (addToFront) state.endEmitted ? errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()) : addChunk(stream, state, chunk, !0); else if (state.ended) errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); else {
        if (state.destroyed) return !1;
        state.reading = !1;
        if (state.decoder && !encoding) {
          chunk = state.decoder.write(chunk);
          state.objectMode || 0 !== chunk.length ? addChunk(stream, state, chunk, !1) : maybeReadMore(stream, state);
        } else addChunk(stream, state, chunk, !1);
      }
    } else if (!addToFront) {
      state.reading = !1;
      maybeReadMore(stream, state);
    }
  }
  return !state.ended && (state.length < state.highWaterMark || 0 === state.length);
}

function addChunk(stream, state, chunk, addToFront) {
  if (state.flowing && 0 === state.length && !state.sync) {
    state.awaitDrain = 0;
    stream.emit("data", chunk);
  } else {
    state.length += state.objectMode ? 1 : chunk.length;
    addToFront ? state.buffer.unshift(chunk) : state.buffer.push(chunk);
    state.needReadable && emitReadable(stream);
  }
  maybeReadMore(stream, state);
}

function chunkInvalid(state, chunk) {
  var er;
  _isUint8Array(chunk) || "string" === typeof chunk || void 0 === chunk || state.objectMode || (er = new ERR_INVALID_ARG_TYPE("chunk", [ "string", "Buffer", "Uint8Array" ], chunk));
  return er;
}

Readable.prototype.isPaused = function() {
  return !1 === this._readableState.flowing;
};

Readable.prototype.setEncoding = function(enc) {
  var decoder = new (StringDecoder = StringDecoder || require("string_decoder/").StringDecoder)(enc);
  this._readableState.decoder = decoder;
  this._readableState.encoding = this._readableState.decoder.encoding;
  var p = this._readableState.buffer.head, content = "";
  while (null !== p) {
    content += decoder.write(p.data);
    p = p.next;
  }
  this._readableState.buffer.clear();
  "" !== content && this._readableState.buffer.push(content);
  this._readableState.length = content.length;
  return this;
};

var _, MAX_HWM = 1073741824;

function computeNewHighWaterMark(n) {
  if (n >= MAX_HWM) n = MAX_HWM; else {
    n--;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    n++;
  }
  return n;
}

function howMuchToRead(n, state) {
  if (n <= 0 || 0 === state.length && state.ended) return 0;
  if (state.objectMode) return 1;
  if (n !== n) return state.flowing && state.length ? state.buffer.head.data.length : state.length;
  n > state.highWaterMark && (state.highWaterMark = computeNewHighWaterMark(n));
  if (n <= state.length) return n;
  if (state.ended) return state.length;
  state.needReadable = !0;
  return 0;
}

Readable.prototype.read = function(n) {
  n = parseInt(n, 10);
  var state = this._readableState, nOrig = n;
  0 !== n && (state.emittedReadable = !1);
  if (0 === n && state.needReadable && ((0 !== state.highWaterMark ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
    (0 === state.length && state.ended ? endReadable : emitReadable)(this);
    return null;
  }
  if (0 === (n = howMuchToRead(n, state)) && state.ended) {
    0 === state.length && endReadable(this);
    return null;
  }
  var ret, doRead = state.needReadable;
  (0 === state.length || state.length - n < state.highWaterMark) && (doRead = !0);
  if (state.ended || state.reading) doRead = !1; else if (doRead) {
    state.reading = !0;
    state.sync = !0;
    0 === state.length && (state.needReadable = !0);
    this._read(state.highWaterMark);
    state.sync = !1;
    state.reading || (n = howMuchToRead(nOrig, state));
  }
  if (null === (ret = n > 0 ? fromList(n, state) : null)) {
    state.needReadable = state.length <= state.highWaterMark;
    n = 0;
  } else {
    state.length -= n;
    state.awaitDrain = 0;
  }
  if (0 === state.length) {
    state.ended || (state.needReadable = !0);
    nOrig !== n && state.ended && endReadable(this);
  }
  null !== ret && this.emit("data", ret);
  return ret;
};

function onEofChunk(stream, state) {
  if (!state.ended) {
    if (state.decoder) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) {
        state.buffer.push(chunk);
        state.length += state.objectMode ? 1 : chunk.length;
      }
    }
    state.ended = !0;
    if (state.sync) emitReadable(stream); else {
      state.needReadable = !1;
      if (!state.emittedReadable) {
        state.emittedReadable = !0;
        emitReadable_(stream);
      }
    }
  }
}

function emitReadable(stream) {
  var state = stream._readableState;
  state.needReadable = !1;
  if (!state.emittedReadable) {
    state.emittedReadable = !0;
    vsNT(emitReadable_.bind(null, stream));
  }
}

function emitReadable_(stream) {
  var state = stream._readableState;
  if (!state.destroyed && (state.length || state.ended)) {
    stream.emit("readable");
    state.emittedReadable = !1;
  }
  state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  flow(stream);
}

function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = !0;
    vsNT(maybeReadMore_.bind(null, stream, state));
  }
}

function maybeReadMore_(stream, state) {
  while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && 0 === state.length)) {
    var len = state.length;
    stream.read(0);
    if (len === state.length) break;
  }
  state.readingMore = !1;
}

Readable.prototype._read = function(n) {
  errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()"));
};

Readable.prototype.pipe = function(dest, pipeOpts) {
  var src = this, state = this._readableState;
  switch (state.pipesCount) {
   case 0:
    state.pipes = dest;
    break;

   case 1:
    state.pipes = [ state.pipes, dest ];
    break;

   default:
    state.pipes.push(dest);
  }
  state.pipesCount += 1;
  var endFn = pipeOpts && !1 === pipeOpts.end ? unpipe : onend;
  state.endEmitted ? vsNT(endFn.bind(null)) : src.once("end", endFn);
  dest.on("unpipe", function onunpipe(readable, unpipeInfo) {
    if (readable === src && unpipeInfo && !1 === unpipeInfo.hasUnpiped) {
      unpipeInfo.hasUnpiped = !0;
      !function() {
        dest.removeListener("close", onclose);
        dest.removeListener("finish", onfinish);
        dest.removeListener("drain", ondrain);
        dest.removeListener("error", onerror);
        dest.removeListener("unpipe", onunpipe);
        src.removeListener("end", onend);
        src.removeListener("end", unpipe);
        src.removeListener("data", ondata);
        cleanedUp = !0;
        !state.awaitDrain || dest._writableState && !dest._writableState.needDrain || ondrain();
      }();
    }
  });
  function onend() {
    dest.end();
  }
  var ondrain = pipeOnDrain(src);
  dest.on("drain", ondrain);
  var cleanedUp = !1;
  src.on("data", ondata);
  function ondata(chunk) {
    if (!1 === dest.write(chunk)) {
      (1 === state.pipesCount && state.pipes === dest || state.pipesCount > 1 && -1 !== indexOf(state.pipes, dest)) && !cleanedUp && state.awaitDrain++;
      src.pause();
    }
  }
  function onerror(er) {
    unpipe();
    dest.removeListener("error", onerror);
    0 === EElistenerCount(dest, "error") && errorOrDestroy(dest, er);
  }
  dest.on("error", onerror, 0, !0);
  function onclose() {
    dest.removeListener("finish", onfinish);
    unpipe();
  }
  dest.once("close", onclose);
  function onfinish() {
    dest.removeListener("close", onclose);
    unpipe();
  }
  dest.once("finish", onfinish);
  function unpipe() {
    src.unpipe(dest);
  }
  dest.emit("pipe", src);
  state.flowing || src.resume();
  return dest;
};

function pipeOnDrain(src) {
  return function() {
    var state = src._readableState;
    state.awaitDrain && state.awaitDrain--;
    if (0 === state.awaitDrain && EElistenerCount(src, "data")) {
      state.flowing = !0;
      flow(src);
    }
  };
}

Readable.prototype.unpipe = function(dest) {
  var state = this._readableState, unpipeInfo = {
    hasUnpiped: !1
  };
  if (0 === state.pipesCount) return this;
  if (1 === state.pipesCount) {
    if (dest && dest !== state.pipes) return this;
    dest = dest || state.pipes;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = !1;
    dest && dest.emit("unpipe", this, unpipeInfo);
    return this;
  }
  if (!dest) {
    var dests = state.pipes, len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = !1;
    for (var i = 0; i < len; i++) dests[i].emit("unpipe", this, {
      hasUnpiped: !1
    });
    return this;
  }
  var index = indexOf(state.pipes, dest);
  if (-1 === index) return this;
  state.pipes.splice(index, 1);
  --state.pipesCount;
  1 === state.pipesCount && (state.pipes = state.pipes[0]);
  dest.emit("unpipe", this, unpipeInfo);
  return this;
};

Readable.prototype.on = function(ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn), state = this._readableState;
  if ("data" === ev) {
    state.readableListening = this.listenerCount("readable") > 0;
    !1 !== state.flowing && this.resume();
  } else if ("readable" === ev && !state.endEmitted && !state.readableListening) {
    state.readableListening = state.needReadable = !0;
    state.flowing = !1;
    state.emittedReadable = !1;
    state.length ? emitReadable(this) : state.reading || vsNT(nReadingNextTick.bind(null, this));
  }
  return res;
};

Readable.prototype.addListener = Readable.prototype.on;

Readable.prototype.removeListener = function(ev, fn) {
  var res = Stream.prototype.removeListener.call(this, ev, fn);
  "readable" === ev && vsNT(updateReadableListening.bind(null, this));
  return res;
};

Readable.prototype.removeAllListeners = function(ev) {
  var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  "readable" !== ev && void 0 !== ev || vsNT(updateReadableListening.bind(null, this));
  return res;
};

function updateReadableListening(self) {
  var state = self._readableState;
  state.readableListening = self.listenerCount("readable") > 0;
  state.resumeScheduled && !state.paused ? state.flowing = !0 : self.listenerCount("data") > 0 && self.resume();
}

function nReadingNextTick(self) {
  self.read(0);
}

Readable.prototype.resume = function() {
  var state = this._readableState;
  if (!state.flowing) {
    state.flowing = !state.readableListening;
    resume(this, state);
  }
  state.paused = !1;
  return this;
};

function resume(stream, state) {
  if (!state.resumeScheduled) {
    state.resumeScheduled = !0;
    vsNT(resume_.bind(null, stream, state));
  }
}

function resume_(stream, state) {
  state.reading || stream.read(0);
  state.resumeScheduled = !1;
  stream.emit("resume");
  flow(stream);
  state.flowing && !state.reading && stream.read(0);
}

Readable.prototype.pause = function() {
  if (!1 !== this._readableState.flowing) {
    this._readableState.flowing = !1;
    this.emit("pause");
  }
  this._readableState.paused = !0;
  return this;
};

function flow(stream) {
  var state = stream._readableState;
  while (state.flowing && null !== stream.read()) ;
}

Readable.prototype.wrap = function(stream) {
  var i, _this = this, state = this._readableState, paused = !1;
  stream.on("end", function() {
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      chunk && chunk.length && _this.push(chunk);
    }
    _this.push(null);
  });
  stream.on("data", function(chunk) {
    state.decoder && (chunk = state.decoder.write(chunk));
    if ((!state.objectMode || null !== chunk && void 0 !== chunk) && (state.objectMode || chunk && chunk.length) && !_this.push(chunk)) {
      paused = !0;
      stream.pause();
    }
  });
  for (i in stream) void 0 === this[i] && "function" === typeof stream[i] && (this[i] = function(method) {
    return function() {
      return stream[method].apply(stream, arguments);
    };
  }(i));
  for (var n = 0; n < kProxyEvents.length; n++) stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  this._read = function(n) {
    if (paused) {
      paused = !1;
      stream.resume();
    }
  };
  return this;
};

Object.defineProperty(Readable.prototype, "readableHighWaterMark", {
  enumerable: !1,
  get: function() {
    return this._readableState.highWaterMark;
  }
});

Object.defineProperty(Readable.prototype, "readableBuffer", {
  enumerable: !1,
  get: function() {
    return this._readableState && this._readableState.buffer;
  }
});

Object.defineProperty(Readable.prototype, "readableFlowing", {
  enumerable: !1,
  get: function() {
    return this._readableState.flowing;
  },
  set: function(state) {
    this._readableState && (this._readableState.flowing = state);
  }
});

Readable._fromList = fromList;

Object.defineProperty(Readable.prototype, "readableLength", {
  enumerable: !1,
  get: function() {
    return this._readableState.length;
  }
});

function fromList(n, state) {
  if (0 === state.length) return null;
  var ret;
  if (state.objectMode) ret = state.buffer.shift(); else if (!n || n >= state.length) {
    ret = state.decoder ? state.buffer.join("") : 1 === state.buffer.length ? state.buffer.first() : state.buffer.concat(state.length);
    state.buffer.clear();
  } else ret = state.buffer.consume(n, state.decoder);
  return ret;
}

function endReadable(stream) {
  var state = stream._readableState;
  if (!state.endEmitted) {
    state.ended = !0;
    vsNT(endReadableNT.bind(null, state, stream));
  }
}

function endReadableNT(state, stream) {
  if (!state.endEmitted && 0 === state.length) {
    stream.readable = !(state.endEmitted = !0);
    stream.emit("end");
    if (state.autoDestroy) {
      var wState = stream._writableState;
      (!wState || wState.autoDestroy && wState.finished) && stream.destroy();
    }
  }
}

function indexOf(xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) if (xs[i] === x) return i;
  return -1;
}
},{"../errors":29,"./_stream_duplex":30,"./internal/streams/buffer_list":35,"./internal/streams/destroy":36,"./internal/streams/state":39,"./internal/streams/stream":40,"/bundle/utils":4,"buffer":10,"eventemitter3":15,"string_decoder/":42}],33:[function(require,module,exports){
"use strict";

module.exports = Transform;

var _require$codes = require("../errors").codes, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0, Duplex = require("./_stream_duplex");

require("/bundle/utils").inherit(Transform, Duplex);

function afterTransform(er, data) {
  var ts = this._transformState;
  ts.transforming = !1;
  var cb = ts.writecb;
  if (null === cb) return this.emit("error", new ERR_MULTIPLE_CALLBACK());
  ts.writechunk = null;
  (ts.writecb = null) != data && this.push(data);
  cb(er);
  var rs = this._readableState;
  rs.reading = !1;
  (rs.needReadable || rs.length < rs.highWaterMark) && this._read(rs.highWaterMark);
}

function Transform(options) {
  if (!(this instanceof Transform)) return new Transform(options);
  Duplex.call(this, options);
  this._transformState = {
    afterTransform: afterTransform.bind(this),
    needTransform: !1,
    transforming: !1,
    writecb: null,
    writechunk: null,
    writeencoding: null
  };
  this._readableState.needReadable = !0;
  this._readableState.sync = !1;
  if (options) {
    "function" === typeof options.transform && (this._transform = options.transform);
    "function" === typeof options.flush && (this._flush = options.flush);
  }
  this.on("prefinish", prefinish);
}

function prefinish() {
  var _this = this;
  "function" !== typeof this._flush || this._readableState.destroyed ? done(this, null, null) : this._flush(function(er, data) {
    done(_this, er, data);
  });
}

Transform.prototype.push = function(chunk, encoding) {
  this._transformState.needTransform = !1;
  return Duplex.prototype.push.call(this, chunk, encoding);
};

Transform.prototype._transform = function(chunk, encoding, cb) {
  cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"));
};

Transform.prototype._write = function(chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) && this._read(rs.highWaterMark);
  }
};

Transform.prototype._read = function(n) {
  var ts = this._transformState;
  if (null === ts.writechunk || ts.transforming) ts.needTransform = !0; else {
    ts.transforming = !0;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  }
};

Transform.prototype._destroy = function(err, cb) {
  Duplex.prototype._destroy.call(this, err, function(err2) {
    cb(err2);
  });
};

function done(stream, er, data) {
  if (er) return stream.emit("error", er);
  null != data && stream.push(data);
  if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  return stream.push(null);
}
},{"../errors":29,"./_stream_duplex":30,"/bundle/utils":4}],34:[function(require,module,exports){
"use strict";

function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
  this.next = null;
}

function CorkedRequest(state) {
  var _this = this;
  this.next = null;
  this.entry = null;
  this.finish = function() {
    onCorkedFinish(_this, state);
  };
}

var Duplex;

(module.exports = Writable).WritableState = WritableState;

var realHasInstance, deprecate = require("/bundle/utils").deprecate, Stream = require("./internal/streams/stream"), _isUint8Array = require("/bundle/utils").isU8, Buffer = require("buffer").Buffer, destroyImpl = require("./internal/streams/destroy"), _require = require("./internal/streams/state"), getHighWaterMark = _require.getHighWaterMark, _require$codes = require("../errors").codes, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING, errorOrDestroy = destroyImpl.errorOrDestroy;

require("/bundle/utils").inherit(Writable, Stream);

function nop() {}

function WritableState(options, stream, isDuplex) {
  Duplex = Duplex || require("./_stream_duplex");
  "boolean" !== typeof isDuplex && (isDuplex = stream instanceof Duplex);
  this.objectMode = !!(options = options || {}).objectMode;
  isDuplex && (this.objectMode = this.objectMode || !!options.writableObjectMode);
  this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex);
  this.finalCalled = !1;
  this.needDrain = !1;
  this.ending = !1;
  this.ended = !1;
  this.finished = !1;
  this.destroyed = !1;
  this.decodeStrings = !(!1 === options.decodeStrings);
  this.defaultEncoding = options.defaultEncoding || "utf8";
  this.length = 0;
  this.writing = !1;
  this.corked = 0;
  this.sync = !0;
  this.bufferProcessing = !1;
  this.onwrite = function(er) {
    onwrite(stream, er);
  };
  this.writecb = null;
  this.writelen = 0;
  this.bufferedRequest = null;
  this.lastBufferedRequest = null;
  this.pendingcb = 0;
  this.prefinished = !1;
  this.errorEmitted = !1;
  this.emitClose = !1 !== options.emitClose;
  this.autoDestroy = !!options.autoDestroy;
  this.bufferedRequestCount = 0;
  this.corkedRequestsFree = new CorkedRequest(this);
}

WritableState.prototype.getBuffer = function() {
  var current = this.bufferedRequest, out = [];
  while (current) {
    out.push(current);
    current = current.next;
  }
  return out;
};

!function() {
  try {
    Object.defineProperty(WritableState.prototype, "buffer", {
      get: deprecate(function() {
        return this.getBuffer();
      }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003")
    });
  } catch (_) {}
}();

if ("function" === typeof Symbol && Symbol.hasInstance && "function" === typeof Function.prototype[Symbol.hasInstance]) {
  realHasInstance = Function.prototype[Symbol.hasInstance];
  Object.defineProperty(Writable, Symbol.hasInstance, {
    value: function(object) {
      return !!realHasInstance.call(this, object) || this === Writable && object && object._writableState instanceof WritableState;
    }
  });
} else realHasInstance = function(object) {
  return object instanceof this;
};

function Writable(options) {
  var isDuplex = this instanceof (Duplex = Duplex || require("./_stream_duplex"));
  if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  this._writableState = new WritableState(options, this, isDuplex);
  this.writable = !0;
  if (options) {
    "function" === typeof options.write && (this._write = options.write);
    "function" === typeof options.writev && (this._writev = options.writev);
    "function" === typeof options.destroy && (this._destroy = options.destroy);
    "function" === typeof options.final && (this._final = options.final);
  }
  Stream.call(this);
}

Writable.prototype.pipe = function() {
  errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
};

function writeAfterEnd(stream, cb) {
  var er = new ERR_STREAM_WRITE_AFTER_END();
  errorOrDestroy(stream, er);
  vsNT(cb.bind(null, er));
}

function validChunk(stream, state, chunk, cb) {
  var er;
  null === chunk ? er = new ERR_STREAM_NULL_VALUES() : "string" === typeof chunk || state.objectMode || (er = new ERR_INVALID_ARG_TYPE("chunk", [ "string", "Buffer" ], chunk));
  if (er) {
    errorOrDestroy(stream, er);
    vsNT(cb.bind(null, er));
    return !1;
  }
  return !0;
}

Writable.prototype.write = function(chunk, encoding, cb) {
  var state = this._writableState, ret = !1, isBuf = !state.objectMode && _isUint8Array(chunk);
  isBuf && !Buffer.isBuffer(chunk) && (chunk = Buffer.from(chunk));
  if ("function" === typeof encoding) {
    cb = encoding;
    encoding = null;
  }
  encoding = isBuf ? "buffer" : encoding || state.defaultEncoding;
  "function" !== typeof cb && (cb = nop);
  if (state.ending) writeAfterEnd(this, cb); else if (isBuf || validChunk(this, state, chunk, cb)) {
    state.pendingcb++;
    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  }
  return ret;
};

Writable.prototype.cork = function() {
  this._writableState.corked++;
};

Writable.prototype.uncork = function() {
  var state = this._writableState;
  if (state.corked) {
    state.corked--;
    state.writing || state.corked || state.bufferProcessing || !state.bufferedRequest || clearBuffer(this, state);
  }
};

Writable.prototype.setDefaultEncoding = function(encoding) {
  "string" === typeof encoding && (encoding = encoding.toLowerCase());
  if (!([ "hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw" ].indexOf((encoding + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  this._writableState.defaultEncoding = encoding;
  return this;
};

Object.defineProperty(Writable.prototype, "writableBuffer", {
  enumerable: !1,
  get: function() {
    return this._writableState && this._writableState.getBuffer();
  }
});

function decodeChunk(state, chunk, encoding) {
  state.objectMode || !1 === state.decodeStrings || "string" !== typeof chunk || (chunk = Buffer.from(chunk, encoding));
  return chunk;
}

Object.defineProperty(Writable.prototype, "writableHighWaterMark", {
  enumerable: !1,
  get: function() {
    return this._writableState.highWaterMark;
  }
});

function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  if (!isBuf) {
    var newChunk = decodeChunk(state, chunk, encoding);
    if (chunk !== newChunk) {
      isBuf = !0;
      encoding = "buffer";
      chunk = newChunk;
    }
  }
  var len = state.objectMode ? 1 : chunk.length;
  state.length += len;
  var ret = state.length < state.highWaterMark;
  ret || (state.needDrain = !0);
  if (state.writing || state.corked) {
    var last = state.lastBufferedRequest;
    state.lastBufferedRequest = {
      chunk: chunk,
      encoding: encoding,
      isBuf: isBuf,
      callback: cb,
      next: null
    };
    last ? last.next = state.lastBufferedRequest : state.bufferedRequest = state.lastBufferedRequest;
    state.bufferedRequestCount += 1;
  } else doWrite(stream, state, !1, len, chunk, encoding, cb);
  return ret;
}

function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = !0;
  state.sync = !0;
  state.destroyed ? state.onwrite(new ERR_STREAM_DESTROYED("write")) : writev ? stream._writev(chunk, state.onwrite) : stream._write(chunk, encoding, state.onwrite);
  state.sync = !1;
}

function onwriteError(stream, state, sync, er, cb) {
  --state.pendingcb;
  if (sync) {
    vsNT(cb.bind(null, er));
    vsNT(finishMaybe.bind(null, stream, state));
    stream._writableState.errorEmitted = !0;
    errorOrDestroy(stream, er);
  } else {
    cb(er);
    stream._writableState.errorEmitted = !0;
    errorOrDestroy(stream, er);
    finishMaybe(stream, state);
  }
}

function onwriteStateUpdate(state) {
  state.writing = !1;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}

function onwrite(stream, er) {
  var state = stream._writableState, sync = state.sync, cb = state.writecb;
  if ("function" !== typeof cb) throw new ERR_MULTIPLE_CALLBACK();
  onwriteStateUpdate(state);
  if (er) onwriteError(stream, state, sync, er, cb); else {
    var finished = needFinish(state) || stream.destroyed;
    finished || state.corked || state.bufferProcessing || !state.bufferedRequest || clearBuffer(stream, state);
    sync ? vsNT(afterWrite.bind(null, stream, state, finished, cb)) : afterWrite(stream, state, finished, cb);
  }
}

function afterWrite(stream, state, finished, cb) {
  finished || onwriteDrain(stream, state);
  state.pendingcb--;
  cb();
  finishMaybe(stream, state);
}

function onwriteDrain(stream, state) {
  if (0 === state.length && state.needDrain) {
    state.needDrain = !1;
    stream.emit("drain");
  }
}

function clearBuffer(stream, state) {
  state.bufferProcessing = !0;
  var entry = state.bufferedRequest;
  if (stream._writev && entry && entry.next) {
    var buffer = new Array(state.bufferedRequestCount), holder = state.corkedRequestsFree;
    holder.entry = entry;
    var count = 0, allBuffers = !0;
    while (entry) {
      (buffer[count] = entry).isBuf || (allBuffers = !1);
      entry = entry.next;
      count += 1;
    }
    buffer.allBuffers = allBuffers;
    doWrite(stream, state, !0, state.length, buffer, "", holder.finish);
    state.pendingcb++;
    state.lastBufferedRequest = null;
    if (holder.next) {
      state.corkedRequestsFree = holder.next;
      holder.next = null;
    } else state.corkedRequestsFree = new CorkedRequest(state);
    state.bufferedRequestCount = 0;
  } else {
    while (entry) {
      var chunk = entry.chunk;
      doWrite(stream, state, !1, state.objectMode ? 1 : chunk.length, chunk, entry.encoding, entry.callback);
      entry = entry.next;
      state.bufferedRequestCount--;
      if (state.writing) break;
    }
    null === entry && (state.lastBufferedRequest = null);
  }
  state.bufferedRequest = entry;
  state.bufferProcessing = !1;
}

Writable.prototype._write = function(chunk, encoding, cb) {
  cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"));
};

Writable.prototype._writev = null;

Writable.prototype.end = function(chunk, encoding, cb) {
  var state = this._writableState;
  if ("function" === typeof chunk) {
    cb = chunk;
    encoding = chunk = null;
  } else if ("function" === typeof encoding) {
    cb = encoding;
    encoding = null;
  }
  null !== chunk && void 0 !== chunk && this.write(chunk, encoding);
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }
  state.ending || endWritable(this, state, cb);
  return this;
};

Object.defineProperty(Writable.prototype, "writableLength", {
  enumerable: !1,
  get: function() {
    return this._writableState.length;
  }
});

function needFinish(state) {
  return state.ending && 0 === state.length && null === state.bufferedRequest && !state.finished && !state.writing;
}

function callFinal(stream, state) {
  stream._final(function(err) {
    state.pendingcb--;
    err && errorOrDestroy(stream, err);
    state.prefinished = !0;
    stream.emit("prefinish");
    finishMaybe(stream, state);
  });
}

function prefinish(stream, state) {
  if (!state.prefinished && !state.finalCalled) if ("function" !== typeof stream._final || state.destroyed) {
    state.prefinished = !0;
    stream.emit("prefinish");
  } else {
    state.pendingcb++;
    state.finalCalled = !0;
    vsNT(callFinal.bind(null, stream, state));
  }
}

function finishMaybe(stream, state) {
  var need = needFinish(state);
  if (need) {
    prefinish(stream, state);
    if (0 === state.pendingcb) {
      state.finished = !0;
      stream.emit("finish");
      if (state.autoDestroy) {
        var rState = stream._readableState;
        (!rState || rState.autoDestroy && rState.endEmitted) && stream.destroy();
      }
    }
  }
  return need;
}

function endWritable(stream, state, cb) {
  state.ending = !0;
  finishMaybe(stream, state);
  cb && (state.finished ? vsNT(cb.bind(null)) : stream.once("finish", cb));
  stream.writable = !(state.ended = !0);
}

function onCorkedFinish(corkReq, state, err) {
  var entry = corkReq.entry;
  corkReq.entry = null;
  while (entry) {
    var cb = entry.callback;
    state.pendingcb--;
    cb(err);
    entry = entry.next;
  }
  state.corkedRequestsFree.next = corkReq;
}

Object.defineProperty(Writable.prototype, "destroyed", {
  enumerable: !1,
  get: function() {
    return void 0 !== this._writableState && this._writableState.destroyed;
  },
  set: function(value) {
    this._writableState && (this._writableState.destroyed = value);
  }
});

Writable.prototype.destroy = destroyImpl.destroy;

Writable.prototype._undestroy = destroyImpl.undestroy;

Writable.prototype._destroy = function(err, cb) {
  cb(err);
};
},{"../errors":29,"./_stream_duplex":30,"./internal/streams/destroy":36,"./internal/streams/state":39,"./internal/streams/stream":40,"/bundle/utils":4,"buffer":10}],35:[function(require,module,exports){
"use strict";

var Buffer = require("buffer").Buffer;

function copyBuffer(src, target, offset) {
  Buffer.prototype.copy.call(src, target, offset);
}

module.exports = function() {
  function BufferList() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
  _createClass(BufferList, [ {
    key: "push",
    value: function(v) {
      var entry = {
        data: v,
        next: null
      };
      this.length > 0 ? this.tail.next = entry : this.head = entry;
      this.tail = entry;
      ++this.length;
    }
  }, {
    key: "unshift",
    value: function(v) {
      var entry = {
        data: v,
        next: this.head
      };
      0 === this.length && (this.tail = entry);
      this.head = entry;
      ++this.length;
    }
  }, {
    key: "shift",
    value: function() {
      if (0 !== this.length) {
        var ret = this.head.data;
        this.head = 1 === this.length ? this.tail = null : this.head.next;
        --this.length;
        return ret;
      }
    }
  }, {
    key: "clear",
    value: function() {
      this.head = this.tail = null;
      this.length = 0;
    }
  }, {
    key: "join",
    value: function(s) {
      if (0 === this.length) return "";
      var p = this.head, ret = "" + p.data;
      while (p = p.next) ret += s + p.data;
      return ret;
    }
  }, {
    key: "concat",
    value: function(n) {
      if (0 === this.length) return Buffer.alloc(0);
      var ret = Buffer.allocUnsafe(n >>> 0), p = this.head, i = 0;
      while (p) {
        copyBuffer(p.data, ret, i);
        i += p.data.length;
        p = p.next;
      }
      return ret;
    }
  }, {
    key: "consume",
    value: function(n, hasStrings) {
      var ret;
      if (n < this.head.data.length) {
        ret = this.head.data.slice(0, n);
        this.head.data = this.head.data.slice(n);
      } else ret = n === this.head.data.length ? this.shift() : hasStrings ? this._getString(n) : this._getBuffer(n);
      return ret;
    }
  }, {
    key: "first",
    value: function() {
      return this.head.data;
    }
  }, {
    key: "_getString",
    value: function(n) {
      var p = this.head, c = 1, ret = p.data;
      n -= ret.length;
      while (p = p.next) {
        var str = p.data, nb = n > str.length ? str.length : n;
        ret += nb === str.length ? str : str.slice(0, n);
        if (0 === (n -= nb)) {
          if (nb === str.length) {
            ++c;
            this.head = p.next ? p.next : this.tail = null;
          } else (this.head = p).data = str.slice(nb);
          break;
        }
        ++c;
      }
      this.length -= c;
      return ret;
    }
  }, {
    key: "_getBuffer",
    value: function(n) {
      var ret = Buffer.allocUnsafe(n), p = this.head, c = 1;
      p.data.copy(ret);
      n -= p.data.length;
      while (p = p.next) {
        var buf = p.data, nb = n > buf.length ? buf.length : n;
        buf.copy(ret, ret.length - n, 0, nb);
        if (0 === (n -= nb)) {
          if (nb === buf.length) {
            ++c;
            this.head = p.next ? p.next : this.tail = null;
          } else (this.head = p).data = buf.slice(nb);
          break;
        }
        ++c;
      }
      this.length -= c;
      return ret;
    }
  }, 0 ]);
  return BufferList;
}();

function _createClass(c, p) {
  for (var i = p.length; i--; ) {
    var d = p[i];
    if (d) {
      d.writable = !0;
      d.configurable = !0;
      Object.defineProperty(c.prototype, d.key, d);
    }
  }
}
},{"buffer":10}],36:[function(require,module,exports){
"use strict";

function destroy(err, cb) {
  var _this = this;
  if (this._readableState && this._readableState.destroyed || this._writableState && this._writableState.destroyed) {
    if (cb) cb(err); else if (err) if (this._writableState) {
      if (!this._writableState.errorEmitted) {
        this._writableState.errorEmitted = !0;
        vsNT(emitErrorNT.bind(null, this, err));
      }
    } else vsNT(emitErrorNT.bind(null, this, err));
    return this;
  }
  this._readableState && (this._readableState.destroyed = !0);
  this._writableState && (this._writableState.destroyed = !0);
  this._destroy(err || null, function(err) {
    if (!cb && err) if (_this._writableState) if (_this._writableState.errorEmitted) vsNT(emitCloseNT.bind(null, _this)); else {
      _this._writableState.errorEmitted = !0;
      vsNT(emitErrorAndCloseNT.bind(null, _this, err));
    } else vsNT(emitErrorAndCloseNT.bind(null, _this, err)); else if (cb) {
      vsNT(emitCloseNT.bind(null, _this));
      cb(err);
    } else vsNT(emitCloseNT.bind(null, _this));
  });
  return this;
}

function emitErrorAndCloseNT(self, err) {
  emitErrorNT(self, err);
  emitCloseNT(self);
}

function emitCloseNT(self) {
  self._writableState && !self._writableState.emitClose || self._readableState && !self._readableState.emitClose || self.emit("close");
}

function undestroy() {
  if (this._readableState) {
    this._readableState.destroyed = !1;
    this._readableState.reading = !1;
    this._readableState.ended = !1;
    this._readableState.endEmitted = !1;
  }
  if (this._writableState) {
    this._writableState.destroyed = !1;
    this._writableState.ended = !1;
    this._writableState.ending = !1;
    this._writableState.finalCalled = !1;
    this._writableState.prefinished = !1;
    this._writableState.finished = !1;
    this._writableState.errorEmitted = !1;
  }
}

function emitErrorNT(self, err) {
  self.emit("error", err);
}

function errorOrDestroy(stream, err) {
  var rState = stream._readableState, wState = stream._writableState;
  rState && rState.autoDestroy || wState && wState.autoDestroy ? stream.destroy(err) : stream.emit("error", err);
}

module.exports = {
  destroy: destroy,
  undestroy: undestroy,
  errorOrDestroy: errorOrDestroy
};
},{}],37:[function(require,module,exports){
"use strict";

var ERR_STREAM_PREMATURE_CLOSE = require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE, once = require("once");

function noop() {}

function eos(stream, opts, callback) {
  if ("function" === typeof opts) return eos(stream, null, opts);
  opts = opts || {};
  callback = once(callback || noop);
  function onlegacyfinish() {
    stream.writable || onfinish();
  }
  function onend() {
    readableEnded = !(readable = !1);
    writable || callback.call(stream);
  }
  function onerror(err) {
    callback.call(stream, err);
  }
  function onclose() {
    var err;
    if (readable && !readableEnded) {
      stream._readableState && stream._readableState.ended || (err = new ERR_STREAM_PREMATURE_CLOSE());
      return callback.call(stream, err);
    }
    if (writable && !writableEnded) {
      stream._writableState && stream._writableState.ended || (err = new ERR_STREAM_PREMATURE_CLOSE());
      return callback.call(stream, err);
    }
  }
  function onrequest() {
    stream.req.on("finish", onfinish);
  }
  function onfinish() {
    writableEnded = !(writable = !1);
    readable || callback.call(stream);
  }
  var readable = opts.readable || !1 !== opts.readable && stream.readable, writable = opts.writable || !1 !== opts.writable && stream.writable, writableEnded = stream._writableState && stream._writableState.finished, readableEnded = stream._readableState && stream._readableState.endEmitted;
  if (writable && !stream._writableState) {
    stream.on("end", onlegacyfinish);
    stream.on("close", onlegacyfinish);
  }
  stream.on("end", onend);
  stream.on("finish", onfinish);
  !1 !== opts.error && stream.on("error", onerror);
  stream.on("close", onclose);
  return function() {
    stream.removeListener("complete", onfinish);
    stream.removeListener("abort", onclose);
    stream.removeListener("request", onrequest);
    stream.req && stream.req.removeListener("finish", onfinish);
    stream.removeListener("end", onlegacyfinish);
    stream.removeListener("close", onlegacyfinish);
    stream.removeListener("finish", onfinish);
    stream.removeListener("end", onend);
    stream.removeListener("error", onerror);
    stream.removeListener("close", onclose);
  };
}

module.exports = eos;
},{"../../../errors":29,"once":25}],38:[function(require,module,exports){
"use strict";

var eos, once = require("once"), _require$codes = require("../../../errors").codes, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;

function noop(err) {
  if (err) throw err;
}

function destroyer(stream, reading, writing, callback) {
  callback = once(callback);
  var closed = !1;
  stream.on("close", function() {
    closed = !0;
  });
  void 0 === eos && (eos = require("./end-of-stream"));
  eos(stream, {
    readable: reading,
    writable: writing
  }, function(err) {
    if (err) return callback(err);
    closed = !0;
    callback();
  });
  var destroyed = !1;
  return function(err) {
    if (!closed && !destroyed) {
      destroyed = !0;
      if ("function" === typeof stream.destroy) return stream.destroy();
      callback(err || new ERR_STREAM_DESTROYED("pipe"));
    }
  };
}

function call(fn) {
  fn();
}

function pipe(from, to) {
  return from.pipe(to);
}

function popCallback(streams) {
  return streams.length && "function" === typeof streams[streams.length - 1] ? streams.pop() : noop;
}

function pipeline() {
  for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) streams[_key] = arguments[_key];
  var error, callback = popCallback(streams);
  Array.isArray(streams[0]) && (streams = streams[0]);
  if (streams.length < 2) throw new ERR_MISSING_ARGS("streams");
  var destroys = streams.map(function(stream, i) {
    var reading = i < streams.length - 1;
    return destroyer(stream, reading, i > 0, function(err) {
      error = error || err;
      err && destroys.forEach(call);
      if (!reading) {
        destroys.forEach(call);
        callback(error);
      }
    });
  });
  return streams.reduce(pipe);
}

module.exports = pipeline;
},{"../../../errors":29,"./end-of-stream":37,"once":25}],39:[function(require,module,exports){
"use strict";

var ERR_INVALID_OPT_VALUE = require("../../../errors").codes.ERR_INVALID_OPT_VALUE;

function highWaterMarkFrom(options, isDuplex, duplexKey) {
  return null != options.highWaterMark ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
}

function getHighWaterMark(state, options, duplexKey, isDuplex) {
  var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  if (null == hwm) return state.objectMode ? 16 : 16384;
  if (!isFinite(hwm) || Math.floor(hwm) !== hwm || hwm < 0) throw new ERR_INVALID_OPT_VALUE(isDuplex ? duplexKey : "highWaterMark", hwm);
  return Math.floor(hwm);
}

module.exports = {
  getHighWaterMark: getHighWaterMark
};
},{"../../../errors":29}],40:[function(require,module,exports){
module.exports = require("eventemitter3").EventEmitter;
},{"eventemitter3":15}],41:[function(require,module,exports){
exports = module.exports = require("./lib/_stream_readable.js");

exports.Stream = exports;

exports.Readable = exports;

exports.Writable = require("./lib/_stream_writable.js");

exports.Duplex = require("./lib/_stream_duplex.js");

exports.Transform = require("./lib/_stream_transform.js");

exports.PassThrough = require("./lib/_stream_passthrough.js");

exports.finished = require("./lib/internal/streams/end-of-stream.js");

exports.pipeline = require("./lib/internal/streams/pipeline.js");
},{"./lib/_stream_duplex.js":30,"./lib/_stream_passthrough.js":31,"./lib/_stream_readable.js":32,"./lib/_stream_transform.js":33,"./lib/_stream_writable.js":34,"./lib/internal/streams/end-of-stream.js":37,"./lib/internal/streams/pipeline.js":38}],42:[function(require,module,exports){
"use strict";

var Buffer = require("buffer").Buffer, isEncoding = Buffer.isEncoding || function(encoding) {
  switch ((encoding = "" + encoding) && encoding.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 !0;

   default:
    return !1;
  }
};

function _normalizeEncoding(enc) {
  if (!enc) return "utf8";
  var retried;
  while (1) switch (enc) {
   case "utf8":
   case "utf-8":
    return "utf8";

   case "ucs2":
   case "ucs-2":
   case "utf16le":
   case "utf-16le":
    return "utf16le";

   case "latin1":
   case "binary":
    return "latin1";

   case "base64":
   case "ascii":
   case "hex":
    return enc;

   default:
    if (retried) return;
    enc = ("" + enc).toLowerCase();
    retried = !0;
  }
}

function normalizeEncoding(enc) {
  var nenc = _normalizeEncoding(enc);
  if ("string" !== typeof nenc && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc);
  return nenc || enc;
}

function StringDecoder(encoding) {
  this.encoding = normalizeEncoding(encoding);
  var nb;
  switch (this.encoding) {
   case "utf16le":
    this.text = utf16Text;
    this.end = utf16End;
    nb = 4;
    break;

   case "utf8":
    this.fillLast = utf8FillLast;
    nb = 4;
    break;

   case "base64":
    this.text = base64Text;
    this.end = base64End;
    nb = 3;
    break;

   default:
    this.write = simpleWrite;
    this.end = simpleEnd;
    return;
  }
  this.lastNeed = 0;
  this.lastTotal = 0;
  this.lastChar = Buffer.allocUnsafe(nb);
}

(exports.StringDecoder = StringDecoder).prototype.write = function(buf) {
  if (0 === buf.length) return "";
  var r, i;
  if (this.lastNeed) {
    if (void 0 === (r = this.fillLast(buf))) return "";
    i = this.lastNeed;
    this.lastNeed = 0;
  } else i = 0;
  return i < buf.length ? r ? r + this.text(buf, i) : this.text(buf, i) : r || "";
};

StringDecoder.prototype.end = utf8End;

StringDecoder.prototype.text = utf8Text;

StringDecoder.prototype.fillLast = function(buf) {
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  this.lastNeed -= buf.length;
};

function utf8CheckByte(byte) {
  return byte <= 127 ? 0 : byte >> 5 === 6 ? 2 : byte >> 4 === 14 ? 3 : byte >> 3 === 30 ? 4 : byte >> 6 === 2 ? -1 : -2;
}

function utf8CheckIncomplete(self, buf, i) {
  var j = buf.length - 1;
  if (j < i) return 0;
  var nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    nb > 0 && (self.lastNeed = nb - 1);
    return nb;
  }
  if (--j < i || -2 === nb) return 0;
  if ((nb = utf8CheckByte(buf[j])) >= 0) {
    nb > 0 && (self.lastNeed = nb - 2);
    return nb;
  }
  if (--j < i || -2 === nb) return 0;
  if ((nb = utf8CheckByte(buf[j])) >= 0) {
    nb > 0 && (2 === nb ? nb = 0 : self.lastNeed = nb - 3);
    return nb;
  }
  return 0;
}

function utf8CheckExtraBytes(self, buf, p) {
  if (128 !== (192 & buf[0])) {
    self.lastNeed = 0;
    return "\ufffd";
  }
  if (self.lastNeed > 1 && buf.length > 1) {
    if (128 !== (192 & buf[1])) {
      self.lastNeed = 1;
      return "\ufffd";
    }
    if (self.lastNeed > 2 && buf.length > 2 && 128 !== (192 & buf[2])) {
      self.lastNeed = 2;
      return "\ufffd";
    }
  }
}

function utf8FillLast(buf) {
  var p = this.lastTotal - this.lastNeed, r = utf8CheckExtraBytes(this, buf, p);
  if (void 0 !== r) return r;
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, p, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, p, 0, buf.length);
  this.lastNeed -= buf.length;
}

function utf8Text(buf, i) {
  var total = utf8CheckIncomplete(this, buf, i);
  if (!this.lastNeed) return buf.toString("utf8", i);
  var end = buf.length - ((this.lastTotal = total) - this.lastNeed);
  buf.copy(this.lastChar, 0, end);
  return buf.toString("utf8", i, end);
}

function utf8End(buf) {
  var r = buf && buf.length ? this.write(buf) : "";
  return this.lastNeed ? r + "\ufffd" : r;
}

function utf16Text(buf, i) {
  if ((buf.length - i) % 2 === 0) {
    var r = buf.toString("utf16le", i);
    if (r) {
      var c = r.charCodeAt(r.length - 1);
      if (c >= 55296 && c <= 56319) {
        this.lastNeed = 2;
        this.lastTotal = 4;
        this.lastChar[0] = buf[buf.length - 2];
        this.lastChar[1] = buf[buf.length - 1];
        return r.slice(0, -1);
      }
    }
    return r;
  }
  this.lastNeed = 1;
  this.lastTotal = 2;
  this.lastChar[0] = buf[buf.length - 1];
  return buf.toString("utf16le", i, buf.length - 1);
}

function utf16End(buf) {
  var r = buf && buf.length ? this.write(buf) : "";
  return this.lastNeed ? r + this.lastChar.toString("utf16le", 0, this.lastTotal - this.lastNeed) : r;
}

function base64Text(buf, i) {
  var n = (buf.length - i) % 3;
  if (0 === n) return buf.toString("base64", i);
  this.lastNeed = 3 - n;
  this.lastTotal = 3;
  if (1 === n) this.lastChar[0] = buf[buf.length - 1]; else {
    this.lastChar[0] = buf[buf.length - 2];
    this.lastChar[1] = buf[buf.length - 1];
  }
  return buf.toString("base64", i, buf.length - n);
}

function base64End(buf) {
  var r = buf && buf.length ? this.write(buf) : "";
  return this.lastNeed ? r + this.lastChar.toString("base64", 0, 3 - this.lastNeed) : r;
}

function simpleWrite(buf) {
  return buf.toString(this.encoding);
}

function simpleEnd(buf) {
  return buf && buf.length ? this.write(buf) : "";
}
},{"buffer":10}],43:[function(require,module,exports){
var Buffer = require("buffer").Buffer;

module.exports = function(buf) {
  if (buf instanceof Uint8Array) {
    if (0 === buf.byteOffset && buf.byteLength === buf.buffer.byteLength) return buf.buffer;
    if ("function" === typeof buf.buffer.slice) return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
  }
  if (Buffer.isBuffer(buf)) {
    for (var arrayCopy = new Uint8Array(buf.length), len = buf.length, i = 0; i < len; i++) arrayCopy[i] = buf[i];
    return arrayCopy.buffer;
  }
  throw new Error("Argument must be a Buffer");
};
},{"buffer":10}],44:[function(require,module,exports){
var Buffer = require("buffer").Buffer, UINT_32_MAX = Math.pow(2, 32);

exports.encodingLength = function() {
  return 8;
};

exports.encode = function(num, buf, offset) {
  buf = buf || Buffer.allocUnsafe(8);
  offset = offset || 0;
  var top = Math.floor(num / UINT_32_MAX), rem = num - top * UINT_32_MAX;
  buf.writeUInt32BE(top, offset);
  buf.writeUInt32BE(rem, offset + 4);
  return buf;
};

exports.decode = function(buf, offset) {
  var top = buf.readUInt32BE(offset = offset || 0), rem = buf.readUInt32BE(offset + 4);
  return top * UINT_32_MAX + rem;
};

exports.encode.bytes = 8;

exports.decode.bytes = 8;
},{"buffer":10}],45:[function(require,module,exports){
module.exports = wrappy;

function wrappy(fn, cb) {
  if (fn && cb) return wrappy(fn)(cb);
  if ("function" !== typeof fn) throw new TypeError("need wrapper function");
  Object.keys(fn).forEach(function(k) {
    wrapper[k] = fn[k];
  });
  return wrapper;
  function wrapper() {
    for (var args = new Array(arguments.length), i = 0; i < args.length; i++) args[i] = arguments[i];
    var ret = fn.apply(this, args), cb = args[args.length - 1];
    "function" === typeof ret && ret !== cb && Object.keys(cb).forEach(function(k) {
      ret[k] = cb[k];
    });
    return ret;
  }
}
},{}],46:[function(require,module,exports){
"use strict";

var pump = require("pump"), MP4Remuxer = require("./mp4-remuxer"), EBMLRemuxer = require("./ebml-remuxer"), MediaElementWrapper = require("mediasource");

function VideoStream(file, mediaElem, opts) {
  var self = this;
  if (!(this instanceof VideoStream)) return new VideoStream(file, mediaElem, opts);
  opts = opts || {};
  self.detailedError = null;
  self._elem = mediaElem;
  self._elemWrapper = new MediaElementWrapper(mediaElem, opts);
  self._waitingFired = !1;
  self._seekCoercion = !1;
  self._sbQuotaError = null;
  self._trackMeta = null;
  self._file = file;
  self._tracks = null;
  self._type = opts.type;
  self._fpTick = 0;
  self._startTime = opts.startTime;
  "none" !== self._elem.preload && self._createMuxer(opts);
  self.flushSourceBuffers = opts.sbflush ? self._flushSourceBuffers : function() {
    if (self._sbQuotaError) {
      var s = file.streamer;
      if (s && "stalled" === s.state) {
        d && console.warn("Forcing pump on quota-error while stalled...");
        self._enqueueForcePump(Math.max(.3, self._elem.currentTime - 1.2));
      }
    }
  };
  self._onError = function(err) {
    self.detailedError = self._elemWrapper.detailedError || err;
    d && console.error("VideoStream Error.", err, self.detailedError);
    self.destroy();
  };
  self._onWaiting = function() {
    self._waitingFired = !0;
    if (self._muxer) {
      if (self._tracks) {
        self._pump(0 | self._startTime);
        self._startTime = null;
      }
    } else self._createMuxer(opts);
  };
  self._elem.autoplay && (self._elem.preload = "auto");
  self._elem.addEventListener("waiting", self._onWaiting);
  self._elem.addEventListener("error", self._onError);
}

(module.exports = VideoStream).prototype = Object.create(null);

VideoStream.prototype._createMuxer = function(opts) {
  var self = this;
  self._muxer = new ({
    WebM: 1,
    Matroska: 1
  }[self._type] ? EBMLRemuxer : MP4Remuxer)(self._file, opts);
  self._muxer.once("ready", function(data) {
    self._tracks = data.map(function(trackData) {
      var mediaSource = self.createWriteStream(trackData.mime), track = {
        muxed: null,
        mediaSource: mediaSource,
        initFlushed: !1,
        onInitFlushed: null
      };
      mediaSource.write(trackData.init, function(err) {
        track.initFlushed = !0;
        track.onInitFlushed && track.onInitFlushed(err);
      });
      return track;
    });
    if (self._waitingFired || "auto" === self._elem.preload) {
      self._pump(0 | self._startTime);
      self._startTime = null;
    }
  });
  self._muxer.on("error", function(err) {
    self.error(err);
  });
};

VideoStream.prototype.error = function(err) {
  var ew = this._elemWrapper;
  if (ew) {
    var ms = ew._mediaSource, sb = ms && ms.sourceBuffers, cb = ew.error.bind(ew, err);
    later(cb);
    if (sb && sb.length) for (var i = sb.length; i--; ) this.onSourceBufferUpdateEnded(sb[i], cb);
  }
};

VideoStream.prototype.createWriteStream = function(obj) {
  var videoStream = this, videoFile = videoStream._file, mediaSource = videoStream._elemWrapper.createWriteStream(obj), csb = mediaSource._createSourceBuffer, mediaSourceDestroy = mediaSource.destroy, trace = localStorage.vsd ? function(time, sb, chunk) {
    for (var start = time, end = time + chunk.duration, b = [], i = 0; i < sb.buffered.length; ++i) b.push(sb.buffered.start(i) + "-" + sb.buffered.end(i));
    console.debug("ranges(%s), timecode=%s, duration=%s, time=%s, start=%s(%s), end=%s(%s)", b.join(", "), chunk.timecode, chunk.duration, time, start, sb.appendWindowStart, end, sb.appendWindowEnd, sb.timestampOffset, chunk.seektime);
  } : null;
  mediaSource._createSourceBuffer = function() {
    try {
      return csb.apply(this, arguments);
    } catch (ex) {
      ex = String(ex.message || ex);
      vsNT(this.destroy.bind(this, ex));
    }
  };
  mediaSource._write = function(chunk, encoding, cb) {
    if (!this.destroyed) {
      var self = this, sb = this._sourceBuffer;
      if (sb && !sb.updating) try {
        if (chunk.duration) {
          var time = sb.buffered.length ? sb.buffered.end(0) : 0;
          trace && trace(time, sb, chunk);
          void 0 !== chunk.seektime && (!time || time > chunk.seektime) && (time = chunk.seektime);
          sb.timestampOffset = time;
        }
        sb.appendBuffer(new Uint8Array(chunk).buffer);
        this._cb = cb;
        return;
      } catch (ex) {
        d > 1 && console.debug("Caught %s", ex.name, ex);
        if ("QuotaExceededError" !== ex.name) return self.destroy(ex);
        videoStream._sbQuotaError = !0;
        videoStream.flushSourceBuffers(-1);
      }
      this._cb = function(err) {
        if (err) return cb(err);
        self._write(chunk, encoding, cb);
      };
    }
  };
  mediaSource.destroy = function(err) {
    try {
      mediaSourceDestroy.apply(mediaSource, arguments);
    } catch (ex) {
      var sb = this._sourceBuffer;
      d && console.debug('Caught exception ("%s")', ex.name, sb && sb.updating, sb, ex);
      if (!sb || !sb.updating) throw ex;
      err && this.emit("error", err);
      this.emit("close");
    }
  };
  mediaSource._flow = function() {
    if (this._cb && !this.destroyed) {
      var sb = this._sourceBuffer;
      if (sb && !sb.updating) {
        if (videoFile.throttle && "open" === this._mediaSource.readyState && sb.buffered.length && sb.buffered.end(sb.buffered.length - 1) - this._elem.currentTime > this._bufferDuration) return;
        var cb = this._cb;
        this._cb = null;
        cb();
      }
    }
  };
  mediaSource.on("error", function(err) {
    videoStream.error(err);
  });
  return mediaSource;
};

VideoStream.prototype._pump = function(time) {
  try {
    var video = this._elem;
    (0 | time) > 0 && (video.currentTime = time);
    time = video.currentTime;
    "WebM" === this._type && this.withinBufferedRange(time + 1) ? d && console.debug("Ignoring pump within buffered range.", time) : this._tryPump(time);
  } catch (ex) {
    this.error(ex);
  }
};

VideoStream.prototype._tryPump = function(time) {
  var i, m, self = this, video = self._elem, muxer = self._muxer, muxed = muxer.seek(time), timeStampFixup = muxer._seekTimeFixup;
  d && console.debug("Seeking to %s, fixup=%s", time, timeStampFixup);
  if (time - timeStampFixup > .4 || 0 === timeStampFixup) {
    if (self._seekCoercion !== timeStampFixup) {
      d && console.debug("Applying timestamp fixup...", time, timeStampFixup);
      for (i = muxed.length; i--; ) {
        (m = muxed[i]).inStream && m.inStream.destroy();
        m.outStream && m.outStream.destroy();
      }
      this._tryPump(video.currentTime = self._seekCoercion = timeStampFixup);
      return;
    }
    d && console.debug("Seek coercion, waiting for more data...");
  }
  self._tracks.forEach(function(track, i) {
    function pumpTrack() {
      if (track.muxed) {
        var ms = track.mediaSource, sb = ms && ms._sourceBuffer;
        track.muxed.destroy();
        track.mediaSource = self.createWriteStream(ms);
        if (sb) {
          "audio/mpeg" === ms._type && (sb.timestampOffset = time);
          void 0 !== timeStampFixup && self.removeBuffered(sb, time);
        }
      }
      track.muxed = muxed[i];
      pump(track.muxed, track.mediaSource);
    }
    track.initFlushed ? pumpTrack() : track.onInitFlushed = function(err) {
      err ? self.error(err) : pumpTrack();
    };
  });
};

VideoStream.prototype.destroy = function() {
  if (!this.destroyed) {
    this.destroyed = !0;
    this._elem.removeEventListener("waiting", this._onWaiting);
    this._elem.removeEventListener("error", this._onError);
    if (this._tracks) {
      for (var track, tracks = this._tracks, destroy = function(track, instance) {
        try {
          track[instance] && track[instance].destroy();
        } catch (ex) {
          console.warn(track, instance, ex);
        }
      }, i = tracks.length; i--; ) {
        destroy(track = tracks[i], "mediaSource");
        destroy(track, "muxed");
      }
      this._tracks = !1;
    }
    String(this._elem.src).startsWith("blob:") && URL.revokeObjectURL(this._elem.src);
    this._elem.removeAttribute("src");
    this._elem = !1;
    this._file = !1;
    this._elemWrapper = !1;
  }
};

VideoStream.prototype.forEachSourceBuffer = function(cb) {
  if (this._tracks) for (var sb, startRange, endRange, ms, src, currentTime = this._elem.currentTime, i = this._tracks.length; i--; ) {
    ms = (src = this._tracks[i].mediaSource || !1)._mediaSource;
    sb = src._sourceBuffer;
    try {
      startRange = sb.buffered.length ? sb.buffered.start(0) : 0;
      endRange = sb.buffered.length ? sb.buffered.end(sb.buffered.length - 1) : 0;
      cb.call(this, sb, startRange, endRange, currentTime, ms);
    } catch (ex) {
      console.debug(ex);
    }
  }
};

VideoStream.prototype.onSourceBufferUpdateEnded = function(sb, cb) {
  if (!sb.updating) return queueMicrotask(cb);
  sb.addEventListener("updateend", function end() {
    sb.removeEventListener("updateend", end);
    queueMicrotask(cb);
  });
};

VideoStream.prototype._enqueueForcePump = function(offset) {
  if (++this._fpTick > 3) return this._forcePump(offset);
  delay("vs.force-track-pump", this._forcePump.bind(this, offset), 2600);
};

VideoStream.prototype._forcePump = function(offset) {
  function pump() {
    var f = self._file;
    if (!--step && f) {
      d && self.forEachBufferedRanges(dump);
      if (f.playing) {
        f.throttle = 0;
        self._pump(offset);
      }
    }
  }
  var self = this, res = 0, step = 0;
  self._fpTick = 0;
  delay.cancel("vs.force-track-pump");
  if (this._tracks) for (var ms, sb, t = this._tracks, i = t.length; i--; ) if ((sb = (ms = t[i].mediaSource) && ms._sourceBuffer) && ms) {
    ++step;
    ms._cb = null;
    ms.destroy();
    if (sb.updating) {
      res = -1;
      this.onSourceBufferUpdateEnded(sb, this.removeBuffered.bind(this, sb, null, pump));
    } else try {
      res |= this.removeBuffered(sb, null, pump);
    } catch (ex) {
      --step;
      dump(ex);
    }
  }
  step || pump(++step);
  return res;
};

VideoStream.prototype.removeBuffered = function(sb, currentTime, callback) {
  if (sb.buffered.length) {
    var startRange = sb.buffered.start(0), endRange = sb.buffered.end(sb.buffered.length - 1);
    d && console.debug("Removing source buffered range (%s:%s-%s)", currentTime, startRange, endRange);
    currentTime > startRange && currentTime < endRange && (startRange = currentTime);
    tryCatch(sb.remove.bind(sb, startRange, endRange), d > 2 && dump)();
    callback && this.onSourceBufferUpdateEnded(sb, callback);
    return !0;
  }
  callback && queueMicrotask(callback);
  return !1;
};

VideoStream.prototype.withinBufferedRange = function(time, sb) {
  var ranges = this.getBufferedRange(sb);
  return time > ranges[0] && ranges[1] > time;
};

VideoStream.prototype.getBufferedRange = function(sb) {
  if (!sb) {
    var tk = this._tracks, ms = tk && tk[0].mediaSource;
    sb = ms && ms._sourceBuffer;
  }
  return !(!sb || !sb.buffered.length) && [ sb.buffered.start(0), sb.buffered.end(sb.buffered.length - 1) ];
};

VideoStream.prototype.findTimeGAPs = function() {
  var gap = {}, res = 0;
  this.forEachBufferedRanges(function(sb, sr, er, ct, ms, tid, bid) {
    if (bid && !gap[tid]) {
      gap[tid] = res = 1;
      console.warn("SourceBuffer has a gap!", [ sb ], [ ms ]);
    }
    gap[tid] && console.debug("buffer gap on track%s(%s), sr=%s, er=%s, ct=%s", tid, bid, sr, er, ct);
  });
  return res;
};

VideoStream.prototype.forEachBufferedRanges = tryCatch(function(cb) {
  if (this._tracks) for (var j, sb, startRange, endRange, ms, src, currentTime = this._elem.currentTime, trackId = this._tracks.length; trackId--; ) {
    ms = (src = this._tracks[trackId].mediaSource || !1)._mediaSource;
    for (j = (sb = src._sourceBuffer) && sb.buffered.length; j--; ) try {
      endRange = sb.buffered.end(j);
      startRange = sb.buffered.start(j);
      cb.call(this, sb, startRange, endRange, currentTime, ms, trackId, j);
    } catch (ex) {
      console.debug(ex);
    }
  }
});

VideoStream.prototype._flushSourceBuffers = function(mode, track) {
  var res = !1;
  this.forEachSourceBuffer(function(sb, startRange, endRange, currentTime, mediaSource) {
    d && console.debug("[VideoStream.flushSourceBuffers] ct=%s sr=%s er=%s", currentTime, startRange, endRange, sb.updating, mediaSource.readyState, mode, sb);
    if (!sb.updating) {
      if (-1 !== mode) endRange > currentTime ? startRange = Math.max(currentTime + 1, startRange) : currentTime >= startRange && currentTime <= endRange && (endRange = currentTime - 1); else {
        endRange >= currentTime && (endRange = currentTime);
        if (startRange >= currentTime) return;
      }
      if (endRange > startRange && endRange - startRange > 1) {
        sb.remove(startRange, endRange);
        track && this.onSourceBufferUpdateEnded(track);
        ++res;
        d && console.log("[VideoStream.flushSourceBuffers] remove took place", startRange, endRange);
      }
    }
  });
  return res;
};

Object.defineProperty(VideoStream.prototype, "bufTime", {
  get: function() {
    var time = 0;
    if (this._muxer instanceof MP4Remuxer) {
      var trak = this._muxer._tracks[0] || !1, smpl = trak && trak.samples[trak.currSample] || !1;
      return (time = (smpl.dts + smpl.duration) / trak.timeScale) - this._elem.currentTime;
    }
    if (this._muxer instanceof EBMLRemuxer) for (var mediaSourceStream, i = Object(this._tracks).length; i--; ) "open" === ((mediaSourceStream = this._tracks[i].mediaSource) && mediaSourceStream._mediaSource).readyState && (time = Math.max(time, mediaSourceStream._getBufferDuration()));
    return time;
  }
});
},{"./ebml-remuxer":5,"./mp4-remuxer":6,"mediasource":17,"pump":27}]},{},[3]);
